internal CmdletParameterBinderController(Cmdlet cmdlet, CommandMetadata commandMetadata, ParameterBinderBase parameterBinder)
     : base(cmdlet.MyInvocation, cmdlet.Context, parameterBinder)
 {
     this._warningSet = new HashSet<string>();
     this._useDefaultParameterBinding = true;
     this._delayBindScriptBlocks = new Dictionary<MergedCompiledCommandParameter, DelayedScriptBlockArgument>();
     this._defaultParameterValues = new Dictionary<string, CommandParameterInternal>(StringComparer.OrdinalIgnoreCase);
     if (cmdlet == null)
     {
         throw PSTraceSource.NewArgumentNullException("cmdlet");
     }
     if (commandMetadata == null)
     {
         throw PSTraceSource.NewArgumentNullException("commandMetadata");
     }
     this.Command = cmdlet;
     this._commandRuntime = (MshCommandRuntime)cmdlet.CommandRuntime;
     this._commandMetadata = commandMetadata;
     if (commandMetadata.ImplementsDynamicParameters)
     {
         base.UnboundParameters = base.BindableParameters.ReplaceMetadata(commandMetadata.StaticCommandParameterMetadata);
         base.BindableParameters.GenerateParameterSetMappingFromMetadata(commandMetadata.DefaultParameterSetName);
     }
     else
     {
         base._bindableParameters = commandMetadata.StaticCommandParameterMetadata;
         base.UnboundParameters = new List<MergedCompiledCommandParameter>(base._bindableParameters.BindableParameters.Values);
     }
 }
예제 #2
0
 private HelpCommentsParser(CommandInfo commandInfo, List<string> parameterDescriptions)
 {
     this._sections = new CommentHelpInfo();
     this._parameters = new Dictionary<string, string>();
     this._examples = new List<string>();
     this._inputs = new List<string>();
     this._outputs = new List<string>();
     this._links = new List<string>();
     FunctionInfo info = commandInfo as FunctionInfo;
     if (info != null)
     {
         this.scriptBlock = info.ScriptBlock;
         this.commandName = info.Name;
     }
     else
     {
         ExternalScriptInfo info2 = commandInfo as ExternalScriptInfo;
         if (info2 != null)
         {
             this.scriptBlock = info2.ScriptBlock;
             this.commandName = info2.Path;
         }
     }
     this.commandMetadata = commandInfo.CommandMetadata;
     this.parameterDescriptions = parameterDescriptions;
 }
예제 #3
0
        /// <summary>
        /// This method constructs a string representing the CmdletBinding attribute of the command
        /// specified by <paramref name="commandMetadata"/>.
        /// </summary>
        /// <param name="commandMetadata">
        /// An instance of CommandMetadata representing a command.
        /// </param>
        /// <returns>
        /// A string representing the CmdletBinding attribute of the command.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// commandMetadata is null.
        /// </exception>
        public static string GetCmdletBindingAttribute(CommandMetadata commandMetadata)
        {
            if (null == commandMetadata)
            {
                throw PSTraceSource.NewArgumentNullException("commandMetaData");
            }

            return(commandMetadata.GetDecl());
        }
예제 #4
0
        /// <summary>
        /// This method constructs a string representing the command specified by <paramref name="commandMetadata"/>.
        /// The returned string is a ScriptBlock which can be used to configure a Cmdlet/Function in a Runspace.
        /// </summary>
        /// <param name="commandMetadata">
        /// An instance of CommandMetadata representing a command.
        /// </param>
        /// <param name="helpComment">
        /// The string to be used as the help comment.
        /// </param>
        /// <param name="generateDynamicParameters">
        /// A boolean that determines whether the generated proxy command should include the functionality required
        /// to proxy dynamic parameters of the underlying command.
        /// </param>
        /// <returns>
        /// A string representing Command ScriptBlock.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// commandMetadata is null.
        /// </exception>
        public static string Create(CommandMetadata commandMetadata, string helpComment, bool generateDynamicParameters)
        {
            if (commandMetadata == null)
            {
                throw PSTraceSource.NewArgumentNullException("commandMetaData");
            }

            return(commandMetadata.GetProxyCommand(helpComment, generateDynamicParameters));
        }
예제 #5
0
        /// <summary>
        /// This method constructs a string representing the command specified by <paramref name="commandMetadata"/>.
        /// The returned string is a ScriptBlock which can be used to configure a Cmdlet/Function in a Runspace.
        /// </summary>
        /// <param name="commandMetadata">
        /// An instance of CommandMetadata representing a command.
        /// </param>
        /// <param name="helpComment">
        /// The string to be used as the help comment.
        /// </param>
        /// <returns>
        /// A string representing Command ScriptBlock.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// commandMetadata is null.
        /// </exception>
        public static string Create(CommandMetadata commandMetadata, string helpComment)
        {
            if (commandMetadata == null)
            {
                throw PSTraceSource.NewArgumentNullException("commandMetaData");
            }

            return(commandMetadata.GetProxyCommand(helpComment, true));
        }
예제 #6
0
        /// <summary>
        /// This method constructs a string representing the process block of the command
        /// specified by <paramref name="commandMetadata"/>.  The returned string only contains the
        /// script, it is not enclosed in "process { }".
        /// </summary>
        /// <param name="commandMetadata">
        /// An instance of CommandMetadata representing a command.
        /// </param>
        /// <returns>
        /// A string representing the process block of the command.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// commandMetadata is null.
        /// </exception>
        public static string GetProcess(CommandMetadata commandMetadata)
        {
            if (commandMetadata == null)
            {
                throw PSTraceSource.NewArgumentNullException("commandMetaData");
            }

            return(commandMetadata.GetProcessBlock());
        }
예제 #7
0
        /// <summary>
        /// This method constructs a string representing the command specified by <paramref name="commandMetadata"/>.
        /// The returned string is a ScriptBlock which can be used to configure a Cmdlet/Function in a Runspace.
        /// </summary>
        /// <param name="commandMetadata">
        /// An instance of CommandMetadata representing a command.
        /// </param>
        /// <returns>
        /// A string representing Command ScriptBlock.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// commandMetadata is null.
        /// </exception>
        public static string Create(CommandMetadata commandMetadata)
        {
            if (null == commandMetadata)
            {
                throw PSTraceSource.NewArgumentNullException("commandMetaData");
            }

            return(commandMetadata.GetProxyCommand("", true));
        }
예제 #8
0
        public static string GetParamBlock(CommandMetadata commandMetadata)
        {
            if (null == commandMetadata)
            {
                throw PSTraceSource.NewArgumentNullException("commandMetaData");
            }

            return(commandMetadata.GetParamBlock());
        }
예제 #9
0
        public static Dictionary <string, ParameterMetadata> GetParameterMetadata(Type type)
        {
            if (null == type)
            {
                throw PSTraceSource.NewArgumentNullException("type");
            }
            CommandMetadata metadata = new CommandMetadata(type);
            Dictionary <string, ParameterMetadata> parameters = metadata.Parameters;

            metadata = null;
            return(parameters);
        }
예제 #10
0
 public MergedCommandParameterMetadata GetParameterMetadata(ScriptBlock scriptBlock)
 {
     if (this._parameterMetadata == null)
     {
         lock (this._syncObject)
         {
             if (this._parameterMetadata == null)
             {
                 CommandMetadata metadata = new CommandMetadata(scriptBlock, "", LocalPipeline.GetExecutionContextFromTLS());
                 this._parameterMetadata = metadata.StaticCommandParameterMetadata;
             }
         }
     }
     return(this._parameterMetadata);
 }
