/// <summary> /// Resolves a full, shortened, or aliased parameter name to the actual /// cmdlet parameter name, using PowerShell's standard parameter resolution /// algorithm. /// </summary> /// <param name="name">The name of the parameter to resolve.</param> /// <returns>The parameter that matches this name.</returns> public ParameterMetadata ResolveParameter(string name) { MergedCommandParameterMetadata merged = GetMergedCommandParameterMetadataSafely(); MergedCompiledCommandParameter result = merged.GetMatchingParameter(name, true, true, null); return(this.Parameters[result.Parameter.Name]); }
internal override Collection <CommandParameterInternal> BindParameters(Collection <CommandParameterInternal> arguments) { Collection <CommandParameterInternal> collection = new Collection <CommandParameterInternal>(); foreach (CommandParameterInternal internal2 in arguments) { if (!internal2.ParameterNameSpecified) { collection.Add(internal2); } else { MergedCompiledCommandParameter parameter = base.BindableParameters.GetMatchingParameter(internal2.ParameterName, false, true, new InvocationInfo(base.InvocationInfo.MyCommand, internal2.ParameterExtent)); if (parameter != null) { if (base.BoundParameters.ContainsKey(parameter.Parameter.Name)) { ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, base.InvocationInfo, base.GetParameterErrorExtent(internal2), internal2.ParameterName, null, null, "ParameterBinderStrings", "ParameterAlreadyBound", new object[0]); throw exception; } this.BindParameter(int.MaxValue, internal2, parameter, ParameterBindingFlags.ShouldCoerceType); } else if (internal2.ParameterName.Equals("-%", StringComparison.Ordinal)) { base.DefaultParameterBinder.CommandLineParameters.SetImplicitUsingParameters(internal2.ArgumentValue); } else { collection.Add(internal2); } } } return(collection); }
internal MergedCompiledCommandParameter GetMatchingParameter(string name, bool throwOnParameterNotFound, bool tryExactMatching, InvocationInfo invocationInfo) { if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException("name"); } Collection <MergedCompiledCommandParameter> collection = new Collection <MergedCompiledCommandParameter>(); if ((name.Length > 0) && SpecialCharacters.IsDash(name[0])) { name = name.Substring(1); } foreach (string str in this.bindableParameters.Keys) { if (nameCompareInfo.IsPrefix(str, name, CompareOptions.IgnoreCase)) { if (tryExactMatching && string.Equals(str, name, StringComparison.OrdinalIgnoreCase)) { return(this.bindableParameters[str]); } collection.Add(this.bindableParameters[str]); } } foreach (string str2 in this.aliasedParameters.Keys) { if (nameCompareInfo.IsPrefix(str2, name, CompareOptions.IgnoreCase)) { if (tryExactMatching && string.Equals(str2, name, StringComparison.OrdinalIgnoreCase)) { return(this.aliasedParameters[str2]); } if (!collection.Contains(this.aliasedParameters[str2])) { collection.Add(this.aliasedParameters[str2]); } } } if (collection.Count > 1) { StringBuilder builder = new StringBuilder(); foreach (MergedCompiledCommandParameter parameter in collection) { builder.AppendFormat(" -{0}", parameter.Parameter.Name); } ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, invocationInfo, null, name, null, null, "ParameterBinderStrings", "AmbiguousParameter", new object[] { builder }); throw exception; } if ((collection.Count == 0) && throwOnParameterNotFound) { ParameterBindingException exception2 = new ParameterBindingException(ErrorCategory.InvalidArgument, invocationInfo, null, name, null, null, "ParameterBinderStrings", "NamedParameterNotFound", new object[0]); throw exception2; } MergedCompiledCommandParameter parameter2 = null; if (collection.Count > 0) { parameter2 = collection[0]; } return(parameter2); }
/// <summary> /// Binds the specified parameters to the shell function /// </summary> /// /// <param name="arguments"> /// The arguments to bind. /// </param> /// internal override Collection <CommandParameterInternal> BindParameters(Collection <CommandParameterInternal> arguments) { Collection <CommandParameterInternal> result = new Collection <CommandParameterInternal>(); foreach (CommandParameterInternal argument in arguments) { if (!argument.ParameterNameSpecified) { result.Add(argument); continue; } // We don't want to throw an exception yet because // the parameter might be a positional argument MergedCompiledCommandParameter parameter = BindableParameters.GetMatchingParameter( argument.ParameterName, false, true, new InvocationInfo(this.InvocationInfo.MyCommand, argument.ParameterExtent)); // If the parameter is not in the specified parameter set, // throw a binding exception if (parameter != null) { // Now check to make sure it hasn't already been // bound by looking in the boundParameters collection if (BoundParameters.ContainsKey(parameter.Parameter.Name)) { ParameterBindingException bindingException = new ParameterBindingException( ErrorCategory.InvalidArgument, this.InvocationInfo, GetParameterErrorExtent(argument), argument.ParameterName, null, null, ParameterBinderStrings.ParameterAlreadyBound, "ParameterAlreadyBound"); throw bindingException; } BindParameter(uint.MaxValue, argument, parameter, ParameterBindingFlags.ShouldCoerceType); } else if (argument.ParameterName.Equals(Language.Parser.VERBATIM_PARAMETERNAME, StringComparison.Ordinal)) { // We sometimes send a magic parameter from a remote machine with the values referenced via // a using expression ($using:x). We then access these values via PSBoundParameters, so // "bind" them here. DefaultParameterBinder.CommandLineParameters.SetImplicitUsingParameters(argument.ArgumentValue); } else { result.Add(argument); } } return(result); }
internal void BindUnboundScriptParameterWithDefaultValue(MergedCompiledCommandParameter parameter) { ScriptParameterBinder defaultParameterBinder = (ScriptParameterBinder)this.DefaultParameterBinder; ScriptBlock script = defaultParameterBinder.Script; if (script.RuntimeDefinedParameters.ContainsKey(parameter.Parameter.Name)) { bool recordBoundParameters = defaultParameterBinder.RecordBoundParameters; try { defaultParameterBinder.RecordBoundParameters = false; RuntimeDefinedParameter parameter2 = script.RuntimeDefinedParameters[parameter.Parameter.Name]; IList implicitUsingParameters = null; if (this.DefaultParameterBinder.CommandLineParameters != null) { implicitUsingParameters = this.DefaultParameterBinder.CommandLineParameters.GetImplicitUsingParameters(); } object defaultScriptParameterValue = defaultParameterBinder.GetDefaultScriptParameterValue(parameter2, implicitUsingParameters); this.SaveDefaultScriptParameterValue(parameter.Parameter.Name, defaultScriptParameterValue); CommandParameterInternal argument = CommandParameterInternal.CreateParameterWithArgument(PositionUtilities.EmptyExtent, parameter.Parameter.Name, "-" + parameter.Parameter.Name + ":", PositionUtilities.EmptyExtent, defaultScriptParameterValue, false); ParameterBindingFlags isDefaultValue = ParameterBindingFlags.IsDefaultValue; if (parameter2.IsSet) { isDefaultValue |= ParameterBindingFlags.ShouldCoerceType; } this.BindParameter(int.MaxValue, argument, parameter, isDefaultValue); } finally { defaultParameterBinder.RecordBoundParameters = recordBoundParameters; } } }
private static void AddNewPosition(SortedDictionary<int, Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter>> result, int positionInParameterSet, MergedCompiledCommandParameter parameter, ParameterSetSpecificMetadata parameterSetData) { if (result.ContainsKey(positionInParameterSet)) { Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter> positionalCommandParameters = result[positionInParameterSet]; if (ContainsPositionalParameterInSet(positionalCommandParameters, parameter, parameterSetData.ParameterSetFlag)) { throw PSTraceSource.NewInvalidOperationException(); } if (positionalCommandParameters.ContainsKey(parameter)) { positionalCommandParameters[parameter].ParameterSetData.Add(parameterSetData); } else { PositionalCommandParameter parameter2 = new PositionalCommandParameter(parameter); parameter2.ParameterSetData.Add(parameterSetData); positionalCommandParameters.Add(parameter, parameter2); } } else { Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter> dictionary2 = new Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter>(); PositionalCommandParameter parameter3 = new PositionalCommandParameter(parameter) { ParameterSetData = { parameterSetData } }; dictionary2.Add(parameter, parameter3); result.Add(positionInParameterSet, dictionary2); } }
internal Collection <MergedCompiledCommandParameter> AddMetadataForBinder( InternalParameterMetadata parameterMetadata, ParameterBinderAssociation binderAssociation) { if (parameterMetadata == null) { throw MergedCommandParameterMetadata.tracer.NewArgumentNullException(nameof(parameterMetadata)); } Collection <MergedCompiledCommandParameter> collection = new Collection <MergedCompiledCommandParameter>(); foreach (KeyValuePair <string, CompiledCommandParameter> bindableParameter in parameterMetadata.BindableParameters) { if (this.bindableParameters.ContainsKey(bindableParameter.Key)) { MetadataException metadataException = new MetadataException("ParameterNameAlreadyExistsForCommand", (Exception)null, "Metadata", "ParameterNameAlreadyExistsForCommand", new object[1] { (object)bindableParameter.Key }); MergedCommandParameterMetadata.tracer.TraceException((Exception)metadataException); throw metadataException; } if (this.aliasedParameters.ContainsKey(bindableParameter.Key)) { MetadataException metadataException = new MetadataException("ParameterNameConflictsWithAlias", (Exception)null, "Metadata", "ParameterNameConflictsWithAlias", new object[2] { (object)bindableParameter.Key, (object)this.RetrieveParameterNameForAlias(bindableParameter.Key, this.aliasedParameters) }); MergedCommandParameterMetadata.tracer.TraceException((Exception)metadataException); throw metadataException; } MergedCompiledCommandParameter commandParameter = new MergedCompiledCommandParameter(bindableParameter.Value, binderAssociation); this.bindableParameters.Add(bindableParameter.Key, commandParameter); collection.Add(commandParameter); foreach (string alias in bindableParameter.Value.Aliases) { if (this.aliasedParameters.ContainsKey(alias)) { MetadataException metadataException = new MetadataException("AliasParameterNameAlreadyExistsForCommand", (Exception)null, "Metadata", "AliasParameterNameAlreadyExistsForCommand", new object[1] { (object)alias }); MergedCommandParameterMetadata.tracer.TraceException((Exception)metadataException); throw metadataException; } if (this.bindableParameters.ContainsKey(alias)) { MetadataException metadataException = new MetadataException("ParameterNameConflictsWithAlias", (Exception)null, "Metadata", "ParameterNameConflictsWithAlias", new object[2] { (object)this.RetrieveParameterNameForAlias(alias, this.bindableParameters), (object)bindableParameter.Value.Name }); MergedCommandParameterMetadata.tracer.TraceException((Exception)metadataException); throw metadataException; } this.aliasedParameters.Add(alias, commandParameter); } } return(collection); }
internal void ReparseUnboundArguments() { Collection <CommandParameterInternal> collection = new Collection <CommandParameterInternal>(); for (int i = 0; i < this._unboundArguments.Count; i++) { CommandParameterInternal item = this._unboundArguments[i]; if (!item.ParameterNameSpecified || item.ArgumentSpecified) { collection.Add(item); } else { string parameterName = item.ParameterName; MergedCompiledCommandParameter parameter = this._bindableParameters.GetMatchingParameter(parameterName, false, true, new System.Management.Automation.InvocationInfo(this.InvocationInfo.MyCommand, item.ParameterExtent)); if (parameter == null) { collection.Add(item); } else if (IsSwitchAndSetValue(parameterName, item, parameter.Parameter)) { collection.Add(item); } else if ((this._unboundArguments.Count - 1) > i) { CommandParameterInternal internal3 = this._unboundArguments[i + 1]; if (internal3.ParameterNameSpecified) { if ((this._bindableParameters.GetMatchingParameter(internal3.ParameterName, false, true, new System.Management.Automation.InvocationInfo(this.InvocationInfo.MyCommand, internal3.ParameterExtent)) != null) || internal3.ParameterAndArgumentSpecified) { ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetParameterErrorExtent(item), parameter.Parameter.Name, parameter.Parameter.Type, null, "ParameterBinderStrings", "MissingArgument", new object[0]); throw exception; } i++; item.ParameterName = parameter.Parameter.Name; item.SetArgumentValue(internal3.ArgumentExtent, internal3.ParameterText); collection.Add(item); } else { i++; item.ParameterName = parameter.Parameter.Name; item.SetArgumentValue(internal3.ArgumentExtent, internal3.ArgumentValue); collection.Add(item); } } else { ParameterBindingException exception2 = new ParameterBindingException(ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetParameterErrorExtent(item), parameter.Parameter.Name, parameter.Parameter.Type, null, "ParameterBinderStrings", "MissingArgument", new object[0]); throw exception2; } } } this._unboundArguments = collection; }
private static string RetrieveParameterNameForAlias(string key, IDictionary <string, MergedCompiledCommandParameter> dict) { MergedCompiledCommandParameter parameter = dict[key]; if (parameter != null) { CompiledCommandParameter parameter2 = parameter.Parameter; if ((parameter2 != null) && !string.IsNullOrEmpty(parameter2.Name)) { return(parameter2.Name); } } return(string.Empty); }
internal virtual bool BindParameter(CommandParameterInternal argument, ParameterBindingFlags flags) { bool flag = false; MergedCompiledCommandParameter parameter = this.BindableParameters.GetMatchingParameter(argument.ParameterName, (flags & ParameterBindingFlags.ThrowOnParameterNotFound) != ParameterBindingFlags.None, true, new System.Management.Automation.InvocationInfo(this.InvocationInfo.MyCommand, argument.ParameterExtent)); if (parameter == null) { return(flag); } if (this.BoundParameters.ContainsKey(parameter.Parameter.Name)) { ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetParameterErrorExtent(argument), argument.ParameterName, null, null, "ParameterBinderStrings", "ParameterAlreadyBound", new object[0]); throw exception; } flags &= ~ParameterBindingFlags.DelayBindScriptBlock; return(this.BindParameter(this._currentParameterSetFlag, argument, parameter, flags)); }
} // GetParameterSetName /// <summary> /// Helper function to retrieve the name of the parameter /// which defined an alias. /// </summary> /// <param name="key"></param> /// <param name="dict"></param> /// <returns></returns> private static string RetrieveParameterNameForAlias( string key, IDictionary <string, MergedCompiledCommandParameter> dict) { MergedCompiledCommandParameter mergedParam = dict[key]; if (null != mergedParam) { CompiledCommandParameter compiledParam = mergedParam.Parameter; if (null != compiledParam) { if (!String.IsNullOrEmpty(compiledParam.Name)) { return(compiledParam.Name); } } } return(String.Empty); }
internal Collection <MergedCompiledCommandParameter> AddMetadataForBinder(InternalParameterMetadata parameterMetadata, ParameterBinderAssociation binderAssociation) { if (parameterMetadata == null) { throw PSTraceSource.NewArgumentNullException("parameterMetadata"); } Collection <MergedCompiledCommandParameter> collection = new Collection <MergedCompiledCommandParameter>(); foreach (KeyValuePair <string, CompiledCommandParameter> pair in parameterMetadata.BindableParameters) { if (this.bindableParameters.ContainsKey(pair.Key)) { System.Management.Automation.MetadataException exception = new System.Management.Automation.MetadataException("ParameterNameAlreadyExistsForCommand", null, Metadata.ParameterNameAlreadyExistsForCommand, new object[] { pair.Key }); throw exception; } if (this.aliasedParameters.ContainsKey(pair.Key)) { System.Management.Automation.MetadataException exception2 = new System.Management.Automation.MetadataException("ParameterNameConflictsWithAlias", null, Metadata.ParameterNameConflictsWithAlias, new object[] { pair.Key, RetrieveParameterNameForAlias(pair.Key, this.aliasedParameters) }); throw exception2; } MergedCompiledCommandParameter parameter = new MergedCompiledCommandParameter(pair.Value, binderAssociation); this.bindableParameters.Add(pair.Key, parameter); collection.Add(parameter); foreach (string str in pair.Value.Aliases) { if (this.aliasedParameters.ContainsKey(str)) { System.Management.Automation.MetadataException exception3 = new System.Management.Automation.MetadataException("AliasParameterNameAlreadyExistsForCommand", null, Metadata.AliasParameterNameAlreadyExistsForCommand, new object[] { str }); throw exception3; } if (this.bindableParameters.ContainsKey(str)) { System.Management.Automation.MetadataException exception4 = new System.Management.Automation.MetadataException("ParameterNameConflictsWithAlias", null, Metadata.ParameterNameConflictsWithAlias, new object[] { RetrieveParameterNameForAlias(str, this.bindableParameters), pair.Value.Name }); throw exception4; } this.aliasedParameters.Add(str, parameter); } } return(collection); }
internal Collection<MergedCompiledCommandParameter> AddMetadataForBinder(InternalParameterMetadata parameterMetadata, ParameterBinderAssociation binderAssociation) { if (parameterMetadata == null) { throw PSTraceSource.NewArgumentNullException("parameterMetadata"); } Collection<MergedCompiledCommandParameter> collection = new Collection<MergedCompiledCommandParameter>(); foreach (KeyValuePair<string, CompiledCommandParameter> pair in parameterMetadata.BindableParameters) { if (this.bindableParameters.ContainsKey(pair.Key)) { System.Management.Automation.MetadataException exception = new System.Management.Automation.MetadataException("ParameterNameAlreadyExistsForCommand", null, Metadata.ParameterNameAlreadyExistsForCommand, new object[] { pair.Key }); throw exception; } if (this.aliasedParameters.ContainsKey(pair.Key)) { System.Management.Automation.MetadataException exception2 = new System.Management.Automation.MetadataException("ParameterNameConflictsWithAlias", null, Metadata.ParameterNameConflictsWithAlias, new object[] { pair.Key, RetrieveParameterNameForAlias(pair.Key, this.aliasedParameters) }); throw exception2; } MergedCompiledCommandParameter parameter = new MergedCompiledCommandParameter(pair.Value, binderAssociation); this.bindableParameters.Add(pair.Key, parameter); collection.Add(parameter); foreach (string str in pair.Value.Aliases) { if (this.aliasedParameters.ContainsKey(str)) { System.Management.Automation.MetadataException exception3 = new System.Management.Automation.MetadataException("AliasParameterNameAlreadyExistsForCommand", null, Metadata.AliasParameterNameAlreadyExistsForCommand, new object[] { str }); throw exception3; } if (this.bindableParameters.ContainsKey(str)) { System.Management.Automation.MetadataException exception4 = new System.Management.Automation.MetadataException("ParameterNameConflictsWithAlias", null, Metadata.ParameterNameConflictsWithAlias, new object[] { RetrieveParameterNameForAlias(str, this.bindableParameters), pair.Value.Name }); throw exception4; } this.aliasedParameters.Add(str, parameter); } } return collection; }
/// <summary> /// Constructs a container for the merged parameter metadata and /// parameter set specific metadata for a positional parameter /// </summary> /// internal PositionalCommandParameter(MergedCompiledCommandParameter parameter) { Parameter = parameter; }
private static void AddNewPosition(SortedDictionary <int, Dictionary <MergedCompiledCommandParameter, PositionalCommandParameter> > result, int positionInParameterSet, MergedCompiledCommandParameter parameter, ParameterSetSpecificMetadata parameterSetData) { if (result.ContainsKey(positionInParameterSet)) { Dictionary <MergedCompiledCommandParameter, PositionalCommandParameter> positionalCommandParameters = result[positionInParameterSet]; if (ContainsPositionalParameterInSet(positionalCommandParameters, parameter, parameterSetData.ParameterSetFlag)) { throw PSTraceSource.NewInvalidOperationException(); } if (positionalCommandParameters.ContainsKey(parameter)) { positionalCommandParameters[parameter].ParameterSetData.Add(parameterSetData); } else { PositionalCommandParameter parameter2 = new PositionalCommandParameter(parameter); parameter2.ParameterSetData.Add(parameterSetData); positionalCommandParameters.Add(parameter, parameter2); } } else { Dictionary <MergedCompiledCommandParameter, PositionalCommandParameter> dictionary2 = new Dictionary <MergedCompiledCommandParameter, PositionalCommandParameter>(); PositionalCommandParameter parameter3 = new PositionalCommandParameter(parameter) { ParameterSetData = { parameterSetData } }; dictionary2.Add(parameter, parameter3); result.Add(positionInParameterSet, dictionary2); } }
/// <summary> /// Binds the specified value to the specified parameter /// </summary> /// /// <param name="parameterValue"> /// The value to bind to the parameter /// </param> /// /// <param name="parameter"> /// The parameter to bind the value to. /// </param> /// /// <param name="flags"> /// Parameter binding flags for type coercion and validation. /// </param> /// /// <returns> /// True if the parameter was successfully bound. False if <paramref name="flags"/> /// specifies no coercion and the type does not match the parameter type. /// </returns> /// /// <exception cref="ParameterBindingParameterDefaultValueException"> /// If the parameter binder encounters an error getting the default value. /// </exception> /// private bool BindPipelineParameter( object parameterValue, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags) { bool result = false; if (parameterValue != AutomationNull.Value) { s_tracer.WriteLine("Adding PipelineParameter name={0}; value={1}", parameter.Parameter.Name, parameterValue ?? "null"); // Backup the default value BackupDefaultParameter(parameter); // Now bind the new value CommandParameterInternal param = CommandParameterInternal.CreateParameterWithArgument( PositionUtilities.EmptyExtent, parameter.Parameter.Name, "-" + parameter.Parameter.Name + ":", PositionUtilities.EmptyExtent, parameterValue, false); flags = flags & ~ParameterBindingFlags.DelayBindScriptBlock; result = BindParameter(_currentParameterSetFlag, param, parameter, flags); if (result) { // Now make sure to remember that the default value needs to be restored // if we get another pipeline object ParametersBoundThroughPipelineInput.Add(parameter); } } return result; }
internal XmlDocument BuildXmlFromComments() { this.doc = new XmlDocument(); XmlElement element1 = this.doc.CreateElement("command:command", HelpCommentsParser.commandURI); element1.SetAttribute("xmlns:maml", HelpCommentsParser.mamlURI); element1.SetAttribute("xmlns:command", HelpCommentsParser.commandURI); element1.SetAttribute("xmlns:dev", HelpCommentsParser.devURI); this.doc.AppendChild((XmlNode)element1); XmlElement element2 = this.doc.CreateElement("command:details", HelpCommentsParser.commandURI); element1.AppendChild((XmlNode)element2); XmlElement element3 = this.doc.CreateElement("command:name", HelpCommentsParser.commandURI); XmlText textNode1 = this.doc.CreateTextNode(this.commandName); element2.AppendChild((XmlNode)element3).AppendChild((XmlNode)textNode1); if (!string.IsNullOrEmpty(this.sections.synopsis)) { XmlElement element4 = this.doc.CreateElement("maml:description", HelpCommentsParser.mamlURI); XmlElement element5 = this.doc.CreateElement("maml:para", HelpCommentsParser.mamlURI); XmlText textNode2 = this.doc.CreateTextNode(this.sections.synopsis); element2.AppendChild((XmlNode)element4).AppendChild((XmlNode)element5).AppendChild((XmlNode)textNode2); } this.DetermineParameterDescriptions(); XmlElement element6 = this.doc.CreateElement("command:syntax", HelpCommentsParser.commandURI); MergedCommandParameterMetadata parameterMetadata = this.commandMetadata.StaticCommandParameterMetadata; if (parameterMetadata.ParameterSetCount > 0) { for (int i = 0; i < parameterMetadata.ParameterSetCount; ++i) { this.BuildSyntaxForParameterSet(element1, element6, parameterMetadata, i); } } else { this.BuildSyntaxForParameterSet(element1, element6, parameterMetadata, int.MaxValue); } XmlElement element7 = this.doc.CreateElement("command:parameters", HelpCommentsParser.commandURI); foreach (KeyValuePair <string, MergedCompiledCommandParameter> bindableParameter in parameterMetadata.BindableParameters) { MergedCompiledCommandParameter commandParameter = bindableParameter.Value; if (commandParameter.BinderAssociation != ParameterBinderAssociation.CommonParameters) { string key = bindableParameter.Key; string parameterDescription = this.GetParameterDescription(key); ParameterSetSpecificMetadata specificMetadata = (ParameterSetSpecificMetadata)null; bool isMandatory = false; bool valueFromPipeline = false; bool valueFromPipelineByPropertyName = false; string position = "named"; int num = 0; CompiledCommandParameter parameter = commandParameter.Parameter; parameter.ParameterSetData.TryGetValue("__AllParameterSets", out specificMetadata); while (specificMetadata == null && num < 32) { specificMetadata = parameter.GetParameterSetData((uint)(1 << num++)); } if (specificMetadata != null) { isMandatory = specificMetadata.IsMandatory; valueFromPipeline = specificMetadata.ValueFromPipeline; valueFromPipelineByPropertyName = specificMetadata.ValueFromPipelineByPropertyName; position = specificMetadata.IsPositional ? (1 + specificMetadata.Position).ToString((IFormatProvider)CultureInfo.InvariantCulture) : "named"; } XmlElement xmlElement = this.BuildXmlForParameter(key, isMandatory, valueFromPipeline, valueFromPipelineByPropertyName, position, parameter.Type, parameterDescription, false); element7.AppendChild((XmlNode)xmlElement); } } element1.AppendChild((XmlNode)element7); if (!string.IsNullOrEmpty(this.sections.description)) { XmlElement element4 = this.doc.CreateElement("maml:description", HelpCommentsParser.mamlURI); XmlElement element5 = this.doc.CreateElement("maml:para", HelpCommentsParser.mamlURI); XmlText textNode2 = this.doc.CreateTextNode(this.sections.description); element1.AppendChild((XmlNode)element4).AppendChild((XmlNode)element5).AppendChild((XmlNode)textNode2); } if (!string.IsNullOrEmpty(this.sections.notes)) { XmlElement element4 = this.doc.CreateElement("maml:alertSet", HelpCommentsParser.mamlURI); XmlElement element5 = this.doc.CreateElement("maml:alert", HelpCommentsParser.mamlURI); XmlElement element8 = this.doc.CreateElement("maml:para", HelpCommentsParser.mamlURI); XmlText textNode2 = this.doc.CreateTextNode(this.sections.notes); element1.AppendChild((XmlNode)element4).AppendChild((XmlNode)element5).AppendChild((XmlNode)element8).AppendChild((XmlNode)textNode2); } if (this.sections.examples.Count > 0) { XmlElement element4 = this.doc.CreateElement("command:examples", HelpCommentsParser.commandURI); int num = 1; foreach (string example in this.sections.examples) { XmlElement element5 = this.doc.CreateElement("command:example", HelpCommentsParser.commandURI); XmlElement element8 = this.doc.CreateElement("maml:title", HelpCommentsParser.mamlURI); XmlText textNode2 = this.doc.CreateTextNode(string.Format((IFormatProvider)CultureInfo.InvariantCulture, "\t\t\t\t-------------------------- {0} {1} --------------------------", (object)ResourceManagerCache.GetResourceString("HelpDisplayStrings", "ExampleUpperCase"), (object)num++)); element5.AppendChild((XmlNode)element8).AppendChild((XmlNode)textNode2); string prompt_str; string code_str; string remarks_str; this.GetExampleSections(example, out prompt_str, out code_str, out remarks_str); XmlElement element9 = this.doc.CreateElement("maml:introduction", HelpCommentsParser.mamlURI); XmlElement element10 = this.doc.CreateElement("maml:para", HelpCommentsParser.mamlURI); XmlText textNode3 = this.doc.CreateTextNode(prompt_str); element5.AppendChild((XmlNode)element9).AppendChild((XmlNode)element10).AppendChild((XmlNode)textNode3); XmlElement element11 = this.doc.CreateElement("dev:code", HelpCommentsParser.devURI); XmlText textNode4 = this.doc.CreateTextNode(code_str); element5.AppendChild((XmlNode)element11).AppendChild((XmlNode)textNode4); XmlElement element12 = this.doc.CreateElement("dev:remarks", HelpCommentsParser.devURI); XmlElement element13 = this.doc.CreateElement("maml:para", HelpCommentsParser.mamlURI); XmlText textNode5 = this.doc.CreateTextNode(remarks_str); element5.AppendChild((XmlNode)element12).AppendChild((XmlNode)element13).AppendChild((XmlNode)textNode5); for (int index = 0; index < 4; ++index) { element12.AppendChild((XmlNode)this.doc.CreateElement("maml:para", HelpCommentsParser.mamlURI)); } element4.AppendChild((XmlNode)element5); } element1.AppendChild((XmlNode)element4); } if (this.sections.inputs.Count > 0) { XmlElement element4 = this.doc.CreateElement("command:inputTypes", HelpCommentsParser.commandURI); foreach (string input in this.sections.inputs) { XmlElement element5 = this.doc.CreateElement("command:inputType", HelpCommentsParser.commandURI); XmlElement element8 = this.doc.CreateElement("dev:type", HelpCommentsParser.devURI); XmlElement element9 = this.doc.CreateElement("maml:name", HelpCommentsParser.mamlURI); XmlText textNode2 = this.doc.CreateTextNode(input); element4.AppendChild((XmlNode)element5).AppendChild((XmlNode)element8).AppendChild((XmlNode)element9).AppendChild((XmlNode)textNode2); } element1.AppendChild((XmlNode)element4); } IEnumerable enumerable = (IEnumerable)null; if (this.sections.outputs.Count > 0) { enumerable = (IEnumerable)this.sections.outputs; } else if (this.scriptBlock.OutputType.Count > 0) { enumerable = (IEnumerable)this.scriptBlock.OutputType; } if (enumerable != null) { XmlElement element4 = this.doc.CreateElement("command:returnValues", HelpCommentsParser.commandURI); foreach (object obj in enumerable) { XmlElement element5 = this.doc.CreateElement("command:returnValue", HelpCommentsParser.commandURI); XmlElement element8 = this.doc.CreateElement("dev:type", HelpCommentsParser.devURI); XmlElement element9 = this.doc.CreateElement("maml:name", HelpCommentsParser.mamlURI); if (!(obj is string text)) { text = ((PSTypeName)obj).Name; } XmlText textNode2 = this.doc.CreateTextNode(text); element4.AppendChild((XmlNode)element5).AppendChild((XmlNode)element8).AppendChild((XmlNode)element9).AppendChild((XmlNode)textNode2); } element1.AppendChild((XmlNode)element4); } if (this.sections.links.Count > 0) { XmlElement element4 = this.doc.CreateElement("maml:relatedLinks", HelpCommentsParser.mamlURI); foreach (string link in this.sections.links) { XmlElement element5 = this.doc.CreateElement("maml:navigationLink", HelpCommentsParser.mamlURI); XmlElement element8 = this.doc.CreateElement(Uri.IsWellFormedUriString(Uri.EscapeUriString(link), UriKind.Absolute) ? "maml:uri" : "maml:linkText", HelpCommentsParser.mamlURI); XmlText textNode2 = this.doc.CreateTextNode(link); element4.AppendChild((XmlNode)element5).AppendChild((XmlNode)element8).AppendChild((XmlNode)textNode2); } element1.AppendChild((XmlNode)element4); } return(this.doc); }
internal MergedCompiledCommandParameter GetMatchingParameter( string name, bool throwOnParameterNotFound, InvocationInfo invocationInfo) { if (string.IsNullOrEmpty(name)) { throw MergedCommandParameterMetadata.tracer.NewArgumentException(nameof(name)); } Collection <MergedCompiledCommandParameter> collection = new Collection <MergedCompiledCommandParameter>(); if (name.Length > 0 && SpecialCharacters.IsDash(name[0])) { name = name.Substring(1); } foreach (string key in this.bindableParameters.Keys) { if (this.nameCompareInfo.IsPrefix(key, name, CompareOptions.IgnoreCase)) { MergedCommandParameterMetadata.tracer.WriteLine("Found match: {0}", (object)key); if (string.Equals(key, name, StringComparison.OrdinalIgnoreCase)) { return(this.bindableParameters[key]); } collection.Add(this.bindableParameters[key]); } } foreach (string key in this.aliasedParameters.Keys) { if (this.nameCompareInfo.IsPrefix(key, name, CompareOptions.IgnoreCase)) { MergedCommandParameterMetadata.tracer.WriteLine("Found match: {0}", (object)key); if (string.Equals(key, name, StringComparison.OrdinalIgnoreCase)) { return(this.aliasedParameters[key]); } if (!collection.Contains(this.aliasedParameters[key])) { collection.Add(this.aliasedParameters[key]); } } } if (collection.Count > 1) { StringBuilder stringBuilder = new StringBuilder(); foreach (MergedCompiledCommandParameter commandParameter in collection) { stringBuilder.AppendFormat(" -{0}", (object)commandParameter.Parameter.Name); } ParameterBindingException bindingException = new ParameterBindingException(ErrorCategory.InvalidArgument, invocationInfo, (Token)null, name, (Type)null, (Type)null, "ParameterBinderStrings", "AmbiguousParameter", new object[1] { (object)stringBuilder }); MergedCommandParameterMetadata.tracer.TraceException((Exception)bindingException); throw bindingException; } if (collection.Count == 0 && throwOnParameterNotFound) { ParameterBindingException bindingException = new ParameterBindingException(ErrorCategory.InvalidArgument, invocationInfo, (Token)null, name, (Type)null, (Type)null, "ParameterBinderStrings", "NamedParameterNotFound", new object[0]); MergedCommandParameterMetadata.tracer.TraceException((Exception)bindingException); throw bindingException; } MergedCompiledCommandParameter commandParameter1 = (MergedCompiledCommandParameter)null; if (collection.Count > 0) { commandParameter1 = collection[0]; } return(commandParameter1); }
private bool BindValueFromPipeline(PSObject inputToOperateOn, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags) { bool flag = false; ParameterBinderBase.bindingTracer.WriteLine(((flags & ParameterBindingFlags.ShouldCoerceType) != ParameterBindingFlags.None) ? "Parameter [{0}] PIPELINE INPUT ValueFromPipeline WITH COERCION" : "Parameter [{0}] PIPELINE INPUT ValueFromPipeline NO COERCION", new object[] { parameter.Parameter.Name }); ParameterBindingException pbex = null; try { flag = this.BindPipelineParameter(inputToOperateOn, parameter, flags); } catch (ParameterBindingArgumentTransformationException exception2) { PSInvalidCastException innerException; if (exception2.InnerException is ArgumentTransformationMetadataException) { innerException = exception2.InnerException.InnerException as PSInvalidCastException; } else { innerException = exception2.InnerException as PSInvalidCastException; } if (innerException == null) { pbex = exception2; } flag = false; } catch (ParameterBindingValidationException exception4) { pbex = exception4; } catch (ParameterBindingParameterDefaultValueException exception5) { pbex = exception5; } catch (ParameterBindingException) { flag = false; } if (pbex != null) { if (!base.DefaultParameterBindingInUse) { throw pbex; } base.ThrowElaboratedBindingException(pbex); } return flag; }
internal override bool BindParameter(int parameterSets, CommandParameterInternal argument, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags) { bool flag = true; if ((((flags & ParameterBindingFlags.DelayBindScriptBlock) != ParameterBindingFlags.None) && parameter.Parameter.DoesParameterSetTakePipelineInput(parameterSets)) && argument.ArgumentSpecified) { object argumentValue = argument.ArgumentValue; if (((argumentValue is ScriptBlock) || (argumentValue is DelayedScriptBlockArgument)) && !IsParameterScriptBlockBindable(parameter)) { if (this._commandRuntime.IsClosed && this._commandRuntime.InputPipe.Empty) { ParameterBindingException exception = new ParameterBindingException(ErrorCategory.MetadataError, this.Command.MyInvocation, base.GetErrorExtent(argument), parameter.Parameter.Name, parameter.Parameter.Type, null, "ParameterBinderStrings", "ScriptBlockArgumentNoInput", new object[0]); throw exception; } ParameterBinderBase.bindingTracer.WriteLine("Adding ScriptBlock to delay-bind list for parameter '{0}'", new object[] { parameter.Parameter.Name }); DelayedScriptBlockArgument argument2 = argumentValue as DelayedScriptBlockArgument; if (argument2 == null) { argument2 = new DelayedScriptBlockArgument { _argument = argument, _parameterBinder = this }; } if (!this._delayBindScriptBlocks.ContainsKey(parameter)) { this._delayBindScriptBlocks.Add(parameter, argument2); } if (parameter.Parameter.ParameterSetFlags != 0) { base._currentParameterSetFlag &= parameter.Parameter.ParameterSetFlags; } base.UnboundParameters.Remove(parameter); if (!base.BoundParameters.ContainsKey(parameter.Parameter.Name)) { base.BoundParameters.Add(parameter.Parameter.Name, parameter); } if (!base.BoundArguments.ContainsKey(parameter.Parameter.Name)) { base.BoundArguments.Add(parameter.Parameter.Name, argument); } if (base.DefaultParameterBinder.RecordBoundParameters && !base.DefaultParameterBinder.CommandLineParameters.ContainsKey(parameter.Parameter.Name)) { base.DefaultParameterBinder.CommandLineParameters.Add(parameter.Parameter.Name, argument2); } flag = false; } } bool flag2 = false; if (flag) { try { flag2 = this.BindParameter(argument, parameter, flags); } catch (Exception innerException) { bool flag3 = true; if ((flags & ParameterBindingFlags.ShouldCoerceType) == ParameterBindingFlags.None) { while (innerException != null) { if (innerException is PSInvalidCastException) { flag3 = false; break; } innerException = innerException.InnerException; } } if (flag3) { throw; } } } return flag2; }
private static bool ContainsPositionalParameterInSet(Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter> positionalCommandParameters, MergedCompiledCommandParameter parameter, int parameterSet) { bool flag = false; foreach (KeyValuePair<MergedCompiledCommandParameter, PositionalCommandParameter> pair in positionalCommandParameters) { if (pair.Key == parameter) { continue; } foreach (ParameterSetSpecificMetadata metadata in pair.Value.ParameterSetData) { if (((metadata.ParameterSetFlag & parameterSet) != 0) || (metadata.ParameterSetFlag == parameterSet)) { flag = true; break; } } if (flag) { return flag; } } return flag; }
internal void BindUnboundScriptParameterWithDefaultValue(MergedCompiledCommandParameter parameter) { ScriptParameterBinder defaultParameterBinder = (ScriptParameterBinder) this.DefaultParameterBinder; ScriptBlock script = defaultParameterBinder.Script; if (script.RuntimeDefinedParameters.ContainsKey(parameter.Parameter.Name)) { bool recordBoundParameters = defaultParameterBinder.RecordBoundParameters; try { defaultParameterBinder.RecordBoundParameters = false; RuntimeDefinedParameter parameter2 = script.RuntimeDefinedParameters[parameter.Parameter.Name]; IList implicitUsingParameters = null; if (this.DefaultParameterBinder.CommandLineParameters != null) { implicitUsingParameters = this.DefaultParameterBinder.CommandLineParameters.GetImplicitUsingParameters(); } object defaultScriptParameterValue = defaultParameterBinder.GetDefaultScriptParameterValue(parameter2, implicitUsingParameters); this.SaveDefaultScriptParameterValue(parameter.Parameter.Name, defaultScriptParameterValue); CommandParameterInternal argument = CommandParameterInternal.CreateParameterWithArgument(PositionUtilities.EmptyExtent, parameter.Parameter.Name, "-" + parameter.Parameter.Name + ":", PositionUtilities.EmptyExtent, defaultScriptParameterValue, false); ParameterBindingFlags isDefaultValue = ParameterBindingFlags.IsDefaultValue; if (parameter2.IsSet) { isDefaultValue |= ParameterBindingFlags.ShouldCoerceType; } this.BindParameter(int.MaxValue, argument, parameter, isDefaultValue); } finally { defaultParameterBinder.RecordBoundParameters = recordBoundParameters; } } }
internal virtual bool BindParameter(int parameterSets, CommandParameterInternal argument, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags) { bool flag = false; if (parameter.BinderAssociation == ParameterBinderAssociation.DeclaredFormalParameters) { flag = this.DefaultParameterBinder.BindParameter(argument, parameter.Parameter, flags); } if (flag && ((flags & ParameterBindingFlags.IsDefaultValue) == ParameterBindingFlags.None)) { this.UnboundParameters.Remove(parameter); this.BoundParameters.Add(parameter.Parameter.Name, parameter); } return flag; }
internal PositionalCommandParameter(MergedCompiledCommandParameter parameter) { using (PositionalCommandParameter.tracer.TraceConstructor((object)this)) this.parameter = parameter; }
private static bool ContainsPositionalParameterInSet(Dictionary <MergedCompiledCommandParameter, PositionalCommandParameter> positionalCommandParameters, MergedCompiledCommandParameter parameter, int parameterSet) { bool flag = false; foreach (KeyValuePair <MergedCompiledCommandParameter, PositionalCommandParameter> pair in positionalCommandParameters) { if (pair.Key == parameter) { continue; } foreach (ParameterSetSpecificMetadata metadata in pair.Value.ParameterSetData) { if (((metadata.ParameterSetFlag & parameterSet) != 0) || (metadata.ParameterSetFlag == parameterSet)) { flag = true; break; } } if (flag) { return(flag); } } return(flag); }
private bool BindParameter(CommandParameterInternal argument, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags) { bool flag = false; switch (parameter.BinderAssociation) { case ParameterBinderAssociation.DeclaredFormalParameters: flag = base.DefaultParameterBinder.BindParameter(argument, parameter.Parameter, flags); break; case ParameterBinderAssociation.DynamicParameters: if (this._dynamicParameterBinder != null) { flag = this._dynamicParameterBinder.BindParameter(argument, parameter.Parameter, flags); } break; case ParameterBinderAssociation.CommonParameters: flag = this.CommonParametersBinder.BindParameter(argument, parameter.Parameter, flags); break; case ParameterBinderAssociation.ShouldProcessParameters: flag = this.ShouldProcessParametersBinder.BindParameter(argument, parameter.Parameter, flags); break; case ParameterBinderAssociation.TransactionParameters: flag = this.TransactionParametersBinder.BindParameter(argument, parameter.Parameter, flags); break; case ParameterBinderAssociation.PagingParameters: flag = this.PagingParametersBinder.BindParameter(argument, parameter.Parameter, flags); break; } if (flag && ((flags & ParameterBindingFlags.IsDefaultValue) == ParameterBindingFlags.None)) { if (parameter.Parameter.ParameterSetFlags != 0) { base._currentParameterSetFlag &= parameter.Parameter.ParameterSetFlags; } base.UnboundParameters.Remove(parameter); if (!base.BoundParameters.ContainsKey(parameter.Parameter.Name)) { base.BoundParameters.Add(parameter.Parameter.Name, parameter); } if (!base.BoundArguments.ContainsKey(parameter.Parameter.Name)) { base.BoundArguments.Add(parameter.Parameter.Name, argument); } } return flag; }
} // BindParameters /// <summary> /// Determines if a ScriptBlock can be bound directly to the type of the specified parameter /// </summary> /// /// <param name="parameter"> /// The metadata of the parameter to check the type of. /// </param> /// /// <returns> /// true if the parameter type is Object, ScriptBlock, derived from ScriptBlock, a /// collection of ScriptBlocks, a collection of Objects, or a collection of types derived from /// ScriptBlock. /// False otherwise. /// </returns> /// private static bool IsParameterScriptBlockBindable(MergedCompiledCommandParameter parameter) { bool result = false; Type parameterType = parameter.Parameter.Type; do // false loop { if (parameterType == typeof(Object)) { result = true; break; } if (parameterType == typeof(ScriptBlock)) { result = true; break; } if (parameterType.IsSubclassOf(typeof(ScriptBlock))) { result = true; break; } ParameterCollectionTypeInformation parameterCollectionTypeInfo = parameter.Parameter.CollectionTypeInformation; if (parameterCollectionTypeInfo.ParameterCollectionType != ParameterCollectionType.NotCollection) { if (parameterCollectionTypeInfo.ElementType == typeof(object)) { result = true; break; } if (parameterCollectionTypeInfo.ElementType == typeof(ScriptBlock)) { result = true; break; } if (parameterCollectionTypeInfo.ElementType.IsSubclassOf(typeof(ScriptBlock))) { result = true; break; } } } while (false); s_tracer.WriteLine("IsParameterScriptBlockBindable: result = {0}", result); return result; }
private bool BindPipelineParameter(object parameterValue, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags) { bool flag = false; if (parameterValue != AutomationNull.Value) { object[] args = new object[] { parameter.Parameter.Name, parameterValue ?? "null" }; _tracer.WriteLine("Adding PipelineParameter name={0}; value={1}", args); this.BackupDefaultParameter(parameter); CommandParameterInternal argument = CommandParameterInternal.CreateParameterWithArgument(PositionUtilities.EmptyExtent, parameter.Parameter.Name, "-" + parameter.Parameter.Name + ":", PositionUtilities.EmptyExtent, parameterValue, false); flags &= ~ParameterBindingFlags.DelayBindScriptBlock; flag = this.BindParameter(base._currentParameterSetFlag, argument, parameter, flags); if (flag) { base.ParametersBoundThroughPipelineInput.Add(parameter); } } return flag; }
/// <summary> /// Binds the specified argument to the specified parameter using the appropriate /// parameter binder. /// </summary> /// /// <param name="argument"> /// The argument to be bound. /// </param> /// /// <param name="parameter"> /// The metadata for the parameter to bind the argument to. /// </param> /// /// <param name="flags"> /// Flags for type coercion and validation. /// </param> /// /// <returns> /// True if the parameter was successfully bound. False if <paramref name="flags"/> /// has the flag <see cref="ParameterBindingFlags.ShouldCoerceType"/> set and the type does not match the parameter type. /// </returns> /// private bool BindParameter( CommandParameterInternal argument, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags) { bool result = false; switch (parameter.BinderAssociation) { case ParameterBinderAssociation.DeclaredFormalParameters: result = DefaultParameterBinder.BindParameter( argument, parameter.Parameter, flags); break; case ParameterBinderAssociation.CommonParameters: result = CommonParametersBinder.BindParameter( argument, parameter.Parameter, flags); break; case ParameterBinderAssociation.ShouldProcessParameters: Diagnostics.Assert( _commandMetadata.SupportsShouldProcess, "The metadata for the ShouldProcessParameters should only be available if the command supports ShouldProcess"); result = ShouldProcessParametersBinder.BindParameter( argument, parameter.Parameter, flags); break; case ParameterBinderAssociation.PagingParameters: Diagnostics.Assert( _commandMetadata.SupportsPaging, "The metadata for the PagingParameters should only be available if the command supports paging"); result = PagingParametersBinder.BindParameter( argument, parameter.Parameter, flags); break; case ParameterBinderAssociation.TransactionParameters: Diagnostics.Assert( _commandMetadata.SupportsTransactions, "The metadata for the TransactionsParameters should only be available if the command supports transactions"); result = TransactionParametersBinder.BindParameter( argument, parameter.Parameter, flags); break; case ParameterBinderAssociation.DynamicParameters: Diagnostics.Assert( _commandMetadata.ImplementsDynamicParameters, "The metadata for the dynamic parameters should only be available if the command supports IDynamicParameters"); if (_dynamicParameterBinder != null) { result = _dynamicParameterBinder.BindParameter( argument, parameter.Parameter, flags); } break; } if (result && ((flags & ParameterBindingFlags.IsDefaultValue) == 0)) { // Update the current valid parameter set flags if (parameter.Parameter.ParameterSetFlags != 0) { _currentParameterSetFlag &= parameter.Parameter.ParameterSetFlags; } UnboundParameters.Remove(parameter); if (!BoundParameters.ContainsKey(parameter.Parameter.Name)) { BoundParameters.Add(parameter.Parameter.Name, parameter); } if (!BoundArguments.ContainsKey(parameter.Parameter.Name)) { BoundArguments.Add(parameter.Parameter.Name, argument); } if (parameter.Parameter.ObsoleteAttribute != null && (flags & ParameterBindingFlags.IsDefaultValue) == 0 && !BoundObsoleteParameterNames.Contains(parameter.Parameter.Name)) { string obsoleteWarning = String.Format( CultureInfo.InvariantCulture, ParameterBinderStrings.UseOfDeprecatedParameterWarning, parameter.Parameter.Name, parameter.Parameter.ObsoleteAttribute.Message); var warningRecord = new WarningRecord(ParameterBinderBase.FQIDParameterObsolete, obsoleteWarning); BoundObsoleteParameterNames.Add(parameter.Parameter.Name); if (ObsoleteParameterWarningList == null) ObsoleteParameterWarningList = new List<WarningRecord>(); ObsoleteParameterWarningList.Add(warningRecord); } } return result; }
private bool BindValueFromPipelineByPropertyName(PSObject inputToOperateOn, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags) { bool flag = false; ParameterBinderBase.bindingTracer.WriteLine(((flags & ParameterBindingFlags.ShouldCoerceType) != ParameterBindingFlags.None) ? "Parameter [{0}] PIPELINE INPUT ValueFromPipelineByPropertyName WITH COERCION" : "Parameter [{0}] PIPELINE INPUT ValueFromPipelineByPropertyName NO COERCION", new object[] { parameter.Parameter.Name }); PSMemberInfo info = inputToOperateOn.Properties[parameter.Parameter.Name]; if (info == null) { foreach (string str in parameter.Parameter.Aliases) { info = inputToOperateOn.Properties[str]; if (info != null) { break; } } } if (info != null) { ParameterBindingException pbex = null; try { flag = this.BindPipelineParameter(info.Value, parameter, flags); } catch (ParameterBindingArgumentTransformationException exception2) { pbex = exception2; } catch (ParameterBindingValidationException exception3) { pbex = exception3; } catch (ParameterBindingParameterDefaultValueException exception4) { pbex = exception4; } catch (ParameterBindingException) { flag = false; } if (pbex == null) { return flag; } if (!base.DefaultParameterBindingInUse) { throw pbex; } base.ThrowElaboratedBindingException(pbex); } return flag; }
private bool BindValueFromPipeline( PSObject inputToOperateOn, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags) { bool bindResult = false; // Attempt binding the value from the pipeline // without type coercion ParameterBinderBase.bindingTracer.WriteLine( ((flags & ParameterBindingFlags.ShouldCoerceType) != 0) ? "Parameter [{0}] PIPELINE INPUT ValueFromPipeline WITH COERCION" : "Parameter [{0}] PIPELINE INPUT ValueFromPipeline NO COERCION", parameter.Parameter.Name); ParameterBindingException parameterBindingException = null; try { bindResult = BindPipelineParameter(inputToOperateOn, parameter, flags); } catch (ParameterBindingArgumentTransformationException e) { PSInvalidCastException invalidCast; if (e.InnerException is ArgumentTransformationMetadataException) { invalidCast = e.InnerException.InnerException as PSInvalidCastException; } else { invalidCast = e.InnerException as PSInvalidCastException; } if (invalidCast == null) { parameterBindingException = e; } // Just ignore and continue; bindResult = false; } catch (ParameterBindingValidationException e) { parameterBindingException = e; } catch (ParameterBindingParameterDefaultValueException e) { parameterBindingException = e; } catch (ParameterBindingException) { // Just ignore and continue; bindResult = false; } if (parameterBindingException != null) { if (!DefaultParameterBindingInUse) { throw parameterBindingException; } else { ThrowElaboratedBindingException(parameterBindingException); } } return bindResult; }
} // ReplaceMetadata /// <summary> /// Merges the specified metadata with the other metadata already defined /// in this object. /// </summary> /// /// <param name="parameterMetadata"> /// The compiled metadata for the type to be merged. /// </param> /// /// <param name="binderAssociation"> /// The type of binder that the CommandProcessor will use to bind /// the parameters for <paramref name="parameterMetadata"/> /// </param> /// /// <returns> /// A collection of the merged parameter metadata that was added. /// </returns> /// /// <exception cref="MetadataException"> /// If a parameter name or alias described in the <paramref name="parameterMetadata"/> already /// exists. /// </exception> /// internal Collection<MergedCompiledCommandParameter> AddMetadataForBinder( InternalParameterMetadata parameterMetadata, ParameterBinderAssociation binderAssociation) { if (parameterMetadata == null) { throw PSTraceSource.NewArgumentNullException("parameterMetadata"); } Collection<MergedCompiledCommandParameter> result = new Collection<MergedCompiledCommandParameter>(); // Merge in the bindable parameters foreach (KeyValuePair<string, CompiledCommandParameter> bindableParameter in parameterMetadata.BindableParameters) { if (_bindableParameters.ContainsKey(bindableParameter.Key)) { MetadataException exception = new MetadataException( "ParameterNameAlreadyExistsForCommand", null, Metadata.ParameterNameAlreadyExistsForCommand, bindableParameter.Key); throw exception; } // NTRAID#Windows Out Of Band Releases-926371-2005/12/27-JonN if (_aliasedParameters.ContainsKey(bindableParameter.Key)) { MetadataException exception = new MetadataException( "ParameterNameConflictsWithAlias", null, Metadata.ParameterNameConflictsWithAlias, bindableParameter.Key, RetrieveParameterNameForAlias(bindableParameter.Key, _aliasedParameters)); throw exception; } MergedCompiledCommandParameter mergedParameter = new MergedCompiledCommandParameter(bindableParameter.Value, binderAssociation); _bindableParameters.Add(bindableParameter.Key, mergedParameter); result.Add(mergedParameter); // Merge in the aliases foreach (string aliasName in bindableParameter.Value.Aliases) { if (_aliasedParameters.ContainsKey(aliasName)) { MetadataException exception = new MetadataException( "AliasParameterNameAlreadyExistsForCommand", null, Metadata.AliasParameterNameAlreadyExistsForCommand, aliasName); throw exception; } // NTRAID#Windows Out Of Band Releases-926371-2005/12/27-JonN if (_bindableParameters.ContainsKey(aliasName)) { MetadataException exception = new MetadataException( "ParameterNameConflictsWithAlias", null, Metadata.ParameterNameConflictsWithAlias, RetrieveParameterNameForAlias(aliasName, _bindableParameters), bindableParameter.Value.Name); throw exception; } _aliasedParameters.Add(aliasName, mergedParameter); } } return result; }
internal XmlDocument BuildXmlFromComments() { this.doc = new XmlDocument(); XmlElement newChild = this.doc.CreateElement("command:command", commandURI); newChild.SetAttribute("xmlns:maml", mamlURI); newChild.SetAttribute("xmlns:command", commandURI); newChild.SetAttribute("xmlns:dev", devURI); this.doc.AppendChild(newChild); XmlElement element2 = this.doc.CreateElement("command:details", commandURI); newChild.AppendChild(element2); XmlElement element3 = this.doc.CreateElement("command:name", commandURI); XmlText text = this.doc.CreateTextNode(this.commandName); element2.AppendChild(element3).AppendChild(text); if (!string.IsNullOrEmpty(this._sections.Synopsis)) { XmlElement element4 = this.doc.CreateElement("maml:description", mamlURI); XmlElement element5 = this.doc.CreateElement("maml:para", mamlURI); XmlText text2 = this.doc.CreateTextNode(this._sections.Synopsis); element2.AppendChild(element4).AppendChild(element5).AppendChild(text2); } this.DetermineParameterDescriptions(); XmlElement syntax = this.doc.CreateElement("command:syntax", commandURI); MergedCommandParameterMetadata staticCommandParameterMetadata = this.commandMetadata.StaticCommandParameterMetadata; if (staticCommandParameterMetadata.ParameterSetCount > 0) { for (int i = 0; i < staticCommandParameterMetadata.ParameterSetCount; i++) { this.BuildSyntaxForParameterSet(newChild, syntax, staticCommandParameterMetadata, i); } } else { this.BuildSyntaxForParameterSet(newChild, syntax, staticCommandParameterMetadata, 0x7fffffff); } XmlElement element7 = this.doc.CreateElement("command:parameters", commandURI); foreach (KeyValuePair <string, MergedCompiledCommandParameter> pair in staticCommandParameterMetadata.BindableParameters) { MergedCompiledCommandParameter parameter = pair.Value; if (parameter.BinderAssociation != ParameterBinderAssociation.CommonParameters) { ParameterSetSpecificMetadata parameterSetData; string key = pair.Key; string parameterDescription = this.GetParameterDescription(key); bool isMandatory = false; bool valueFromPipeline = false; bool valueFromPipelineByPropertyName = false; string position = "named"; int num2 = 0; CompiledCommandParameter parameter2 = parameter.Parameter; parameter2.ParameterSetData.TryGetValue("__AllParameterSets", out parameterSetData); while ((parameterSetData == null) && (num2 < 0x20)) { parameterSetData = parameter2.GetParameterSetData(((int)1) << num2++); } if (parameterSetData != null) { isMandatory = parameterSetData.IsMandatory; valueFromPipeline = parameterSetData.ValueFromPipeline; valueFromPipelineByPropertyName = parameterSetData.ValueFromPipelineByPropertyName; position = parameterSetData.IsPositional ? ((1 + parameterSetData.Position)).ToString(CultureInfo.InvariantCulture) : "named"; } Collection <System.Attribute> compiledAttributes = parameter2.CompiledAttributes; bool supportsWildcards = compiledAttributes.OfType <SupportsWildcardsAttribute>().Any <SupportsWildcardsAttribute>(); string help = ""; object obj2 = null; PSDefaultValueAttribute attribute = compiledAttributes.OfType <PSDefaultValueAttribute>().FirstOrDefault <PSDefaultValueAttribute>(); if (attribute != null) { help = attribute.Help; if (string.IsNullOrEmpty(help)) { obj2 = attribute.Value; } } if (string.IsNullOrEmpty(help)) { RuntimeDefinedParameter parameter3; if ((obj2 == null) && this.scriptBlock.RuntimeDefinedParameters.TryGetValue(key, out parameter3)) { obj2 = parameter3.Value; } Compiler.DefaultValueExpressionWrapper wrapper = obj2 as Compiler.DefaultValueExpressionWrapper; if (wrapper != null) { help = wrapper.Expression.Extent.Text; } else if (obj2 != null) { help = PSObject.ToStringParser(null, obj2); } } XmlElement element8 = this.BuildXmlForParameter(key, isMandatory, valueFromPipeline, valueFromPipelineByPropertyName, position, parameter2.Type, parameterDescription, supportsWildcards, help, false); element7.AppendChild(element8); } } newChild.AppendChild(element7); if (!string.IsNullOrEmpty(this._sections.Description)) { XmlElement element9 = this.doc.CreateElement("maml:description", mamlURI); XmlElement element10 = this.doc.CreateElement("maml:para", mamlURI); XmlText text3 = this.doc.CreateTextNode(this._sections.Description); newChild.AppendChild(element9).AppendChild(element10).AppendChild(text3); } if (!string.IsNullOrEmpty(this._sections.Notes)) { XmlElement element11 = this.doc.CreateElement("maml:alertSet", mamlURI); XmlElement element12 = this.doc.CreateElement("maml:alert", mamlURI); XmlElement element13 = this.doc.CreateElement("maml:para", mamlURI); XmlText text4 = this.doc.CreateTextNode(this._sections.Notes); newChild.AppendChild(element11).AppendChild(element12).AppendChild(element13).AppendChild(text4); } if (this._examples.Count > 0) { XmlElement element14 = this.doc.CreateElement("command:examples", commandURI); int num3 = 1; foreach (string str5 in this._examples) { string str7; string str8; string str9; XmlElement element15 = this.doc.CreateElement("command:example", commandURI); XmlElement element16 = this.doc.CreateElement("maml:title", mamlURI); string str6 = string.Format(CultureInfo.InvariantCulture, "\t\t\t\t-------------------------- {0} {1} --------------------------", new object[] { HelpDisplayStrings.ExampleUpperCase, num3++ }); XmlText text5 = this.doc.CreateTextNode(str6); element15.AppendChild(element16).AppendChild(text5); GetExampleSections(str5, out str7, out str8, out str9); XmlElement element17 = this.doc.CreateElement("maml:introduction", mamlURI); XmlElement element18 = this.doc.CreateElement("maml:para", mamlURI); XmlText text6 = this.doc.CreateTextNode(str7); element15.AppendChild(element17).AppendChild(element18).AppendChild(text6); XmlElement element19 = this.doc.CreateElement("dev:code", devURI); XmlText text7 = this.doc.CreateTextNode(str8); element15.AppendChild(element19).AppendChild(text7); XmlElement element20 = this.doc.CreateElement("dev:remarks", devURI); XmlElement element21 = this.doc.CreateElement("maml:para", mamlURI); XmlText text8 = this.doc.CreateTextNode(str9); element15.AppendChild(element20).AppendChild(element21).AppendChild(text8); for (int j = 0; j < 4; j++) { element20.AppendChild(this.doc.CreateElement("maml:para", mamlURI)); } element14.AppendChild(element15); } newChild.AppendChild(element14); } if (this._inputs.Count > 0) { XmlElement element22 = this.doc.CreateElement("command:inputTypes", commandURI); foreach (string str10 in this._inputs) { XmlElement element23 = this.doc.CreateElement("command:inputType", commandURI); XmlElement element24 = this.doc.CreateElement("dev:type", devURI); XmlElement element25 = this.doc.CreateElement("maml:name", mamlURI); XmlText text9 = this.doc.CreateTextNode(str10); element22.AppendChild(element23).AppendChild(element24).AppendChild(element25).AppendChild(text9); } newChild.AppendChild(element22); } IEnumerable outputType = null; if (this._outputs.Count > 0) { outputType = this._outputs; } else if (this.scriptBlock.OutputType.Count > 0) { outputType = this.scriptBlock.OutputType; } if (outputType != null) { XmlElement element26 = this.doc.CreateElement("command:returnValues", commandURI); foreach (object obj3 in outputType) { XmlElement element27 = this.doc.CreateElement("command:returnValue", commandURI); XmlElement element28 = this.doc.CreateElement("dev:type", devURI); XmlElement element29 = this.doc.CreateElement("maml:name", mamlURI); string str11 = (obj3 as string) ?? ((PSTypeName)obj3).Name; XmlText text10 = this.doc.CreateTextNode(str11); element26.AppendChild(element27).AppendChild(element28).AppendChild(element29).AppendChild(text10); } newChild.AppendChild(element26); } if (this._links.Count > 0) { XmlElement element30 = this.doc.CreateElement("maml:relatedLinks", mamlURI); foreach (string str12 in this._links) { XmlElement element31 = this.doc.CreateElement("maml:navigationLink", mamlURI); string qualifiedName = Uri.IsWellFormedUriString(Uri.EscapeUriString(str12), UriKind.Absolute) ? "maml:uri" : "maml:linkText"; XmlElement element32 = this.doc.CreateElement(qualifiedName, mamlURI); XmlText text11 = this.doc.CreateTextNode(str12); element30.AppendChild(element31).AppendChild(element32).AppendChild(text11); } newChild.AppendChild(element30); } return(this.doc); }
public ParameterMetadata ResolveParameter(string name) { MergedCompiledCommandParameter parameter = this.GetMergedCommandParameterMetdata().GetMatchingParameter(name, true, true, null); return(this.Parameters[parameter.Parameter.Name]); }
private bool PrepareCommandElements(ExecutionContext context) { int num = 0; bool dotSource = this._commandAst.InvocationOperator == TokenKind.Dot; CommandProcessorBase base2 = null; string resolvedCommandName = null; bool flag2 = false; try { base2 = this.PrepareFromAst(context, out resolvedCommandName) ?? context.CreateCommand(resolvedCommandName, dotSource); } catch (RuntimeException exception) { CommandProcessorBase.CheckForSevereException(exception); if ((this._commandAst.IsInWorkflow() && (resolvedCommandName != null)) && CompletionCompleters.PseudoWorkflowCommands.Contains<string>(resolvedCommandName, StringComparer.OrdinalIgnoreCase)) { flag2 = true; } else { return false; } } CommandProcessor commandProcessor = base2 as CommandProcessor; ScriptCommandProcessorBase base3 = base2 as ScriptCommandProcessorBase; bool flag3 = (commandProcessor != null) && commandProcessor.CommandInfo.ImplementsDynamicParameters; List<object> list = flag3 ? new List<object>(this._commandElements.Count) : null; if (((commandProcessor != null) || (base3 != null)) || flag2) { num++; while (num < this._commandElements.Count) { CommandParameterAst parameterAst = this._commandElements[num] as CommandParameterAst; if (parameterAst != null) { if (list != null) { list.Add(parameterAst.Extent.Text); } AstPair item = (parameterAst.Argument != null) ? new AstPair(parameterAst, parameterAst.Argument) : new AstPair(parameterAst); this._arguments.Add(item); } else { StringConstantExpressionAst ast2 = this._commandElements[num] as StringConstantExpressionAst; if ((ast2 == null) || !ast2.Value.Trim().Equals("-", StringComparison.OrdinalIgnoreCase)) { ExpressionAst argumentAst = this._commandElements[num] as ExpressionAst; if (argumentAst != null) { if (list != null) { list.Add(argumentAst.Extent.Text); } this._arguments.Add(new AstPair(null, argumentAst)); } } } num++; } } if (commandProcessor != null) { this._function = false; if (flag3) { ParameterBinderController.AddArgumentsToCommandProcessor(commandProcessor, list.ToArray()); bool flag4 = false; bool flag5 = false; do { CommandProcessorBase currentCommandProcessor = context.CurrentCommandProcessor; try { context.CurrentCommandProcessor = commandProcessor; commandProcessor.SetCurrentScopeToExecutionScope(); if (!flag4) { commandProcessor.CmdletParameterBinderController.BindCommandLineParametersNoValidation(commandProcessor.arguments); } else { flag5 = true; commandProcessor.CmdletParameterBinderController.ClearUnboundArguments(); commandProcessor.CmdletParameterBinderController.BindCommandLineParametersNoValidation(new Collection<CommandParameterInternal>()); } } catch (ParameterBindingException exception2) { if ((exception2.ErrorId == "MissingArgument") || (exception2.ErrorId == "AmbiguousParameter")) { flag4 = true; } } catch (Exception exception3) { CommandProcessorBase.CheckForSevereException(exception3); } finally { context.CurrentCommandProcessor = currentCommandProcessor; commandProcessor.RestorePreviousScope(); } } while (flag4 && !flag5); } this._commandInfo = commandProcessor.CommandInfo; this._commandName = commandProcessor.CommandInfo.Name; this._bindableParameters = commandProcessor.CmdletParameterBinderController.BindableParameters; this._defaultParameterSetFlag = commandProcessor.CommandInfo.CommandMetadata.DefaultParameterSetFlag; } else if (base3 != null) { this._function = true; this._commandInfo = base3.CommandInfo; this._commandName = base3.CommandInfo.Name; this._bindableParameters = base3.ScriptParameterBinderController.BindableParameters; this._defaultParameterSetFlag = 0; } else if (!flag2) { return false; } if (this._commandAst.IsInWorkflow()) { Type type = Type.GetType("Microsoft.PowerShell.Workflow.AstToWorkflowConverter, Microsoft.PowerShell.Activities, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); if (type != null) { Dictionary<string, Type> dictionary = (Dictionary<string, Type>) type.GetMethod("GetActivityParameters").Invoke(null, new object[] { this._commandAst }); if (dictionary != null) { bool flag6 = dictionary.ContainsKey("PSComputerName") && !dictionary.ContainsKey("ComputerName"); List<MergedCompiledCommandParameter> source = new List<MergedCompiledCommandParameter>(); Collection<Attribute> attributes = new Collection<Attribute> { new ParameterAttribute() }; foreach (KeyValuePair<string, Type> pair2 in dictionary) { if (flag2 || !this._bindableParameters.BindableParameters.ContainsKey(pair2.Key)) { Type actualActivityParameterType = GetActualActivityParameterType(pair2.Value); RuntimeDefinedParameter runtimeDefinedParameter = new RuntimeDefinedParameter(pair2.Key, actualActivityParameterType, attributes); CompiledCommandParameter parameter = new CompiledCommandParameter(runtimeDefinedParameter, false) { IsInAllSets = true }; MergedCompiledCommandParameter parameter3 = new MergedCompiledCommandParameter(parameter, ParameterBinderAssociation.DeclaredFormalParameters); source.Add(parameter3); } } if (source.Any<MergedCompiledCommandParameter>()) { MergedCommandParameterMetadata metadata = new MergedCommandParameterMetadata(); if (!flag2) { metadata.ReplaceMetadata(this._bindableParameters); } foreach (MergedCompiledCommandParameter parameter5 in source) { metadata.BindableParameters.Add(parameter5.Parameter.Name, parameter5); } this._bindableParameters = metadata; } foreach (string str2 in ignoredWorkflowParameters) { if (this._bindableParameters.BindableParameters.ContainsKey(str2)) { this._bindableParameters.BindableParameters.Remove(str2); } } if (this._bindableParameters.BindableParameters.ContainsKey("ComputerName") && flag6) { this._bindableParameters.BindableParameters.Remove("ComputerName"); string key = (from aliasPair in this._bindableParameters.AliasedParameters where string.Equals("ComputerName", aliasPair.Value.Parameter.Name) select aliasPair.Key).FirstOrDefault<string>(); this._bindableParameters.AliasedParameters.Remove(key); } } } } this._unboundParameters.AddRange(this._bindableParameters.BindableParameters.Values); CommandBaseAst ast4 = null; PipelineAst parent = this._commandAst.Parent as PipelineAst; if (parent.PipelineElements.Count > 1) { foreach (CommandBaseAst ast6 in parent.PipelineElements) { if (ast6.GetHashCode() == this._commandAst.GetHashCode()) { this._isPipelineInputExpected = ast4 != null; if (this._isPipelineInputExpected) { this._pipelineInputType = typeof(object); } break; } ast4 = ast6; } } return true; }
/// <summary> /// Restores the specified parameter to the original value. /// </summary> /// /// <param name="argumentToBind"> /// The argument containing the value to restore. /// </param> /// /// <param name="parameter"> /// The metadata for the parameter to restore. /// </param> /// /// <returns> /// True if the parameter was restored correctly, or false otherwise. /// </returns> /// private bool RestoreParameter(CommandParameterInternal argumentToBind, MergedCompiledCommandParameter parameter) { switch (parameter.BinderAssociation) { case ParameterBinderAssociation.DeclaredFormalParameters: DefaultParameterBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter); break; case ParameterBinderAssociation.CommonParameters: CommonParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter); break; case ParameterBinderAssociation.ShouldProcessParameters: Diagnostics.Assert( _commandMetadata.SupportsShouldProcess, "The metadata for the ShouldProcessParameters should only be available if the command supports ShouldProcess"); ShouldProcessParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter); break; case ParameterBinderAssociation.PagingParameters: Diagnostics.Assert( _commandMetadata.SupportsPaging, "The metadata for the PagingParameters should only be available if the command supports paging"); PagingParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter); break; case ParameterBinderAssociation.TransactionParameters: Diagnostics.Assert( _commandMetadata.SupportsTransactions, "The metadata for the TransactionParameters should only be available if the command supports Transactions"); TransactionParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter); break; case ParameterBinderAssociation.DynamicParameters: Diagnostics.Assert( _commandMetadata.ImplementsDynamicParameters, "The metadata for the dynamic parameters should only be available if the command supports IDynamicParameters"); if (_dynamicParameterBinder != null) { _dynamicParameterBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter); } break; } return true; }
} // EvaluateUnboundPositionalParameters private static void AddNewPosition( SortedDictionary<int, Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter>> result, int positionInParameterSet, MergedCompiledCommandParameter parameter, ParameterSetSpecificMetadata parameterSetData) { Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter> positionalCommandParameters; if (result.TryGetValue(positionInParameterSet, out positionalCommandParameters)) { // Check to see if any of the other parameters in this position are in the same parameter set. if (ContainsPositionalParameterInSet(positionalCommandParameters, parameter, parameterSetData.ParameterSetFlag)) { // Multiple parameters were found with the same // position. This means the parameter set is ambiguous. // positional parameter could not be resolved // We throw InvalidOperationException, which the // caller will catch and throw a more // appropriate exception. throw PSTraceSource.NewInvalidOperationException(); } PositionalCommandParameter positionalCommandParameter; if (!positionalCommandParameters.TryGetValue(parameter, out positionalCommandParameter)) { positionalCommandParameter = new PositionalCommandParameter(parameter); positionalCommandParameters.Add(parameter, positionalCommandParameter); } positionalCommandParameter.ParameterSetData.Add(parameterSetData); } else { Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter> newPositionDictionary = new Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter>(); PositionalCommandParameter newPositionalParameter = new PositionalCommandParameter(parameter); newPositionalParameter.ParameterSetData.Add(parameterSetData); newPositionDictionary.Add(parameter, newPositionalParameter); result.Add(positionInParameterSet, newPositionDictionary); } }
/// <summary> /// Binds the specified argument to the specified parameter using the appropriate /// parameter binder. If the argument is of type ScriptBlock and the parameter takes /// pipeline input, then the ScriptBlock is saved off in the delay-bind ScriptBlock /// container for further processing of pipeline input and is not bound as the argument /// to the parameter. /// </summary> /// /// <param name="parameterSets"> /// The parameter set used to bind the arguments. /// </param> /// /// <param name="argument"> /// The argument to be bound. /// </param> /// /// <param name="parameter"> /// The metadata for the parameter to bind the argument to. /// </param> /// /// <param name="flags"> /// Flags for type coercion, validation, and script block binding. /// /// ParameterBindingFlags.DelayBindScriptBlock: /// If set, arguments that are of type ScriptBlock where the parameter is not of type ScriptBlock, /// Object, or PSObject will be stored for execution during pipeline input and not bound as /// an argument to the parameter. /// </param> /// /// <returns> /// True if the parameter was successfully bound. False if <paramref name="flags"/> /// has the flag <see cref="ParameterBindingFlags.ShouldCoerceType"/> set and the type does not match the parameter type. /// </returns> /// internal override bool BindParameter( uint parameterSets, CommandParameterInternal argument, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags) { // Now we need to check to see if the argument value is // a ScriptBlock. If it is and the parameter type is // not ScriptBlock and not Object, then we need to delay // binding until a pipeline object is provided to invoke // the ScriptBlock. // Note: we haven't yet determined that only a single parameter // set is valid, so we have to take a best guess on pipeline input // based on the current valid parameter sets. bool continueWithBinding = true; if ((flags & ParameterBindingFlags.DelayBindScriptBlock) != 0 && parameter.Parameter.DoesParameterSetTakePipelineInput(parameterSets) && argument.ArgumentSpecified) { object argumentValue = argument.ArgumentValue; if ((argumentValue is ScriptBlock || argumentValue is DelayedScriptBlockArgument) && !IsParameterScriptBlockBindable(parameter)) { // Now check to see if the command expects to have pipeline input. // If not, we should throw an exception now to inform the // user with more information than they would get if it was // considered an unbound mandatory parameter. if (_commandRuntime.IsClosed && _commandRuntime.InputPipe.Empty) { ParameterBindingException bindingException = new ParameterBindingException( ErrorCategory.MetadataError, this.Command.MyInvocation, GetErrorExtent(argument), parameter.Parameter.Name, parameter.Parameter.Type, null, ParameterBinderStrings.ScriptBlockArgumentNoInput, "ScriptBlockArgumentNoInput"); throw bindingException; } ParameterBinderBase.bindingTracer.WriteLine( "Adding ScriptBlock to delay-bind list for parameter '{0}'", parameter.Parameter.Name); // We need to delay binding of this argument to the parameter DelayedScriptBlockArgument delayedArg = argumentValue as DelayedScriptBlockArgument ?? new DelayedScriptBlockArgument { _argument = argument, _parameterBinder = this }; if (!_delayBindScriptBlocks.ContainsKey(parameter)) { _delayBindScriptBlocks.Add(parameter, delayedArg); } // We treat the parameter as bound, but really the // script block gets run for each pipeline object and // the result is bound. if (parameter.Parameter.ParameterSetFlags != 0) { _currentParameterSetFlag &= parameter.Parameter.ParameterSetFlags; } UnboundParameters.Remove(parameter); BoundParameters[parameter.Parameter.Name] = parameter; BoundArguments[parameter.Parameter.Name] = argument; if (DefaultParameterBinder.RecordBoundParameters && !DefaultParameterBinder.CommandLineParameters.ContainsKey(parameter.Parameter.Name)) { DefaultParameterBinder.CommandLineParameters.Add(parameter.Parameter.Name, delayedArg); } continueWithBinding = false; } } bool result = false; if (continueWithBinding) { try { result = BindParameter(argument, parameter, flags); } catch (Exception e) { bool rethrow = true; if ((flags & ParameterBindingFlags.ShouldCoerceType) == 0) { // Attributes are used to do type coercion and result in various exceptions. // We assume that if we aren't trying to do type coercion, we should avoid // propagating type conversion exceptions. while (e != null) { if (e is PSInvalidCastException) { rethrow = false; break; } e = e.InnerException; } } if (rethrow) { throw; } } } return result; }
private static bool ContainsPositionalParameterInSet( Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter> positionalCommandParameters, MergedCompiledCommandParameter parameter, uint parameterSet) { bool result = false; foreach (KeyValuePair<MergedCompiledCommandParameter, PositionalCommandParameter> pair in positionalCommandParameters) { // It's OK to have the same parameter if (pair.Key == parameter) { continue; } foreach (ParameterSetSpecificMetadata parameterSetData in pair.Value.ParameterSetData) { if ((parameterSetData.ParameterSetFlag & parameterSet) != 0 || parameterSetData.ParameterSetFlag == parameterSet) { result = true; break; } } if (result) { break; } } return result; }
private uint NewParameterSetPromptingData( Dictionary<uint, ParameterSetPromptingData> promptingData, MergedCompiledCommandParameter parameter, ParameterSetSpecificMetadata parameterSetMetadata, uint defaultParameterSet, bool pipelineInputExpected) { uint parameterMandatorySets = 0; uint parameterSetFlag = parameterSetMetadata.ParameterSetFlag; if (parameterSetFlag == 0) { parameterSetFlag = uint.MaxValue; } bool isDefaultSet = (defaultParameterSet != 0) && ((defaultParameterSet & parameterSetFlag) != 0); bool isMandatory = false; if (parameterSetMetadata.IsMandatory) { parameterMandatorySets |= parameterSetFlag; isMandatory = true; } bool isPipelineable = false; if (pipelineInputExpected) { if (parameterSetMetadata.ValueFromPipeline || parameterSetMetadata.ValueFromPipelineByPropertyName) { isPipelineable = true; } } if (isMandatory) { ParameterSetPromptingData promptingDataForSet; if (!promptingData.TryGetValue(parameterSetFlag, out promptingDataForSet)) { promptingDataForSet = new ParameterSetPromptingData(parameterSetFlag, isDefaultSet); promptingData.Add(parameterSetFlag, promptingDataForSet); } if (isPipelineable) { promptingDataForSet.PipelineableMandatoryParameters[parameter] = parameterSetMetadata; if (parameterSetMetadata.ValueFromPipeline) { promptingDataForSet.PipelineableMandatoryByValueParameters[parameter] = parameterSetMetadata; } if (parameterSetMetadata.ValueFromPipelineByPropertyName) { promptingDataForSet.PipelineableMandatoryByPropertyNameParameters[parameter] = parameterSetMetadata; } } else { promptingDataForSet.NonpipelineableMandatoryParameters[parameter] = parameterSetMetadata; } } return parameterMandatorySets; }
/// <summary> /// Bind the default value for an unbound parameter to script (used by both the script binder /// and the cmdlet binder). /// </summary> internal void BindUnboundScriptParameterWithDefaultValue(MergedCompiledCommandParameter parameter) { ScriptParameterBinder spb = (ScriptParameterBinder)this.DefaultParameterBinder; ScriptBlock script = spb.Script; RuntimeDefinedParameter runtimeDefinedParameter; if (script.RuntimeDefinedParameters.TryGetValue(parameter.Parameter.Name, out runtimeDefinedParameter)) { bool oldRecordParameters = spb.RecordBoundParameters; try { spb.RecordBoundParameters = false; // We may pass a magic parameter from the remote end with the values for the using expressions. // In this case, we want to use those values to evaluate the default value. e.g. param($a = $using:date) System.Collections.IDictionary implicitUsingParameters = null; if (DefaultParameterBinder.CommandLineParameters != null) { implicitUsingParameters = DefaultParameterBinder.CommandLineParameters.GetImplicitUsingParameters(); } object result = spb.GetDefaultScriptParameterValue(runtimeDefinedParameter, implicitUsingParameters); SaveDefaultScriptParameterValue(parameter.Parameter.Name, result); CommandParameterInternal argument = CommandParameterInternal.CreateParameterWithArgument( PositionUtilities.EmptyExtent, parameter.Parameter.Name, "-" + parameter.Parameter.Name + ":", PositionUtilities.EmptyExtent, result, false); ParameterBindingFlags flags = ParameterBindingFlags.IsDefaultValue; // Only coerce explicit values. We default to null, which isn't always convertible. if (runtimeDefinedParameter.IsSet) { flags |= ParameterBindingFlags.ShouldCoerceType; } BindParameter(uint.MaxValue, argument, parameter, flags); } finally { spb.RecordBoundParameters = oldRecordParameters; } } }
private bool BindValueFromPipelineByPropertyName( PSObject inputToOperateOn, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags) { bool bindResult = false; ParameterBinderBase.bindingTracer.WriteLine( ((flags & ParameterBindingFlags.ShouldCoerceType) != 0) ? "Parameter [{0}] PIPELINE INPUT ValueFromPipelineByPropertyName WITH COERCION" : "Parameter [{0}] PIPELINE INPUT ValueFromPipelineByPropertyName NO COERCION", parameter.Parameter.Name); PSMemberInfo member = inputToOperateOn.Properties[parameter.Parameter.Name]; if (member == null) { // Since a member matching the name of the parameter wasn't found, // check the aliases. foreach (string alias in parameter.Parameter.Aliases) { member = inputToOperateOn.Properties[alias]; if (member != null) { break; } } } if (member != null) { ParameterBindingException parameterBindingException = null; try { bindResult = BindPipelineParameter( member.Value, parameter, flags); } catch (ParameterBindingArgumentTransformationException e) { parameterBindingException = e; } catch (ParameterBindingValidationException e) { parameterBindingException = e; } catch (ParameterBindingParameterDefaultValueException e) { parameterBindingException = e; } catch (ParameterBindingException) { // Just ignore and continue; bindResult = false; } if (parameterBindingException != null) { if (!DefaultParameterBindingInUse) { throw parameterBindingException; } else { ThrowElaboratedBindingException(parameterBindingException); } } } return bindResult; }
/// <summary> /// Bind the argument to the specified parameter /// </summary> /// /// <param name="parameterSets"> /// The parameter set used to bind the arguments. /// </param> /// /// <param name="argument"> /// The argument to be bound. /// </param> /// /// <param name="parameter"> /// The metadata for the parameter to bind the argument to. /// </param> /// /// <param name="flags"> /// Flags for type coercion and validation of the arguments. /// </param> /// /// <returns> /// True if the parameter was successfully bound. False if <paramref name="flags"/> /// specifies no type coercion and the type does not match the parameter type. /// </returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="parameter"/> or <paramref name="argument"/> is null. /// </exception> /// /// <exception cref="ParameterBindingException"> /// If argument transformation fails. /// or /// The argument could not be coerced to the appropriate type for the parameter. /// or /// The parameter argument transformation, prerequisite, or validation failed. /// or /// If the binding to the parameter fails. /// </exception> /// internal virtual bool BindParameter( uint parameterSets, CommandParameterInternal argument, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags) { bool result = false; switch (parameter.BinderAssociation) { case ParameterBinderAssociation.DeclaredFormalParameters: result = this.DefaultParameterBinder.BindParameter( argument, parameter.Parameter, flags); break; default: Diagnostics.Assert( false, "Only the formal parameters are available for this type of command"); break; } if (result && ((flags & ParameterBindingFlags.IsDefaultValue) == 0)) { UnboundParameters.Remove(parameter); BoundParameters.Add(parameter.Parameter.Name, parameter); } return result; }
/// <summary> /// Backs up the specified parameter value by calling the GetDefaultParameterValue /// abstract method. /// /// This method is called when binding a parameter value that came from a pipeline /// object. /// </summary> /// /// <exception cref="ParameterBindingParameterDefaultValueException"> /// If the parameter binder encounters an error getting the default value. /// </exception> /// private void BackupDefaultParameter(MergedCompiledCommandParameter parameter) { if (!_defaultParameterValues.ContainsKey(parameter.Parameter.Name)) { object defaultParameterValue = GetDefaultParameterValue(parameter.Parameter.Name); _defaultParameterValues.Add( parameter.Parameter.Name, CommandParameterInternal.CreateParameterWithArgument( PositionUtilities.EmptyExtent, parameter.Parameter.Name, "-" + parameter.Parameter.Name + ":", PositionUtilities.EmptyExtent, defaultParameterValue, false)); } }
private static bool IsParameterScriptBlockBindable(MergedCompiledCommandParameter parameter) { bool flag = false; Type type = parameter.Parameter.Type; if (type == typeof(object)) { flag = true; } else if (type == typeof(ScriptBlock)) { flag = true; } else if (type.IsSubclassOf(typeof(ScriptBlock))) { flag = true; } else { ParameterCollectionTypeInformation collectionTypeInformation = parameter.Parameter.CollectionTypeInformation; if (collectionTypeInformation.ParameterCollectionType != ParameterCollectionType.NotCollection) { if (collectionTypeInformation.ElementType == typeof(object)) { flag = true; } else if (collectionTypeInformation.ElementType == typeof(ScriptBlock)) { flag = true; } else if (collectionTypeInformation.ElementType.IsSubclassOf(typeof(ScriptBlock))) { flag = true; } } } _tracer.WriteLine("IsParameterScriptBlockBindable: result = {0}", new object[] { flag }); return flag; }
/// <summary> /// Constructs a container for the merged parameter metadata and /// parameter set specific metadata for a positional parameter /// </summary> /// internal PositionalCommandParameter(MergedCompiledCommandParameter parameter) { Parameter = parameter; }
/// <summary> /// Gets the parameters by matching its name. /// </summary> /// <param name="name"> /// The name of the parameter. /// </param> /// <param name="throwOnParameterNotFound"> /// If true and a matching parameter is not found, an exception will be /// throw. If false and a matching parameter is not found, null is returned. /// </param> /// <param name="tryExactMatching"> /// If true we do exact matching, otherwise we do not. /// </param> /// <param name="invocationInfo"> /// The invocation information about the code being run. /// </param> /// <returns> /// The a collection of the metadata associated with the parameters that /// match the specified name. If no matches were found, an empty collection /// is returned. /// </returns> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> internal MergedCompiledCommandParameter GetMatchingParameter( string name, bool throwOnParameterNotFound, bool tryExactMatching, InvocationInfo invocationInfo) { if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException("name"); } Collection <MergedCompiledCommandParameter> matchingParameters = new Collection <MergedCompiledCommandParameter>(); // Skip the leading '-' if present if (name.Length > 0 && CharExtensions.IsDash(name[0])) { name = name.Substring(1); } // First try to match the bindable parameters foreach (string parameterName in _bindableParameters.Keys) { if (CultureInfo.InvariantCulture.CompareInfo.IsPrefix(parameterName, name, CompareOptions.IgnoreCase)) { // If it is an exact match then only return the exact match // as the result if (tryExactMatching && string.Equals(parameterName, name, StringComparison.OrdinalIgnoreCase)) { return(_bindableParameters[parameterName]); } else { matchingParameters.Add(_bindableParameters[parameterName]); } } } // Now check the aliases foreach (string parameterName in _aliasedParameters.Keys) { if (CultureInfo.InvariantCulture.CompareInfo.IsPrefix(parameterName, name, CompareOptions.IgnoreCase)) { // If it is an exact match then only return the exact match // as the result if (tryExactMatching && string.Equals(parameterName, name, StringComparison.OrdinalIgnoreCase)) { return(_aliasedParameters[parameterName]); } else { if (!matchingParameters.Contains(_aliasedParameters[parameterName])) { matchingParameters.Add(_aliasedParameters[parameterName]); } } } } if (matchingParameters.Count > 1) { // Prefer parameters in the cmdlet over common parameters Collection <MergedCompiledCommandParameter> filteredParameters = new Collection <MergedCompiledCommandParameter>(); foreach (MergedCompiledCommandParameter matchingParameter in matchingParameters) { if ((matchingParameter.BinderAssociation == ParameterBinderAssociation.DeclaredFormalParameters) || (matchingParameter.BinderAssociation == ParameterBinderAssociation.DynamicParameters)) { filteredParameters.Add(matchingParameter); } } if (tryExactMatching && filteredParameters.Count == 1) { matchingParameters = filteredParameters; } else { StringBuilder possibleMatches = new StringBuilder(); foreach (MergedCompiledCommandParameter matchingParameter in matchingParameters) { possibleMatches.Append(" -"); possibleMatches.Append(matchingParameter.Parameter.Name); } ParameterBindingException exception = new ParameterBindingException( ErrorCategory.InvalidArgument, invocationInfo, null, name, null, null, ParameterBinderStrings.AmbiguousParameter, "AmbiguousParameter", possibleMatches); throw exception; } } else if (matchingParameters.Count == 0) { if (throwOnParameterNotFound) { ParameterBindingException exception = new ParameterBindingException( ErrorCategory.InvalidArgument, invocationInfo, null, name, null, null, ParameterBinderStrings.NamedParameterNotFound, "NamedParameterNotFound"); throw exception; } } MergedCompiledCommandParameter result = null; if (matchingParameters.Count > 0) { result = matchingParameters[0]; } return(result); }
private int NewParameterSetPromptingData(Dictionary<int, ParameterSetPromptingData> promptingData, MergedCompiledCommandParameter parameter, ParameterSetSpecificMetadata parameterSetMetadata, int defaultParameterSet, bool pipelineInputExpected) { int num = 0; int parameterSetFlag = parameterSetMetadata.ParameterSetFlag; if (parameterSetFlag == 0) { parameterSetFlag = int.MaxValue; } bool isDefaultSet = (defaultParameterSet != 0) && ((defaultParameterSet & parameterSetFlag) != 0); bool flag2 = false; if (parameterSetMetadata.IsMandatory) { num |= parameterSetFlag; flag2 = true; } bool flag3 = false; if (pipelineInputExpected && (parameterSetMetadata.ValueFromPipeline || parameterSetMetadata.ValueFromPipelineByPropertyName)) { flag3 = true; } if (flag2) { ParameterSetPromptingData data; if (!promptingData.TryGetValue(parameterSetFlag, out data)) { data = new ParameterSetPromptingData(parameterSetFlag, isDefaultSet); promptingData.Add(parameterSetFlag, data); } if (flag3) { data.PipelineableMandatoryParameters[parameter] = parameterSetMetadata; if (parameterSetMetadata.ValueFromPipeline) { data.PipelineableMandatoryByValueParameters[parameter] = parameterSetMetadata; } if (parameterSetMetadata.ValueFromPipelineByPropertyName) { data.PipelineableMandatoryByPropertyNameParameters[parameter] = parameterSetMetadata; } return num; } data.NonpipelineableMandatoryParameters[parameter] = parameterSetMetadata; } return num; }
internal virtual bool BindParameter(int parameterSets, CommandParameterInternal argument, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags) { bool flag = false; if (parameter.BinderAssociation == ParameterBinderAssociation.DeclaredFormalParameters) { flag = this.DefaultParameterBinder.BindParameter(argument, parameter.Parameter, flags); } if (flag && ((flags & ParameterBindingFlags.IsDefaultValue) == ParameterBindingFlags.None)) { this.UnboundParameters.Remove(parameter); this.BoundParameters.Add(parameter.Parameter.Name, parameter); } return(flag); }
/// <summary> /// Merges the specified metadata with the other metadata already defined /// in this object. /// </summary> /// <param name="parameterMetadata"> /// The compiled metadata for the type to be merged. /// </param> /// <param name="binderAssociation"> /// The type of binder that the CommandProcessor will use to bind /// the parameters for <paramref name="parameterMetadata"/> /// </param> /// <returns> /// A collection of the merged parameter metadata that was added. /// </returns> /// <exception cref="MetadataException"> /// If a parameter name or alias described in the <paramref name="parameterMetadata"/> already /// exists. /// </exception> internal Collection <MergedCompiledCommandParameter> AddMetadataForBinder( InternalParameterMetadata parameterMetadata, ParameterBinderAssociation binderAssociation) { if (parameterMetadata == null) { throw PSTraceSource.NewArgumentNullException("parameterMetadata"); } Collection <MergedCompiledCommandParameter> result = new Collection <MergedCompiledCommandParameter>(); // Merge in the bindable parameters foreach (KeyValuePair <string, CompiledCommandParameter> bindableParameter in parameterMetadata.BindableParameters) { if (_bindableParameters.ContainsKey(bindableParameter.Key)) { MetadataException exception = new MetadataException( "ParameterNameAlreadyExistsForCommand", null, Metadata.ParameterNameAlreadyExistsForCommand, bindableParameter.Key); throw exception; } // NTRAID#Windows Out Of Band Releases-926371-2005/12/27-JonN if (_aliasedParameters.ContainsKey(bindableParameter.Key)) { MetadataException exception = new MetadataException( "ParameterNameConflictsWithAlias", null, Metadata.ParameterNameConflictsWithAlias, bindableParameter.Key, RetrieveParameterNameForAlias(bindableParameter.Key, _aliasedParameters)); throw exception; } MergedCompiledCommandParameter mergedParameter = new MergedCompiledCommandParameter(bindableParameter.Value, binderAssociation); _bindableParameters.Add(bindableParameter.Key, mergedParameter); result.Add(mergedParameter); // Merge in the aliases foreach (string aliasName in bindableParameter.Value.Aliases) { if (_aliasedParameters.ContainsKey(aliasName)) { MetadataException exception = new MetadataException( "AliasParameterNameAlreadyExistsForCommand", null, Metadata.AliasParameterNameAlreadyExistsForCommand, aliasName); throw exception; } // NTRAID#Windows Out Of Band Releases-926371-2005/12/27-JonN if (_bindableParameters.ContainsKey(aliasName)) { MetadataException exception = new MetadataException( "ParameterNameConflictsWithAlias", null, Metadata.ParameterNameConflictsWithAlias, RetrieveParameterNameForAlias(aliasName, _bindableParameters), bindableParameter.Value.Name); throw exception; } _aliasedParameters.Add(aliasName, mergedParameter); } } return(result); }
private bool RestoreParameter(CommandParameterInternal argumentToBind, MergedCompiledCommandParameter parameter) { switch (parameter.BinderAssociation) { case ParameterBinderAssociation.DeclaredFormalParameters: base.DefaultParameterBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue); break; case ParameterBinderAssociation.DynamicParameters: if (this._dynamicParameterBinder != null) { this._dynamicParameterBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue); } break; case ParameterBinderAssociation.CommonParameters: this.CommonParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue); break; case ParameterBinderAssociation.ShouldProcessParameters: this.ShouldProcessParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue); break; case ParameterBinderAssociation.TransactionParameters: this.TransactionParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue); break; case ParameterBinderAssociation.PagingParameters: this.PagingParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue); break; } return true; }