예제 #11
0
 public CommandMetadata(CommandMetadata other)
 {
     this._commandName = string.Empty;
     this._defaultParameterSetName = "__AllParameterSets";
     this._positionalBinding = true;
     this._helpUri = string.Empty;
     this._remotingCapability = System.Management.Automation.RemotingCapability.PowerShell;
     this._confirmImpact = System.Management.Automation.ConfirmImpact.Medium;
     this._otherAttributes = new Collection<Attribute>();
     if (other == null)
     {
         throw PSTraceSource.NewArgumentNullException("other");
     }
     this._commandName = other._commandName;
     this._confirmImpact = other._confirmImpact;
     this._defaultParameterSetFlag = other._defaultParameterSetFlag;
     this._defaultParameterSetName = other._defaultParameterSetName;
     this._implementsDynamicParameters = other._implementsDynamicParameters;
     this._supportsShouldProcess = other._supportsShouldProcess;
     this._supportsPaging = other._supportsPaging;
     this._supportsTransactions = other._supportsTransactions;
     this.CommandType = other.CommandType;
     this._wrappedAnyCmdlet = other._wrappedAnyCmdlet;
     this._wrappedCommand = other._wrappedCommand;
     this._wrappedCommandType = other._wrappedCommandType;
     this._parameters = new Dictionary<string, ParameterMetadata>(other.Parameters.Count, StringComparer.OrdinalIgnoreCase);
     if (other.Parameters != null)
     {
         foreach (KeyValuePair<string, ParameterMetadata> pair in other.Parameters)
         {
             this._parameters.Add(pair.Key, new ParameterMetadata(pair.Value));
         }
     }
     if (other._otherAttributes == null)
     {
         this._otherAttributes = null;
     }
     else
     {
         this._otherAttributes = new Collection<Attribute>(new List<Attribute>(other._otherAttributes.Count));
         foreach (Attribute attribute in other._otherAttributes)
         {
             this._otherAttributes.Add(attribute);
         }
     }
     this.staticCommandParameterMetadata = null;
 }
예제 #12
0
 public CommandMetadata(CommandMetadata other)
 {
     this._commandName             = string.Empty;
     this._defaultParameterSetName = "__AllParameterSets";
     this._positionalBinding       = true;
     this._helpUri            = string.Empty;
     this._remotingCapability = System.Management.Automation.RemotingCapability.PowerShell;
     this._confirmImpact      = System.Management.Automation.ConfirmImpact.Medium;
     this._otherAttributes    = new Collection <Attribute>();
     if (other == null)
     {
         throw PSTraceSource.NewArgumentNullException("other");
     }
     this._commandName                 = other._commandName;
     this._confirmImpact               = other._confirmImpact;
     this._defaultParameterSetFlag     = other._defaultParameterSetFlag;
     this._defaultParameterSetName     = other._defaultParameterSetName;
     this._implementsDynamicParameters = other._implementsDynamicParameters;
     this._supportsShouldProcess       = other._supportsShouldProcess;
     this._supportsPaging              = other._supportsPaging;
     this._supportsTransactions        = other._supportsTransactions;
     this.CommandType         = other.CommandType;
     this._wrappedAnyCmdlet   = other._wrappedAnyCmdlet;
     this._wrappedCommand     = other._wrappedCommand;
     this._wrappedCommandType = other._wrappedCommandType;
     this._parameters         = new Dictionary <string, ParameterMetadata>(other.Parameters.Count, StringComparer.OrdinalIgnoreCase);
     if (other.Parameters != null)
     {
         foreach (KeyValuePair <string, ParameterMetadata> pair in other.Parameters)
         {
             this._parameters.Add(pair.Key, new ParameterMetadata(pair.Value));
         }
     }
     if (other._otherAttributes == null)
     {
         this._otherAttributes = null;
     }
     else
     {
         this._otherAttributes = new Collection <Attribute>(new List <Attribute>(other._otherAttributes.Count));
         foreach (Attribute attribute in other._otherAttributes)
         {
             this._otherAttributes.Add(attribute);
         }
     }
     this.staticCommandParameterMetadata = null;
 }
예제 #13
0
        private HelpCommentsParser(CommandInfo commandInfo, List <List <Token> > parameterComments)
        {
            switch (commandInfo)
            {
            case FunctionInfo functionInfo:
                this.scriptBlock = functionInfo.ScriptBlock;
                this.commandName = functionInfo.Name;
                break;

            case ExternalScriptInfo externalScriptInfo:
                this.scriptBlock = externalScriptInfo.ScriptBlock;
                this.commandName = externalScriptInfo.Path;
                break;
            }
            this.commandMetadata   = commandInfo.CommandMetadata;
            this.parameterComments = parameterComments;
        }
예제 #14
0
        internal static Collection <CommandParameterSetInfo> GetParameterMetadata(CommandMetadata metadata, MergedCommandParameterMetadata parameterMetadata)
        {
            Collection <CommandParameterSetInfo> result = new Collection <CommandParameterSetInfo>();

            if (parameterMetadata != null)
            {
                if (parameterMetadata.ParameterSetCount == 0)
                {
                    const string parameterSetName = ParameterAttribute.AllParameterSets;

                    result.Add(
                        new CommandParameterSetInfo(
                            parameterSetName,
                            false,
                            uint.MaxValue,
                            parameterMetadata));
                }
                else
                {
                    int parameterSetCount = parameterMetadata.ParameterSetCount;
                    for (int index = 0; index < parameterSetCount; ++index)
                    {
                        uint currentFlagPosition = (uint)0x1 << index;

                        // Get the parameter set name
                        string parameterSetName = parameterMetadata.GetParameterSetName(currentFlagPosition);

                        // Is the parameter set the default?
                        bool isDefaultParameterSet = (currentFlagPosition & metadata.DefaultParameterSetFlag) != 0;

                        result.Add(
                            new CommandParameterSetInfo(
                                parameterSetName,
                                isDefaultParameterSet,
                                currentFlagPosition,
                                parameterMetadata));
                    }
                }
            }

            return(result);
        }
        /// <summary>
        /// Initializes the cmdlet parameter binder controller for
        /// the specified cmdlet and engine context
        /// </summary>
        /// 
        /// <param name="cmdlet">
        /// The cmdlet that the parameters will be bound to.
        /// </param>
        /// 
        /// <param name="commandMetadata">
        /// The metadata about the cmdlet.
        /// </param>
        /// 
        /// <param name="parameterBinder">
        /// The default parameter binder to use.
        /// </param>
        /// 
        internal CmdletParameterBinderController(
            Cmdlet cmdlet,
            CommandMetadata commandMetadata,
            ParameterBinderBase parameterBinder)
            : base(
                cmdlet.MyInvocation,
                cmdlet.Context,
                parameterBinder)
        {
            if (cmdlet == null)
            {
                throw PSTraceSource.NewArgumentNullException("cmdlet");
            }

            if (commandMetadata == null)
            {
                throw PSTraceSource.NewArgumentNullException("commandMetadata");
            }

            this.Command = cmdlet;
            _commandRuntime = (MshCommandRuntime)cmdlet.CommandRuntime;
            _commandMetadata = commandMetadata;

            // Add the static parameter metadata to the bindable parameters
            // And add them to the unbound parameters list

            if (commandMetadata.ImplementsDynamicParameters)
            {
                // ReplaceMetadata makes a copy for us, so we can use that collection as is.
                this.UnboundParameters = this.BindableParameters.ReplaceMetadata(commandMetadata.StaticCommandParameterMetadata);
            }
            else
            {
                _bindableParameters = commandMetadata.StaticCommandParameterMetadata;

                // Must make a copy of the list because we'll modify it.
                this.UnboundParameters = new List<MergedCompiledCommandParameter>(_bindableParameters.BindableParameters.Values);
            }
        }
예제 #16
0
 public CommandMetadata(CommandMetadata other)
 {
     this.commandName                 = other != null ? other.commandName : throw CommandMetadata.tracer.NewArgumentNullException(nameof(other));
     this.confirmImpact               = other.confirmImpact;
     this.defaultParameterSetFlag     = other.defaultParameterSetFlag;
     this.defaultParameterSetName     = other.defaultParameterSetName;
     this.implementsDynamicParameters = other.implementsDynamicParameters;
     this.supportsShouldProcess       = other.supportsShouldProcess;
     this.supportsTransactions        = other.supportsTransactions;
     this.type               = other.type;
     this.wrappedAnyCmdlet   = other.wrappedAnyCmdlet;
     this.wrappedCommand     = other.wrappedCommand;
     this.wrappedCommandType = other.wrappedCommandType;
     if (other.externalParameterMetadata == null)
     {
         this.externalParameterMetadata = (Dictionary <string, ParameterMetadata>)null;
     }
     else
     {
         this.externalParameterMetadata = new Dictionary <string, ParameterMetadata>(other.externalParameterMetadata.Count, (IEqualityComparer <string>)StringComparer.OrdinalIgnoreCase);
         foreach (KeyValuePair <string, ParameterMetadata> keyValuePair in other.externalParameterMetadata)
         {
             this.externalParameterMetadata.Add(keyValuePair.Key, new ParameterMetadata(keyValuePair.Value));
         }
     }
     if (other.otherAttributes == null)
     {
         this.otherAttributes = (Collection <Attribute>)null;
     }
     else
     {
         this.otherAttributes = new Collection <Attribute>((IList <Attribute>) new List <Attribute>(other.otherAttributes.Count));
         foreach (Attribute otherAttribute in other.otherAttributes)
         {
             this.otherAttributes.Add(otherAttribute);
         }
     }
     this.staticCommandParameterMetadata = (MergedCommandParameterMetadata)null;
 }
예제 #17
0
 internal void SetScriptBlock(ScriptBlock function, bool force)
 {
     if (function == null)
     {
         throw FunctionInfo.tracer.NewArgumentNullException(nameof(function));
     }
     if ((this.options & ScopedItemOptions.Constant) != ScopedItemOptions.None)
     {
         SessionStateUnauthorizedAccessException unauthorizedAccessException = new SessionStateUnauthorizedAccessException(this.Name, SessionStateCategory.Function, "FunctionIsConstant");
         FunctionInfo.tracer.TraceException((Exception)unauthorizedAccessException);
         throw unauthorizedAccessException;
     }
     if (!force && (this.options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None)
     {
         SessionStateUnauthorizedAccessException unauthorizedAccessException = new SessionStateUnauthorizedAccessException(this.Name, SessionStateCategory.Function, "FunctionIsReadOnly");
         FunctionInfo.tracer.TraceException((Exception)unauthorizedAccessException);
         throw unauthorizedAccessException;
     }
     this._function = function;
     this.SetModule(function.Module);
     this.commandMetadata          = (CommandMetadata)null;
     this.parameterSets            = (ReadOnlyCollection <CommandParameterSetInfo>)null;
     this._externalCommandMetadata = (CommandMetadata)null;
 }
예제 #18
0
 private void GenerateCommandProxy(TextWriter writer, CommandMetadata commandMetadata)
 {
     if (writer == null)
     {
         throw PSTraceSource.NewArgumentNullException("writer");
     }
     string str = CommandMetadata.EscapeSingleQuotedString(commandMetadata.Name);
     string str2 = this.EscapeFunctionNameForRemoteHelp(commandMetadata.Name);
     object[] arg = new object[9];
     arg[0] = str;
     arg[1] = str2;
     arg[2] = commandMetadata.GetDecl();
     arg[3] = commandMetadata.GetParamBlock();
     arg[5] = commandMetadata.WrappedCommandType;
     arg[6] = ProxyCommand.GetProcess(commandMetadata);
     arg[7] = ProxyCommand.GetEnd(commandMetadata);
     arg[8] = commandMetadata.WrappedAnyCmdlet;
     writer.Write("\r\n& $script:SetItem 'function:script:{0}' `\r\n{{\r\n    param(\r\n    {3})\r\n\r\n    Begin {{\r\n        try {{\r\n            $positionalArguments = & $script:NewObject collections.arraylist\r\n            foreach ($parameterName in $PSBoundParameters.BoundPositionally)\r\n            {{\r\n                $null = $positionalArguments.Add( $PSBoundParameters[$parameterName] )\r\n                $null = $PSBoundParameters.Remove($parameterName)\r\n            }}\r\n            $positionalArguments.AddRange($args)\r\n\r\n            $clientSideParameters = Get-PSImplicitRemotingClientSideParameters $PSBoundParameters ${8}\r\n\r\n            $scriptCmd = {{ & $script:InvokeCommand `\r\n                            @clientSideParameters `\r\n                            -HideComputerName `\r\n                            -Session (Get-PSImplicitRemotingSession -CommandName '{0}') `\r\n                            -Arg ('{0}', $PSBoundParameters, $positionalArguments) `\r\n                            -Script {{ param($name, $boundParams, $unboundParams) & $name @boundParams @unboundParams }} `\r\n                         }}\r\n\r\n            $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)\r\n            $steppablePipeline.Begin($myInvocation.ExpectingInput, $ExecutionContext)\r\n        }} catch {{\r\n            throw\r\n        }}\r\n    }}\r\n    Process {{ {6} }}\r\n    End {{ {7} }}\r\n\r\n    # .ForwardHelpTargetName {1}\r\n    # .ForwardHelpCategory {5}\r\n    # .RemoteHelpRunspace PSSession\r\n}}\r\n        ", arg);
 }
예제 #19
0
        private CommandMetadata GetCommandMetadata(CommonCmdletMetadata cmdletMetadata)
        {
            string defaultParameterSetName = null;
            StaticCmdletMetadataCmdletMetadata staticCmdletMetadata = cmdletMetadata as StaticCmdletMetadataCmdletMetadata;
            if (staticCmdletMetadata != null)
            {
                if (!string.IsNullOrEmpty(staticCmdletMetadata.DefaultCmdletParameterSet))
                {
                    defaultParameterSetName = staticCmdletMetadata.DefaultCmdletParameterSet;
                }
            }

            var confirmImpact = System.Management.Automation.ConfirmImpact.None;
            if (cmdletMetadata.ConfirmImpactSpecified)
            {
                confirmImpact = (System.Management.Automation.ConfirmImpact)(int)cmdletMetadata.ConfirmImpact;
            }

            Dictionary<string, ParameterMetadata> parameters = new Dictionary<string, ParameterMetadata>(StringComparer.OrdinalIgnoreCase);

            CommandMetadata commandMetadata = new CommandMetadata(
                                   name: this.GetCmdletName(cmdletMetadata),
                            commandType: CommandTypes.Cmdlet,
                       isProxyForCmdlet: true,
                defaultParameterSetName: defaultParameterSetName, // this can only be figured out for static cmdlets - instance cmdlets have to set that separately
                  supportsShouldProcess: confirmImpact != System.Management.Automation.ConfirmImpact.None,
                          confirmImpact: confirmImpact,
                         supportsPaging: false,
                   supportsTransactions: false,
                      positionalBinding: false,
                             parameters: parameters);

            if (!string.IsNullOrEmpty(cmdletMetadata.HelpUri))
            {
                commandMetadata.HelpUri = cmdletMetadata.HelpUri;
            }

            return commandMetadata;
        }
예제 #20
0
 public CommandMetadata(CommandMetadata other)
 {
     throw new NotImplementedException();
 }
예제 #21
0
        internal string GetProxyParameterData(string prefix, string paramNameOverride, bool isProxyForCmdlet)
        {
            StringBuilder builder = new StringBuilder();

            if ((this.parameterSets != null) && isProxyForCmdlet)
            {
                foreach (string str in this.parameterSets.Keys)
                {
                    string proxyParameterData = this.parameterSets[str].GetProxyParameterData();
                    if (!string.IsNullOrEmpty(proxyParameterData) || !str.Equals("__AllParameterSets"))
                    {
                        string str3 = "";
                        builder.Append(prefix);
                        builder.Append("[Parameter(");
                        if (!str.Equals("__AllParameterSets"))
                        {
                            builder.AppendFormat(CultureInfo.InvariantCulture, "ParameterSetName='{0}'", new object[] { CommandMetadata.EscapeSingleQuotedString(str) });
                            str3 = ", ";
                        }
                        if (!string.IsNullOrEmpty(proxyParameterData))
                        {
                            builder.Append(str3);
                            builder.Append(proxyParameterData);
                        }
                        builder.Append(")]");
                    }
                }
            }
            if ((this.aliases != null) && (this.aliases.Count > 0))
            {
                StringBuilder builder2 = new StringBuilder();
                string        str4     = "";
                foreach (string str5 in this.aliases)
                {
                    builder2.AppendFormat(CultureInfo.InvariantCulture, "{0}'{1}'", new object[] { str4, CommandMetadata.EscapeSingleQuotedString(str5) });
                    str4 = ",";
                }
                builder.AppendFormat(CultureInfo.InvariantCulture, "{0}[Alias({1})]", new object[] { prefix, builder2.ToString() });
            }
            if ((this.attributes != null) && (this.attributes.Count > 0))
            {
                foreach (Attribute attribute in this.attributes)
                {
                    string proxyAttributeData = this.GetProxyAttributeData(attribute, prefix);
                    if (!string.IsNullOrEmpty(proxyAttributeData))
                    {
                        builder.Append(proxyAttributeData);
                    }
                }
            }
            if (this.SwitchParameter)
            {
                builder.AppendFormat(CultureInfo.InvariantCulture, "{0}[{1}]", new object[] { prefix, "switch" });
            }
            else if (this.parameterType != null)
            {
                builder.AppendFormat(CultureInfo.InvariantCulture, "{0}[{1}]", new object[] { prefix, ToStringCodeMethods.Type(this.parameterType, false) });
            }
            builder.AppendFormat(CultureInfo.InvariantCulture, "{0}${{{1}}}", new object[] { prefix, CommandMetadata.EscapeVariableName(string.IsNullOrEmpty(paramNameOverride) ? this.name : paramNameOverride) });
            return(builder.ToString());
        }
예제 #22
0
        public PSObject NewTotalCount(ulong totalCount, double accuracy)
        {
            PSObject       obj2   = new PSObject(totalCount);
            string         script = string.Format(CultureInfo.CurrentCulture, "\r\n                    $totalCount = $this.PSObject.BaseObject\r\n                    switch ($this.Accuracy) {{\r\n                        {{ $_ -ge 1.0 }} {{ '{0}' -f $totalCount }}\r\n                        {{ $_ -le 0.0 }} {{ '{1}' -f $totalCount }}\r\n                        default          {{ '{2}' -f $totalCount }}\r\n                    }}\r\n                ", new object[] { CommandMetadata.EscapeSingleQuotedString(CommandBaseStrings.PagingSupportAccurateTotalCountTemplate), CommandMetadata.EscapeSingleQuotedString(CommandBaseStrings.PagingSupportUnknownTotalCountTemplate), CommandMetadata.EscapeSingleQuotedString(CommandBaseStrings.PagingSupportEstimatedTotalCountTemplate) });
            PSScriptMethod member = new PSScriptMethod("ToString", ScriptBlock.Create(script));

            obj2.Members.Add(member);
            accuracy = Math.Max(0.0, Math.Min(1.0, accuracy));
            PSNoteProperty property = new PSNoteProperty("Accuracy", accuracy);

            obj2.Members.Add(property);
            return(obj2);
        }
예제 #23
0
 public static string GetCmdletBindingAttribute(CommandMetadata commandMetadata) => commandMetadata != null?commandMetadata.GetDecl() : throw ProxyCommand.tracer.NewArgumentNullException("commandMetaData");
예제 #24
0
 private CommandMetadata GetCommandMetadata(CommonCmdletMetadata cmdletMetadata)
 {
     string defaultParameterSetName = null;
     StaticCmdletMetadataCmdletMetadata metadata = cmdletMetadata as StaticCmdletMetadataCmdletMetadata;
     if ((metadata != null) && !string.IsNullOrEmpty(metadata.DefaultCmdletParameterSet))
     {
         defaultParameterSetName = metadata.DefaultCmdletParameterSet;
     }
     System.Management.Automation.ConfirmImpact none = System.Management.Automation.ConfirmImpact.None;
     if (cmdletMetadata.ConfirmImpactSpecified)
     {
         none = (System.Management.Automation.ConfirmImpact) cmdletMetadata.ConfirmImpact;
     }
     Dictionary<string, ParameterMetadata> parameters = new Dictionary<string, ParameterMetadata>(StringComparer.OrdinalIgnoreCase);
     CommandMetadata metadata2 = new CommandMetadata(this.GetCmdletName(cmdletMetadata), CommandTypes.Cmdlet, true, defaultParameterSetName, none != System.Management.Automation.ConfirmImpact.None, none, false, false, false, parameters);
     if (!string.IsNullOrEmpty(cmdletMetadata.HelpUri))
     {
         metadata2.HelpUri = cmdletMetadata.HelpUri;
     }
     return metadata2;
 }
예제 #25
0
        /// <summary>
        /// Gets a dictionary of parameter metadata for the supplied <paramref name="type"/>.  
        /// </summary>
        /// <param name="type">
        /// CLR Type for which the parameter metadata is constructed.
        /// </param>
        /// <returns>
        /// A Dictionary of ParameterMetadata keyed by parameter name.
        /// null if no parameter metadata is found.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// type is null.
        /// </exception>
        public static Dictionary<string, ParameterMetadata> GetParameterMetadata(Type type)
        {
            if (null == type)
            {
                throw PSTraceSource.NewArgumentNullException("type");
            }

            CommandMetadata cmdMetaData = new CommandMetadata(type);
            Dictionary<string, ParameterMetadata> result = cmdMetaData.Parameters;
            // early GC.
            cmdMetaData = null;
            return result;
        }
예제 #26
0
        internal string GetProxyParameterData()
        {
            StringBuilder builder = new StringBuilder();
            string        str     = "";

            if (this.isMandatory)
            {
                builder.AppendFormat(CultureInfo.InvariantCulture, "{0}Mandatory=$true", new object[] { str });
                str = ", ";
            }
            if (this.position != -2147483648)
            {
                builder.AppendFormat(CultureInfo.InvariantCulture, "{0}Position={1}", new object[] { str, this.position });
                str = ", ";
            }
            if (this.valueFromPipeline)
            {
                builder.AppendFormat(CultureInfo.InvariantCulture, "{0}ValueFromPipeline=$true", new object[] { str });
                str = ", ";
            }
            if (this.valueFromPipelineByPropertyName)
            {
                builder.AppendFormat(CultureInfo.InvariantCulture, "{0}ValueFromPipelineByPropertyName=$true", new object[] { str });
                str = ", ";
            }
            if (this.valueFromRemainingArguments)
            {
                builder.AppendFormat(CultureInfo.InvariantCulture, "{0}ValueFromRemainingArguments=$true", new object[] { str });
                str = ", ";
            }
            if (!string.IsNullOrEmpty(this.helpMessage))
            {
                builder.AppendFormat(CultureInfo.InvariantCulture, "{0}HelpMessage='{1}'", new object[] { str, CommandMetadata.EscapeSingleQuotedString(this.helpMessage) });
                str = ", ";
            }
            return(builder.ToString());
        }
예제 #27
0
        internal static Collection<CommandParameterSetInfo> GetParameterMetadata(CommandMetadata metadata, MergedCommandParameterMetadata parameterMetadata)
        {
            Collection<CommandParameterSetInfo> result = new Collection<CommandParameterSetInfo>();

            if (parameterMetadata != null)
            {
                if (parameterMetadata.ParameterSetCount == 0)
                {
                    const string parameterSetName = ParameterAttribute.AllParameterSets;

                    result.Add(
                        new CommandParameterSetInfo(
                            parameterSetName,
                            false,
                            uint.MaxValue,
                            parameterMetadata));
                }
                else
                {
                    int parameterSetCount = parameterMetadata.ParameterSetCount;
                    for (int index = 0; index < parameterSetCount; ++index)
                    {
                        uint currentFlagPosition = (uint)0x1 << index;

                        // Get the parameter set name
                        string parameterSetName = parameterMetadata.GetParameterSetName(currentFlagPosition);

                        // Is the parameter set the default?
                        bool isDefaultParameterSet = (currentFlagPosition & metadata.DefaultParameterSetFlag) != 0;

                        result.Add(
                            new CommandParameterSetInfo(
                                parameterSetName,
                                isDefaultParameterSet,
                                currentFlagPosition,
                                parameterMetadata));
                    }
                }
            }

            return result;
        } // GetParameterMetadata
예제 #28
0
 internal static Collection<CommandParameterSetInfo> GetCacheableMetadata(CommandMetadata metadata)
 {
     return GetParameterMetadata(metadata, metadata.StaticCommandParameterMetadata);
 }
예제 #29
0
        private static Collection <CommandMetadata> GetRestrictedJobCommands()
        {
            ParameterSetMetadata metadata  = new ParameterSetMetadata(0, ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty);
            ParameterSetMetadata metadata2 = new ParameterSetMetadata(0, ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty);
            ParameterSetMetadata metadata3 = new ParameterSetMetadata(0, ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty);
            ParameterSetMetadata metadata4 = new ParameterSetMetadata(-2147483648, ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty);
            ParameterSetMetadata metadata5 = new ParameterSetMetadata(-2147483648, ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty);
            ParameterSetMetadata metadata6 = new ParameterSetMetadata(0, ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty);
            ParameterSetMetadata metadata7 = new ParameterSetMetadata(0, ParameterSetMetadata.ParameterFlags.Mandatory | ParameterSetMetadata.ParameterFlags.ValueFromPipeline | ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty);
            ParameterSetMetadata metadata8 = new ParameterSetMetadata(0, ParameterSetMetadata.ParameterFlags.Mandatory | ParameterSetMetadata.ParameterFlags.ValueFromPipeline | ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty);
            ParameterSetMetadata metadata9 = new ParameterSetMetadata(0, ParameterSetMetadata.ParameterFlags.Mandatory | ParameterSetMetadata.ParameterFlags.ValueFromPipeline | ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty);
            Dictionary <string, ParameterSetMetadata> parameterSets = new Dictionary <string, ParameterSetMetadata>();

            parameterSets.Add("NameParameterSet", metadata);
            Collection <string> aliases    = new Collection <string>();
            ParameterMetadata   metadata10 = new ParameterMetadata(aliases, false, "Name", parameterSets, typeof(string[]))
            {
                Attributes = { new ValidatePatternAttribute(@"^[-._:\\\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Lm}]{1,100}$"), new ValidateLengthAttribute(0, 0x3e8) }
            };

            parameterSets = new Dictionary <string, ParameterSetMetadata>();
            parameterSets.Add("InstanceIdParameterSet", metadata2);
            ParameterMetadata metadata11 = new ParameterMetadata(aliases, false, "InstanceId", parameterSets, typeof(Guid[]))
            {
                Attributes = { new ValidateNotNullOrEmptyAttribute() }
            };

            parameterSets = new Dictionary <string, ParameterSetMetadata>();
            parameterSets.Add("SessionIdParameterSet", metadata3);
            ParameterMetadata metadata12 = new ParameterMetadata(aliases, false, "Id", parameterSets, typeof(int[]))
            {
                Attributes = { new ValidateNotNullOrEmptyAttribute() }
            };

            parameterSets = new Dictionary <string, ParameterSetMetadata>();
            parameterSets.Add("StateParameterSet", metadata4);
            ParameterMetadata metadata13 = new ParameterMetadata(aliases, false, "State", parameterSets, typeof(JobState));

            parameterSets = new Dictionary <string, ParameterSetMetadata>();
            parameterSets.Add("CommandParameterSet", metadata5);
            ParameterMetadata metadata14 = new ParameterMetadata(aliases, false, "Command", parameterSets, typeof(string[]));

            parameterSets = new Dictionary <string, ParameterSetMetadata>();
            parameterSets.Add("FilterParameterSet", metadata6);
            ParameterMetadata metadata15 = new ParameterMetadata(aliases, false, "Filter", parameterSets, typeof(Hashtable));

            parameterSets = new Dictionary <string, ParameterSetMetadata>();
            parameterSets.Add("Job", metadata7);
            ParameterMetadata metadata16 = new ParameterMetadata(aliases, false, "Job", parameterSets, typeof(Job[]))
            {
                Attributes = { new ValidateNotNullOrEmptyAttribute() }
            };

            parameterSets = new Dictionary <string, ParameterSetMetadata>();
            parameterSets.Add("ComputerName", metadata8);
            parameterSets.Add("Location", metadata9);
            ParameterMetadata            metadata17  = new ParameterMetadata(aliases, false, "Job", parameterSets, typeof(Job[]));
            Collection <CommandMetadata> collection2 = new Collection <CommandMetadata>();
            ParameterMetadata            metadata18  = new ParameterMetadata("PassThru", typeof(SwitchParameter));
            ParameterMetadata            metadata19  = new ParameterMetadata("Any", typeof(SwitchParameter));
            CommandMetadata item = GetRestrictedCmdlet("Stop-Job", "SessionIdParameterSet", "http://go.microsoft.com/fwlink/?LinkID=113413", new ParameterMetadata[] { metadata10, metadata11, metadata12, metadata13, metadata15, metadata16, metadata18 });

            collection2.Add(item);
            ParameterMetadata metadata21 = new ParameterMetadata("Timeout", typeof(int))
            {
                Attributes = { new ValidateRangeAttribute(-1, 0x7fffffff) }
            };
            CommandMetadata metadata22 = GetRestrictedCmdlet("Wait-Job", "SessionIdParameterSet", "http://go.microsoft.com/fwlink/?LinkID=113422", new ParameterMetadata[] { metadata10, metadata11, metadata12, metadata16, metadata13, metadata15, metadata19, metadata21 });

            collection2.Add(metadata22);
            CommandMetadata metadata23 = GetRestrictedCmdlet("Get-Job", "SessionIdParameterSet", "http://go.microsoft.com/fwlink/?LinkID=113328", new ParameterMetadata[] { metadata10, metadata11, metadata12, metadata13, metadata15, metadata14 });

            collection2.Add(metadata23);
            parameterSets = new Dictionary <string, ParameterSetMetadata>();
            metadata8     = new ParameterSetMetadata(1, ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty);
            parameterSets.Add("ComputerName", metadata8);
            ParameterMetadata metadata24 = new ParameterMetadata(aliases, false, "ComputerName", parameterSets, typeof(string[]))
            {
                Attributes = { new ValidateLengthAttribute(0, 0x3e8), new ValidateNotNullOrEmptyAttribute() }
            };

            parameterSets = new Dictionary <string, ParameterSetMetadata>();
            metadata9     = new ParameterSetMetadata(1, ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty);
            parameterSets.Add("Location", metadata9);
            ParameterMetadata metadata25 = new ParameterMetadata(aliases, false, "Location", parameterSets, typeof(string[]))
            {
                Attributes = { new ValidateLengthAttribute(0, 0x3e8), new ValidateNotNullOrEmptyAttribute() }
            };
            ParameterMetadata metadata26 = new ParameterMetadata("NoRecurse", typeof(SwitchParameter));
            ParameterMetadata metadata27 = new ParameterMetadata("Keep", typeof(SwitchParameter));
            ParameterMetadata metadata28 = new ParameterMetadata("Wait", typeof(SwitchParameter));
            ParameterMetadata metadata29 = new ParameterMetadata("WriteEvents", typeof(SwitchParameter));
            ParameterMetadata metadata30 = new ParameterMetadata("WriteJobInResults", typeof(SwitchParameter));
            ParameterMetadata metadata31 = new ParameterMetadata("AutoRemoveJob", typeof(SwitchParameter));
            CommandMetadata   metadata32 = GetRestrictedCmdlet("Receive-Job", "Location", "http://go.microsoft.com/fwlink/?LinkID=113372", new ParameterMetadata[] { metadata10, metadata11, metadata12, metadata13, metadata17, metadata24, metadata25, metadata26, metadata27, metadata28, metadata29, metadata30, metadata31 });

            collection2.Add(metadata32);
            ParameterMetadata metadata33 = new ParameterMetadata("Force", typeof(SwitchParameter));
            CommandMetadata   metadata34 = GetRestrictedCmdlet("Remove-Job", "SessionIdParameterSet", "http://go.microsoft.com/fwlink/?LinkID=113377", new ParameterMetadata[] { metadata10, metadata11, metadata12, metadata13, metadata15, metadata16, metadata33 });

            collection2.Add(metadata34);
            CommandMetadata metadata35 = GetRestrictedCmdlet("Suspend-Job", "SessionIdParameterSet", "http://go.microsoft.com/fwlink/?LinkID=210613", new ParameterMetadata[] { metadata10, metadata11, metadata12, metadata13, metadata15, metadata16, metadata18 });

            collection2.Add(metadata35);
            CommandMetadata metadata36 = GetRestrictedCmdlet("Resume-Job", "SessionIdParameterSet", "http://go.microsoft.com/fwlink/?LinkID=210611", new ParameterMetadata[] { metadata10, metadata11, metadata12, metadata13, metadata15, metadata16, metadata18 });

            collection2.Add(metadata36);
            return(collection2);
        }
예제 #30
0
 public static string Create(CommandMetadata commandMetadata, string helpComment) => commandMetadata != null?commandMetadata.GetProxyCommand(helpComment) : throw ProxyCommand.tracer.NewArgumentNullException("commandMetaData");
예제 #31
0
 internal static Collection <CommandParameterSetInfo> GetCacheableMetadata(CommandMetadata metadata)
 {
     return(GetParameterMetadata(metadata, metadata.StaticCommandParameterMetadata));
 }
예제 #32
0
 public static string GetEnd(CommandMetadata commandMetadata) => commandMetadata != null?commandMetadata.GetEndBlock() : throw ProxyCommand.tracer.NewArgumentNullException("commandMetaData");
예제 #33
0
 public CommandMetadata(CommandMetadata other)
 {
     throw new NotImplementedException();
 }
예제 #34
0
        private string GetProxyAttributeData(Attribute attrib, string prefix)
        {
            ValidateLengthAttribute attribute = attrib as ValidateLengthAttribute;

            if (attribute != null)
            {
                return(string.Format(CultureInfo.InvariantCulture, "{0}[ValidateLength({1}, {2})]", new object[] { prefix, attribute.MinLength, attribute.MaxLength }));
            }
            ValidateRangeAttribute attribute2 = attrib as ValidateRangeAttribute;

            if (attribute2 != null)
            {
                string str2;
                Type   type = attribute2.MinRange.GetType();
                if ((type == typeof(float)) || (type == typeof(double)))
                {
                    str2 = "{0}[ValidateRange({1:R}, {2:R})]";
                }
                else
                {
                    str2 = "{0}[ValidateRange({1}, {2})]";
                }
                return(string.Format(CultureInfo.InvariantCulture, str2, new object[] { prefix, attribute2.MinRange, attribute2.MaxRange }));
            }
            if (attrib is AllowNullAttribute)
            {
                return(string.Format(CultureInfo.InvariantCulture, "{0}[AllowNull()]", new object[] { prefix }));
            }
            if (attrib is AllowEmptyStringAttribute)
            {
                return(string.Format(CultureInfo.InvariantCulture, "{0}[AllowEmptyString()]", new object[] { prefix }));
            }
            if (attrib is AllowEmptyCollectionAttribute)
            {
                return(string.Format(CultureInfo.InvariantCulture, "{0}[AllowEmptyCollection()]", new object[] { prefix }));
            }
            ValidatePatternAttribute attribute6 = attrib as ValidatePatternAttribute;

            if (attribute6 != null)
            {
                return(string.Format(CultureInfo.InvariantCulture, "{0}[ValidatePattern('{1}')]", new object[] { prefix, CommandMetadata.EscapeSingleQuotedString(attribute6.RegexPattern) }));
            }
            ValidateCountAttribute attribute7 = attrib as ValidateCountAttribute;

            if (attribute7 != null)
            {
                return(string.Format(CultureInfo.InvariantCulture, "{0}[ValidateCount({1}, {2})]", new object[] { prefix, attribute7.MinLength, attribute7.MaxLength }));
            }
            if (attrib is ValidateNotNullAttribute)
            {
                return(string.Format(CultureInfo.InvariantCulture, "{0}[ValidateNotNull()]", new object[] { prefix }));
            }
            if (attrib is ValidateNotNullOrEmptyAttribute)
            {
                return(string.Format(CultureInfo.InvariantCulture, "{0}[ValidateNotNullOrEmpty()]", new object[] { prefix }));
            }
            ValidateSetAttribute attribute10 = attrib as ValidateSetAttribute;

            if (attribute10 != null)
            {
                StringBuilder builder = new StringBuilder();
                string        str3    = "";
                foreach (string str4 in attribute10.ValidValues)
                {
                    builder.AppendFormat(CultureInfo.InvariantCulture, "{0}'{1}'", new object[] { str3, CommandMetadata.EscapeSingleQuotedString(str4) });
                    str3 = ",";
                }
                return(string.Format(CultureInfo.InvariantCulture, "{0}[ValidateSet({1})]", new object[] { prefix, builder.ToString() }));
            }
            ValidateScriptAttribute attribute11 = attrib as ValidateScriptAttribute;

            if (attribute11 != null)
            {
                return(string.Format(CultureInfo.InvariantCulture, "{0}[ValidateScript({{ {1} }})]", new object[] { prefix, attribute11.ScriptBlock.ToString() }));
            }
            PSTypeNameAttribute attribute12 = attrib as PSTypeNameAttribute;

            if (attribute12 != null)
            {
                return(string.Format(CultureInfo.InvariantCulture, "{0}[PSTypeName('{1}')]", new object[] { prefix, CommandMetadata.EscapeSingleQuotedString(attribute12.PSTypeName) }));
            }
            return(null);
        }
예제 #35
0
 public static string GetCmdletBindingAttribute(CommandMetadata commandMetadata)
 {
     throw new NotImplementedException();
 }
예제 #36
0
 public static string GetParamBlock(CommandMetadata commandMetadata)
 {
     throw new NotImplementedException();
 }
예제 #37
0
 public static string GetProcess(CommandMetadata commandMetadata)
 {
     throw new NotImplementedException();
 }
예제 #38
0
        /// <summary>
        /// This sample uses the ProxyCommand class to create a proxy command that 
        /// calls an existing cmdlet, but restricts the set of available parameters.  
        /// The proxy command is then added to an intial session state that is used to 
        /// create a contrained runspace. This means that the user can access the cmdlet 
        /// through the proxy command.
        /// </summary>
        /// <remarks>
        /// This sample demonstrates the following:
        /// 1. Creating a CommandMetadata object that describes the metadata of an 
        ///    existing cmdlet.
        /// 2. Modifying the cmdlet metadata to remove a parameter of the cmdlet.
        /// 3. Adding the cmdlet to an initial session state and making it private.
        /// 4. Creating a proxy function that calls the existing cmdlet, but exposes 
        ///    only a restricted set of parameters.   
        /// 6. Adding the proxy function to the initial session state. 
        /// 7. Calling the private cmdlet and the proxy function to demonstrate the 
        ///    constrained runspace.
        /// </remarks>
        private static void Main()
        {
            // Create a default intial session state. The default inital session state
              // includes all the elements that are provided by Windows PowerShell.
              InitialSessionState iss = InitialSessionState.CreateDefault();

              // Add the get-proc cmdlet to the initial session state.
              SessionStateCmdletEntry cmdletEntry = new SessionStateCmdletEntry("get-proc", typeof(GetProcCommand), null);
              iss.Commands.Add(cmdletEntry);

              // Make the cmdlet private so that it is not accessable.
              cmdletEntry.Visibility = SessionStateEntryVisibility.Private;

              // Set the language mode of the intial session state to NoLanguge to
              //prevent users from using language features. Only the invocation of
              // public commands is allowed.
              iss.LanguageMode = PSLanguageMode.NoLanguage;

              // Create the proxy command using cmdlet metadata to expose the
              // get-proc cmdlet.
              CommandMetadata cmdletMetadata = new CommandMetadata(typeof(GetProcCommand));

              // Remove one of the parameters from the command metadata.
              cmdletMetadata.Parameters.Remove("Name");

              // Generate the body of a proxy function that calls the original cmdlet,
              // but does not have the removed parameter.
              string bodyOfProxyFunction = ProxyCommand.Create(cmdletMetadata);

              // Add the proxy function to the initial session state. The name of the proxy
              // function can be the same as the name of the cmdlet, but to clearly
              // demonstrate that the original cmdlet is not available a different name is
              // used for the proxy function.
              iss.Commands.Add(new SessionStateFunctionEntry("get-procProxy", bodyOfProxyFunction));

              // Create the constrained runspace using the intial session state.
              using (Runspace myRunspace = RunspaceFactory.CreateRunspace(iss))
              {
            myRunspace.Open();

            // Call the private cmdlet to demonstrate that it is not available.
            try
            {
              using (PowerShell powershell = PowerShell.Create())
              {
            powershell.Runspace = myRunspace;
            powershell.AddCommand("get-proc").AddParameter("Name", "*explore*");
            powershell.Invoke();
              }
            }
            catch (CommandNotFoundException e)
            {
              System.Console.WriteLine(
                        "Invoking 'get-proc' failed as expected: {0}: {1}",
                        e.GetType().FullName,
                        e.Message);
            }

            // Call the proxy function to demonstrate that the -Name parameter is
            // not available.
            try
            {
              using (PowerShell powershell = PowerShell.Create())
              {
            powershell.Runspace = myRunspace;
            powershell.AddCommand("get-procProxy").AddParameter("Name", "idle");
            powershell.Invoke();
              }
            }
            catch (ParameterBindingException e)
            {
              System.Console.WriteLine(
                        "\nInvoking 'get-procProxy -Name idle' failed as expected: {0}: {1}",
                        e.GetType().FullName,
                        e.Message);
            }

            // Call the proxy function to demonstrate that it calls into the
            // private cmdlet to retrieve the processes.
            using (PowerShell powershell = PowerShell.Create())
            {
              powershell.Runspace = myRunspace;
              powershell.AddCommand("get-procProxy");
              List<Process> processes = new List<Process>(powershell.Invoke<Process>());
              System.Console.WriteLine(
                        "\nInvoking the get-procProxy function called into the get-proc cmdlet and returned {0} processes",
                        processes.Count);
            }

            // Close the runspace to release resources.
            myRunspace.Close();
              }

              System.Console.WriteLine("Hit any key to exit...");
              System.Console.ReadKey();
        }
예제 #39
0
 public static string Create(CommandMetadata commandMetadata)
 {
     throw new NotImplementedException();
 }
예제 #40
0
 public MergedCommandParameterMetadata GetParameterMetadata(ScriptBlock scriptBlock)
 {
     if (this._parameterMetadata == null)
     {
         lock (this._syncObject)
         {
             if (this._parameterMetadata == null)
             {
                 CommandMetadata metadata = new CommandMetadata(scriptBlock, "", LocalPipeline.GetExecutionContextFromTLS());
                 this._parameterMetadata = metadata.StaticCommandParameterMetadata;
             }
         }
     }
     return this._parameterMetadata;
 }
예제 #41
0
        private void SetParameters(CommandMetadata commandMetadata, params Dictionary<string, ParameterMetadata>[] allParameters)
        {
            commandMetadata.Parameters.Clear();
            foreach (Dictionary<string, ParameterMetadata> parameters in allParameters)
            {
                foreach (KeyValuePair<string, ParameterMetadata> parameter in parameters)
                {
                    if (commandMetadata.Parameters.ContainsKey(parameter.Key))
                    {
                        if (this.GetCommonParameters().ContainsKey(parameter.Key))
                        {
                            string message = string.Format(
                                CultureInfo.InvariantCulture, // parameter name 
                                CmdletizationCoreResources.ScriptWriter_ParameterNameConflictsWithCommonParameters,
                                parameter.Key,
                                commandMetadata.Name,
                                _objectModelWrapper.FullName);
                            throw new XmlException(message);
                        }
                        else
                        {
                            string message = string.Format(
                                CultureInfo.InvariantCulture, // parameter name 
                                CmdletizationCoreResources.ScriptWriter_ParameterNameConflictsWithQueryParameters,
                                parameter.Key,
                                commandMetadata.Name,
                                "<GetCmdletParameters>");
                            throw new XmlException(message);
                        }
                    }

                    commandMetadata.Parameters.Add(parameter.Key, parameter.Value);
                }
            }
        }
예제 #42
0
 private void SetParameters(CommandMetadata commandMetadata, params Dictionary<string, ParameterMetadata>[] allParameters)
 {
     commandMetadata.Parameters.Clear();
     foreach (Dictionary<string, ParameterMetadata> dictionary in allParameters)
     {
         foreach (KeyValuePair<string, ParameterMetadata> pair in dictionary)
         {
             if (commandMetadata.Parameters.ContainsKey(pair.Key))
             {
                 if (this.GetCommonParameters().ContainsKey(pair.Key))
                 {
                     throw new XmlException(string.Format(CultureInfo.InvariantCulture, CmdletizationCoreResources.ScriptWriter_ParameterNameConflictsWithCommonParameters, new object[] { pair.Key, commandMetadata.Name, this.objectModelWrapper.FullName }));
                 }
                 throw new XmlException(string.Format(CultureInfo.InvariantCulture, CmdletizationCoreResources.ScriptWriter_ParameterNameConflictsWithQueryParameters, new object[] { pair.Key, commandMetadata.Name, "<GetCmdletParameters>" }));
             }
             commandMetadata.Parameters.Add(pair.Key, pair.Value);
         }
     }
 }
예제 #43
0
        private static CommandMetadata GetRestrictedCmdlet(string cmdletName, string defaultParameterSet, string helpUri, params ParameterMetadata[] parameters)
        {
            Dictionary<string, ParameterMetadata> parametersDictionary = new Dictionary<string, ParameterMetadata>(StringComparer.OrdinalIgnoreCase);
            foreach (ParameterMetadata parameter in parameters)
            {
                parametersDictionary.Add(parameter.Name, parameter);
            }

            // isProxyForCmdlet:
            // 1a. we would want to set it to false to get rid of unused common parameters
            //    (like OutBuffer - see bug Windows 7: #402213)
            // 1b. otoh common parameters are going to be present anyway on all proxy functions
            //     that the host generates for its cmdlets that need cmdletbinding, so
            //     we should make sure that common parameters are safe, not hide them
            // 2. otoh without cmdletbinding() unspecified parameters get bound to $null which might 
            //    unnecessarily trigger validation attribute failures - see bug Windows 7: #477218

            CommandMetadata metadata = new CommandMetadata(
                                   name: cmdletName,
                            commandType: CommandTypes.Cmdlet,
                       isProxyForCmdlet: true,
                defaultParameterSetName: defaultParameterSet,
                  supportsShouldProcess: false,
                          confirmImpact: ConfirmImpact.None,
                         supportsPaging: false,
                   supportsTransactions: false,
                      positionalBinding: true,
                             parameters: parametersDictionary);

            metadata.HelpUri = helpUri;

            return metadata;
        }
예제 #44
0
 public static Dictionary<string, ParameterMetadata> GetParameterMetadata(Type type)
 {
     if (null == type)
     {
         throw PSTraceSource.NewArgumentNullException("type");
     }
     CommandMetadata metadata = new CommandMetadata(type);
     Dictionary<string, ParameterMetadata> parameters = metadata.Parameters;
     metadata = null;
     return parameters;
 }
예제 #45
0
        /// <summary>
        /// A copy constructor that creates a deep copy of the <paramref name="other"/> CommandMetadata object.
        /// Instances of Attribute and Type classes are copied by reference.
        /// </summary>
        /// <param name="other">object to copy</param>
        public CommandMetadata(CommandMetadata other)
        {
            if (other == null)
            {
                throw PSTraceSource.NewArgumentNullException("other");
            }

            Name = other.Name;
            ConfirmImpact = other.ConfirmImpact;
            _defaultParameterSetFlag = other._defaultParameterSetFlag;
            _defaultParameterSetName = other._defaultParameterSetName;
            _implementsDynamicParameters = other._implementsDynamicParameters;
            SupportsShouldProcess = other.SupportsShouldProcess;
            SupportsPaging = other.SupportsPaging;
            SupportsTransactions = other.SupportsTransactions;
            this.CommandType = other.CommandType;
            _wrappedAnyCmdlet = other._wrappedAnyCmdlet;
            _wrappedCommand = other._wrappedCommand;
            _wrappedCommandType = other._wrappedCommandType;

            _parameters = new Dictionary<string, ParameterMetadata>(other.Parameters.Count, StringComparer.OrdinalIgnoreCase);

            // deep copy
            if (other.Parameters != null)
            {
                foreach (KeyValuePair<string, ParameterMetadata> entry in other.Parameters)
                {
                    _parameters.Add(entry.Key, new ParameterMetadata(entry.Value));
                }
            }

            // deep copy of the collection, collection items (Attributes) copied by reference
            if (other._otherAttributes == null)
            {
                _otherAttributes = null;
            }
            else
            {
                _otherAttributes = new Collection<Attribute>(new List<Attribute>(other._otherAttributes.Count));
                foreach (Attribute attribute in other._otherAttributes)
                {
                    _otherAttributes.Add(attribute);
                }
            }

            // not copying those fields/members as they are untouched (and left set to null) 
            // by public constructors, so we can't rely on those fields/members to be set
            // when CommandMetadata comes from a user
            _staticCommandParameterMetadata = null;
        }
예제 #46
0
        /// <summary>
        /// Gets the metadata for the specified cmdlet from the cache or creates
        /// a new instance if its not in the cache.
        /// </summary>
        /// 
        /// <param name="commandName">
        /// The name of the command that this metadata represents.
        /// </param>
        /// 
        /// <param name="cmdletType">
        /// The cmdlet to get the metadata for.
        /// </param>
        /// 
        /// <param name="context">
        /// The current engine context.
        /// </param>
        /// 
        /// <returns>
        /// The CommandMetadata for the specified cmdlet.
        /// </returns>
        /// 
        /// <exception cref="ArgumentException">
        /// If <paramref name="commandName"/> is null or empty.
        /// </exception>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="cmdletType"/> is null.
        /// </exception>
        /// 
        /// <exception cref="ParsingMetadataException">
        /// If more than int.MaxValue parameter-sets are defined for the command.
        /// </exception>
        /// 
        /// <exception cref="MetadataException">
        /// If a parameter defines the same parameter-set name multiple times.
        /// If the attributes could not be read from a property or field.
        /// </exception>
        /// 
        internal static CommandMetadata Get(string commandName, Type cmdletType, ExecutionContext context)
        {
            if (String.IsNullOrEmpty(commandName))
            {
                throw PSTraceSource.NewArgumentException("commandName");
            }

            CommandMetadata result = null;

            if ((context != null) && (cmdletType != null))
            {
                string cmdletTypeName = cmdletType.AssemblyQualifiedName;
                s_commandMetadataCache.TryGetValue(cmdletTypeName, out result);
            }

            if (result == null)
            {
                result = new CommandMetadata(commandName, cmdletType, context);

                if ((context != null) && (cmdletType != null))
                {
                    string cmdletTypeName = cmdletType.AssemblyQualifiedName;
                    s_commandMetadataCache.TryAdd(cmdletTypeName, result);
                }
            }

            return result;
        } // Get
예제 #47
0
 internal static CommandMetadata Get(string commandName, Type cmdletType, ExecutionContext context)
 {
     if (string.IsNullOrEmpty(commandName))
     {
         throw PSTraceSource.NewArgumentException("commandName");
     }
     CommandMetadata metadata = null;
     if ((context != null) && (cmdletType != null))
     {
         string assemblyQualifiedName = cmdletType.AssemblyQualifiedName;
         if (CommandMetadataCache.ContainsKey(assemblyQualifiedName))
         {
             metadata = CommandMetadataCache[assemblyQualifiedName];
         }
     }
     if (metadata == null)
     {
         metadata = new CommandMetadata(commandName, cmdletType, context);
         if ((context != null) && (cmdletType != null))
         {
             string key = cmdletType.AssemblyQualifiedName;
             CommandMetadataCache.TryAdd(key, metadata);
         }
     }
     return metadata;
 }