public void SetValue(object value, ExecutionContext context) { try { this.CheckTypeConstraintViolation(); if (context.PSDebug > 1 && !this.IsInternalCode) { string str = PSObject.ToStringParser(context, value); int length = 60 - this._varName.Length; if (str.Length > length) { str = str.Substring(0, length) + "..."; } ScriptTrace.Trace(context, 1, "TraceVariableAssignment", (object)this._varName, (object)str); } this.PrivateSetValue(value, context); } catch (RuntimeException ex) { if (ex.ErrorRecord != null && ex.ErrorRecord.InvocationInfo == null) { ex.ErrorRecord.SetInvocationInfo(new InvocationInfo((CommandInfo)null, this.NodeToken, context)); } throw; } }
private object BuildHashtable( ParseTreeNode.ParseTreeNodeExecutor parseTreeNodeExecutor) { Hashtable hashtable = new Hashtable((IEqualityComparer)StringComparer.CurrentCultureIgnoreCase); for (int index = 0; index < this._keys.Count; ++index) { object obj1 = this._keys[index]; if (obj1 is ParseTreeNode) { obj1 = parseTreeNodeExecutor((ParseTreeNode)obj1); } object obj2 = PSObject.Base(obj1); if (obj2 == null || obj2 == AutomationNull.Value) { throw InterpreterError.NewInterpreterException(obj2, typeof(RuntimeException), this._tokens[index], "NullArrayIndex"); } if (hashtable.ContainsKey(obj2)) { string str = PSObject.ToStringParser((ExecutionContext)null, obj2); if (str.Length > 40) { str = str.Substring(0, 40) + "..."; } throw InterpreterError.NewInterpreterException(obj2, typeof(RuntimeException), this._tokens[index], "DuplicateKeyInHashLiteral", (object)str); } hashtable[obj2] = parseTreeNodeExecutor(this._expressions[index]); } return((object)hashtable); }
internal static bool ConditionSatisfiedRegex(bool caseSensitive, object condition, IScriptExtent errorPosition, string str, ExecutionContext context) { string str2; bool success; RegexOptions options = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase; try { Match match; Regex regex = condition as Regex; if ((regex != null) && (((regex.Options & RegexOptions.IgnoreCase) != RegexOptions.None) != caseSensitive)) { match = regex.Match(str); } else { str2 = PSObject.ToStringParser(context, condition); match = Regex.Match(str, str2, options); if (match.Success && (match.Groups.Count > 0)) { regex = new Regex(str2, options); } } if (match.Success) { GroupCollection groups = match.Groups; if (groups.Count > 0) { Hashtable newValue = new Hashtable(StringComparer.CurrentCultureIgnoreCase); foreach (string str3 in regex.GetGroupNames()) { Group group = groups[str3]; if (group.Success) { int num; if (int.TryParse(str3, out num)) { newValue.Add(num, group.ToString()); } else { newValue.Add(str3, group.ToString()); } } } context.SetVariable(SpecialVariables.MatchesVarPath, newValue); } } success = match.Success; } catch (ArgumentException exception) { str2 = PSObject.ToStringParser(context, condition); throw InterpreterError.NewInterpreterExceptionWithInnerException(str2, typeof(RuntimeException), errorPosition, "InvalidRegularExpression", ParserStrings.InvalidRegularExpression, exception, new object[] { str2 }); } return(success); }
private PSMemberInfo GetMemberInfo( PSObject target, object member, ExecutionContext context) { if (!(member is string str)) { str = PSObject.ToStringParser(context, member); } return(this.IsStatic ? PSObject.GetStaticCLRMember((object)target, str) : target.Members[str]); }
internal static object JoinOperator(System.Management.Automation.ExecutionContext context, IScriptExtent errorPosition, object lval, object rval) { string separator = PSObject.ToStringParser(context, rval); IEnumerable enumerable = LanguagePrimitives.GetEnumerable(lval); if (enumerable != null) { return(PSObject.ToStringEnumerable(context, enumerable, separator, null, null)); } return(PSObject.ToStringParser(context, lval)); }
private string GetLabel(object result, ExecutionContext context) { string stringParser = PSObject.ToStringParser(context, result); for (int index = 0; index < stringParser.Length; ++index) { if (!char.IsLetterOrDigit(stringParser[index]) && stringParser[index] != '_') { throw InterpreterError.NewInterpreterException((object)stringParser, typeof(RuntimeException), this.NodeToken, "InvalidLabelCharacter", (object)stringParser[index]); } } return(stringParser); }
private static object SplitOperatorImpl(System.Management.Automation.ExecutionContext context, IScriptExtent errorPosition, object lval, object rval, SplitImplOptions implOptions, bool ignoreCase) { IEnumerable <string> content = enumerateContent(context, errorPosition, implOptions, lval); ScriptBlock predicate = null; string separatorPattern = null; int limit = 0; SplitOptions options = 0; object[] objArray = unfoldTuple(context, errorPosition, rval); if (objArray.Length < 1) { throw InterpreterError.NewInterpreterException(rval, typeof(RuntimeException), errorPosition, "BadOperatorArgument", ParserStrings.BadOperatorArgument, new object[] { "-split", rval }); } object obj1 = objArray[0]; predicate = objArray[0] as ScriptBlock; if (predicate == null) { separatorPattern = PSObject.ToStringParser(context, objArray[0]); } if (objArray.Length >= 2) { limit = FixNum(objArray[1], errorPosition); } if ((objArray.Length >= 3) && (objArray[2] != null)) { string str2 = objArray[2] as string; if ((str2 == null) || !string.IsNullOrEmpty(str2)) { options = ConvertTo <SplitOptions>(objArray[2], errorPosition); if (predicate != null) { throw InterpreterError.NewInterpreterException(null, typeof(ParseException), errorPosition, "InvalidSplitOptionWithPredicate", ParserStrings.InvalidSplitOptionWithPredicate, new object[0]); } if (ignoreCase && ((options & SplitOptions.IgnoreCase) == 0)) { options |= SplitOptions.IgnoreCase; } } } else if (ignoreCase) { options |= SplitOptions.IgnoreCase; } if (predicate != null) { return(SplitWithPredicate(context, errorPosition, content, predicate, limit)); } return(SplitWithPattern(context, errorPosition, content, separatorPattern, limit, options)); }
private string GetFilePath(ExecutionContext context) { try { object obj = this._expression.Execute((Array)null, (Pipe)null, context); string filePath = !(obj is FileInfo fileInfo) ? PSObject.ToStringParser(context, obj) : fileInfo.FullName; return(!string.IsNullOrEmpty(filePath) ? this.ResolveFilePath(filePath, context) : throw InterpreterError.NewInterpreterException((object)filePath, typeof(RuntimeException), this._expression.NodeToken, "InvalidFilenameOption")); } catch (RuntimeException ex) { if (ex.ErrorRecord != null && ex.ErrorRecord.InvocationInfo == null) { ex.ErrorRecord.SetInvocationInfo(new InvocationInfo((CommandInfo)null, this.NodeToken, context)); } throw; } }
internal static void AddKeyValuePair(IDictionary hashtable, object key, object value, IScriptExtent errorExtent) { key = PSObject.Base(key); if (key == null) { throw InterpreterError.NewInterpreterException(hashtable, typeof(RuntimeException), errorExtent, "InvalidNullKey", ParserStrings.InvalidNullKey, new object[0]); } if (hashtable.Contains(key)) { string str = PSObject.ToStringParser(null, key); if (str.Length > 40) { str = str.Substring(0, 40) + "..."; } throw InterpreterError.NewInterpreterException(hashtable, typeof(RuntimeException), errorExtent, "DuplicateKeyInHashLiteral", ParserStrings.DuplicateKeyInHashLiteral, new object[] { str }); } hashtable.Add(key, value); }
private void WriteTextInput() { try { foreach (object input in this.inputList) { if (this.stopping) { break; } this.streamWriter.Write(PSObject.ToStringParser(this.command.Context, input)); } } finally { this.streamWriter.Close(); } }
private void WriteTextInput() { try { foreach (object obj2 in this.inputList) { if (this.stopping) { return; } string str = PSObject.ToStringParser(this.command.Context, obj2); this.streamWriter.Write(str); } } finally { this.streamWriter.Close(); } }
internal static void appendOneNativeArgument(ExecutionContext context, StringBuilder argumentBuilder, bool needInitialSpace, object obj) { IEnumerator enumerator = LanguagePrimitives.GetEnumerator(obj); bool flag = needInitialSpace; do { string str; if (enumerator == null) { str = PSObject.ToStringParser(context, obj); } else { if (!ParserOps.MoveNext(context, null, enumerator)) { break; } str = PSObject.ToStringParser(context, ParserOps.Current(null, enumerator)); } if (!string.IsNullOrEmpty(str)) { if (flag) { argumentBuilder.Append(' '); } else { flag = true; } if (((str.IndexOfAny(whiteSpace) >= 0) && (str.Length > 1)) && (str[0] != '"')) { argumentBuilder.Append('"'); argumentBuilder.Append(str); argumentBuilder.Append('"'); } else { argumentBuilder.Append(str); } } }while (enumerator != null); }
internal static bool ConditionSatisfiedWildcard(bool caseSensitive, object condition, string str, ExecutionContext context) { WildcardPattern pattern = condition as WildcardPattern; if (pattern != null) { if (((pattern.Options & WildcardOptions.IgnoreCase) == WildcardOptions.None) != caseSensitive) { WildcardOptions options = caseSensitive ? WildcardOptions.None : WildcardOptions.IgnoreCase; pattern = new WildcardPattern(pattern.Pattern, options); } } else { WildcardOptions options2 = caseSensitive ? WildcardOptions.None : WildcardOptions.IgnoreCase; pattern = new WildcardPattern(PSObject.ToStringParser(context, condition), options2); } return(pattern.IsMatch(str)); }
internal void TraceVariableSet(string varName, object value) { if (this._callStack.Any <CallStackInfo>() && (this._context.PSDebugTraceLevel <= 2)) { ScriptBlock scriptBlock = this._callStack.Last <CallStackInfo>().ScriptBlock; if (scriptBlock.DebuggerHidden || scriptBlock.DebuggerStepThrough) { return; } } string str = PSObject.ToStringParser(this._context, value); int length = 60 - varName.Length; if (str.Length > length) { str = str.Substring(0, length) + "..."; } this.Trace("TraceVariableAssignment", ParserStrings.TraceVariableAssignment, new object[] { varName, str }); }
internal Pipe GetRedirectionPipe(ExecutionContext context) { if (this._location == null) { return((Pipe)null); } string stringParser = PSObject.ToStringParser(context, this._location.Execute(context)); if (string.IsNullOrEmpty(stringParser)) { return new Pipe() { NullPipe = true } } ; PipelineProcessor outputPipeline = this.BuildRedirectionPipeline(stringParser, context); return(new Pipe(context, outputPipeline)); }
internal static string ResolveFilePath(IScriptExtent errorExtent, object obj, ExecutionContext context) { string str2; try { ProviderInfo info2; FileInfo info = obj as FileInfo; string str = (info != null) ? info.FullName : PSObject.ToStringParser(context, obj); if (string.IsNullOrEmpty(str)) { throw InterpreterError.NewInterpreterException(str, typeof(RuntimeException), errorExtent, "InvalidFilenameOption", ParserStrings.InvalidFilenameOption, new object[0]); } SessionState state = new SessionState(context.EngineSessionState); Collection <string> resolvedProviderPathFromPSPath = state.Path.GetResolvedProviderPathFromPSPath(str, out info2); if (!info2.NameEquals(context.ProviderNames.FileSystem)) { throw InterpreterError.NewInterpreterException(str, typeof(RuntimeException), errorExtent, "FileOpenError", ParserStrings.FileOpenError, new object[] { info2.FullName }); } if ((resolvedProviderPathFromPSPath == null) || (resolvedProviderPathFromPSPath.Count < 1)) { throw InterpreterError.NewInterpreterException(str, typeof(RuntimeException), errorExtent, "FileNotFound", ParserStrings.FileNotFound, new object[] { str }); } if (resolvedProviderPathFromPSPath.Count > 1) { throw InterpreterError.NewInterpreterException(resolvedProviderPathFromPSPath, typeof(RuntimeException), errorExtent, "AmbiguousPath", ParserStrings.AmbiguousPath, new object[0]); } str2 = resolvedProviderPathFromPSPath[0]; } catch (RuntimeException exception) { if ((exception.ErrorRecord != null) && (exception.ErrorRecord.InvocationInfo == null)) { exception.ErrorRecord.SetInvocationInfo(new InvocationInfo(null, errorExtent, context)); } throw; } return(str2); }
private static IEnumerable <string> enumerateContent(System.Management.Automation.ExecutionContext context, IScriptExtent errorPosition, SplitImplOptions implOptions, object tuple) { IEnumerator enumerator = LanguagePrimitives.GetEnumerator(tuple); if (enumerator == null) { enumerator = new object[] { tuple }.GetEnumerator(); } while (true) { if (!MoveNext(context, errorPosition, enumerator)) { yield break; } string iteratorVariable1 = PSObject.ToStringParser(context, enumerator.Current); if ((implOptions & SplitImplOptions.TrimContent) != SplitImplOptions.None) { iteratorVariable1 = iteratorVariable1.Trim(); } yield return(iteratorVariable1); } }
internal static object LikeOperator(System.Management.Automation.ExecutionContext context, IScriptExtent errorPosition, object lval, object rval, bool notLike, bool ignoreCase) { WildcardPattern pattern = new WildcardPattern(PSObject.ToStringParser(context, rval), ignoreCase ? WildcardOptions.IgnoreCase : WildcardOptions.None); IEnumerator enumerator = LanguagePrimitives.GetEnumerator(lval); if (enumerator == null) { string input = (lval == null) ? string.Empty : PSObject.ToStringParser(context, lval); return(BoolToObject(pattern.IsMatch(input) ^ notLike)); } ArrayList list = new ArrayList(); while (MoveNext(context, errorPosition, enumerator)) { object obj2 = Current(errorPosition, enumerator); string str2 = (obj2 == null) ? string.Empty : PSObject.ToStringParser(context, obj2); if (pattern.IsMatch(str2) ^ notLike) { list.Add(str2); } } return(list.ToArray()); }
private static CommandProcessorBase AddCommand(PipelineProcessor pipe, CommandParameterInternal[] commandElements, CommandBaseAst commandBaseAst, CommandRedirection[] redirections, System.Management.Automation.ExecutionContext context) { object parameterText; IScriptExtent parameterExtent; CommandProcessorBase base2; InternalCommand command; string str3; HelpCategory category; CommandAst ast = commandBaseAst as CommandAst; TokenKind kind = (ast != null) ? ast.InvocationOperator : TokenKind.Unknown; bool dotSource = kind == TokenKind.Dot; SessionStateInternal sessionState = null; int index = 0; PSModuleInfo info = PSObject.Base(commandElements[0].ArgumentValue) as PSModuleInfo; if (info != null) { if ((info.ModuleType == ModuleType.Binary) && (info.SessionState == null)) { throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "CantInvokeInBinaryModule", ParserStrings.CantInvokeInBinaryModule, new object[] { info.Name }); } if (info.SessionState == null) { throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "CantInvokeInNonImportedModule", ParserStrings.CantInvokeInNonImportedModule, new object[] { info.Name }); } sessionState = info.SessionState.Internal; index++; } CommandParameterInternal internal3 = commandElements[index]; if (internal3.ParameterNameSpecified) { parameterText = internal3.ParameterText; parameterExtent = internal3.ParameterExtent; if (!internal3.ArgumentSpecified) { } } else { parameterText = PSObject.Base(internal3.ArgumentValue); parameterExtent = internal3.ArgumentExtent; } string str = dotSource ? "." : ((kind == TokenKind.Ampersand) ? "&" : null); ScriptBlock scriptblock = parameterText as ScriptBlock; if (scriptblock != null) { base2 = CommandDiscovery.CreateCommandProcessorForScript(scriptblock, context, !dotSource, sessionState); } else { CommandInfo commandInfo = parameterText as CommandInfo; if (commandInfo != null) { base2 = context.CommandDiscovery.LookupCommandProcessor(commandInfo, context.EngineSessionState.CurrentScope.ScopeOrigin, new bool?(!dotSource), sessionState); } else { string str2 = (parameterText as string) ?? PSObject.ToStringParser(context, parameterText); str = str ?? str2; if (string.IsNullOrEmpty(str2)) { throw InterpreterError.NewInterpreterException(parameterText, typeof(RuntimeException), parameterExtent, "BadExpression", ParserStrings.BadExpression, new object[] { dotSource ? "." : "&" }); } try { if (sessionState != null) { SessionStateInternal engineSessionState = context.EngineSessionState; try { context.EngineSessionState = sessionState; base2 = context.CreateCommand(str2, dotSource); goto Label_025D; } finally { context.EngineSessionState = engineSessionState; } } base2 = context.CreateCommand(str2, dotSource); } catch (RuntimeException exception) { if (exception.ErrorRecord.InvocationInfo == null) { InvocationInfo invocationInfo = new InvocationInfo(null, parameterExtent, context) { InvocationName = str }; exception.ErrorRecord.SetInvocationInfo(invocationInfo); } throw; } } } Label_025D: command = base2.Command; base2.UseLocalScope = !dotSource && ((command is ScriptCommand) || (command is PSScriptCmdlet)); bool flag2 = base2 is NativeCommandProcessor; for (int i = index + 1; i < commandElements.Length; i++) { CommandParameterInternal parameter = commandElements[i]; if ((!parameter.ParameterNameSpecified || !parameter.ParameterName.Equals("-", StringComparison.OrdinalIgnoreCase)) || flag2) { if (parameter.ArgumentSplatted) { foreach (CommandParameterInternal internal6 in Splat(parameter.ArgumentValue, parameter.ArgumentExtent)) { base2.AddParameter(internal6); } } else { base2.AddParameter(parameter); } } } if (base2.IsHelpRequested(out str3, out category)) { base2 = CommandProcessorBase.CreateGetHelpCommandProcessor(context, str3, category); } base2.Command.InvocationExtent = commandBaseAst.Extent; base2.Command.MyInvocation.ScriptPosition = commandBaseAst.Extent; base2.Command.MyInvocation.InvocationName = str; pipe.Add(base2); bool flag3 = false; bool flag4 = false; bool flag5 = false; bool flag6 = false; if (redirections != null) { foreach (CommandRedirection redirection in redirections) { redirection.Bind(pipe, base2, context); switch (redirection.FromStream) { case RedirectionStream.All: flag3 = true; flag4 = true; flag5 = true; flag6 = true; break; case RedirectionStream.Error: flag3 = true; break; case RedirectionStream.Warning: flag4 = true; break; case RedirectionStream.Verbose: flag5 = true; break; case RedirectionStream.Debug: flag6 = true; break; } } } if (!flag3) { if (context.ShellFunctionErrorOutputPipe != null) { base2.CommandRuntime.ErrorOutputPipe = context.ShellFunctionErrorOutputPipe; } else { base2.CommandRuntime.ErrorOutputPipe.ExternalWriter = context.ExternalErrorOutput; } } if (!flag4 && (context.ExpressionWarningOutputPipe != null)) { base2.CommandRuntime.WarningOutputPipe = context.ExpressionWarningOutputPipe; flag4 = true; } if (!flag5 && (context.ExpressionVerboseOutputPipe != null)) { base2.CommandRuntime.VerboseOutputPipe = context.ExpressionVerboseOutputPipe; flag5 = true; } if (!flag6 && (context.ExpressionDebugOutputPipe != null)) { base2.CommandRuntime.DebugOutputPipe = context.ExpressionDebugOutputPipe; flag6 = true; } if ((context.CurrentCommandProcessor != null) && (context.CurrentCommandProcessor.CommandRuntime != null)) { if (!flag4 && (context.CurrentCommandProcessor.CommandRuntime.WarningOutputPipe != null)) { base2.CommandRuntime.WarningOutputPipe = context.CurrentCommandProcessor.CommandRuntime.WarningOutputPipe; } if (!flag5 && (context.CurrentCommandProcessor.CommandRuntime.VerboseOutputPipe != null)) { base2.CommandRuntime.VerboseOutputPipe = context.CurrentCommandProcessor.CommandRuntime.VerboseOutputPipe; } if (!flag6 && (context.CurrentCommandProcessor.CommandRuntime.DebugOutputPipe != null)) { base2.CommandRuntime.DebugOutputPipe = context.CurrentCommandProcessor.CommandRuntime.DebugOutputPipe; } } return(base2); }
internal static object MatchOperator(System.Management.Automation.ExecutionContext context, IScriptExtent errorPosition, object lval, object rval, bool notMatch, bool ignoreCase) { object obj3; RegexOptions options = ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None; Regex regex = PSObject.Base(rval) as Regex; if (regex == null) { regex = NewRegex(PSObject.ToStringParser(context, rval), options); } IEnumerator targetObject = LanguagePrimitives.GetEnumerator(lval); if (targetObject == null) { string input = (lval == null) ? string.Empty : PSObject.ToStringParser(context, lval); Match match = regex.Match(input); if (match.Success) { GroupCollection groups = match.Groups; if (groups.Count > 0) { Hashtable newValue = new Hashtable(StringComparer.CurrentCultureIgnoreCase); foreach (string str2 in regex.GetGroupNames()) { Group group = groups[str2]; if (group.Success) { int num; if (int.TryParse(str2, out num)) { newValue.Add(num, group.ToString()); } else { newValue.Add(str2, group.ToString()); } } } context.SetVariable(SpecialVariables.MatchesVarPath, newValue); } } return(BoolToObject(match.Success ^ notMatch)); } ArrayList list = new ArrayList(); int num2 = 0; try { while (targetObject.MoveNext()) { object current = targetObject.Current; string str3 = (current == null) ? string.Empty : PSObject.ToStringParser(context, current); if (regex.Match(str3).Success ^ notMatch) { list.Add(current); } if (num2++ > 0x3e8) { if ((context != null) && context.CurrentPipelineStopping) { throw new PipelineStoppedException(); } num2 = 0; } } obj3 = list.ToArray(); } catch (RuntimeException) { throw; } catch (FlowControlException) { throw; } catch (ScriptCallDepthException) { throw; } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); throw InterpreterError.NewInterpreterExceptionWithInnerException(targetObject, typeof(RuntimeException), errorPosition, "BadEnumeration", ParserStrings.BadEnumeration, exception, new object[] { exception.Message }); } return(obj3); }
internal static object ReplaceOperator(System.Management.Automation.ExecutionContext context, IScriptExtent errorPosition, object lval, object rval, bool ignoreCase) { string replacement = ""; object obj2 = ""; rval = PSObject.Base(rval); IList list = rval as IList; if (list != null) { if (list.Count > 2) { throw InterpreterError.NewInterpreterException(rval, typeof(RuntimeException), errorPosition, "BadReplaceArgument", ParserStrings.BadReplaceArgument, new object[] { ignoreCase ? "-ireplace" : "-replace", list.Count }); } if (list.Count > 0) { obj2 = list[0]; if (list.Count > 1) { replacement = PSObject.ToStringParser(context, list[1]); } } } else { obj2 = rval; } RegexOptions none = RegexOptions.None; if (ignoreCase) { none = RegexOptions.IgnoreCase; } Regex regex = obj2 as Regex; if (regex == null) { try { regex = NewRegex(PSObject.ToStringParser(context, obj2), none); } catch (ArgumentException exception) { throw InterpreterError.NewInterpreterExceptionWithInnerException(obj2, typeof(RuntimeException), null, "InvalidRegularExpression", ParserStrings.InvalidRegularExpression, exception, new object[] { obj2 }); } } IEnumerator enumerator = LanguagePrimitives.GetEnumerator(lval); if (enumerator == null) { string input = ((lval == null) ? string.Empty : lval).ToString(); return(regex.Replace(input, replacement)); } ArrayList list2 = new ArrayList(); while (MoveNext(context, errorPosition, enumerator)) { string str3 = PSObject.ToStringParser(context, Current(errorPosition, enumerator)); list2.Add(regex.Replace(str3, replacement)); } return(list2.ToArray()); }
/// <summary> /// Stringize a non-IEnum argument to a native command, adding quotes /// and trailing spaces as appropriate. An array gets added as multiple arguments /// each of which will be stringized. /// </summary> /// <param name="context">Execution context instance</param> /// <param name="obj">The object to append</param> /// <param name="separator">A space or comma used when obj is enumerable</param> /// <param name="sawVerbatimArgumentMarker">true if the argument occurs after --%</param> private void appendOneNativeArgument(ExecutionContext context, object obj, char separator, bool sawVerbatimArgumentMarker) { IEnumerator list = LanguagePrimitives.GetEnumerator(obj); bool needSeparator = false; do { string arg; if (list == null) { arg = PSObject.ToStringParser(context, obj); } else { if (!ParserOps.MoveNext(context, null, list)) { break; } arg = PSObject.ToStringParser(context, ParserOps.Current(null, list)); } if (!String.IsNullOrEmpty(arg)) { if (needSeparator) { _arguments.Append(separator); } else { needSeparator = true; } if (sawVerbatimArgumentMarker) { arg = Environment.ExpandEnvironmentVariables(arg); _arguments.Append(arg); } else { // We need to add quotes if the argument has unquoted spaces. The // quotes could appear anywhere inside the string, not just at the start, // e.g. // $a = 'a"b c"d' // echoargs $a 'a"b c"d' a"b c"d // // The above should see 3 identical arguments in argv (the command line will // actually have quotes in different places, but the Win32 command line=>argv parser // erases those differences. // // We need to check quotes that the win32 argument parser checks which is currently // just the normal double quotes, no other special quotes. Also note that mismatched // quotes are supported if (NeedQuotes(arg)) { _arguments.Append('"'); _arguments.Append(arg); _arguments.Append('"'); } else { #if UNIX // On UNIX systems, we expand arguments containing wildcard expressions against // the file system just like bash, etc. if (System.Management.Automation.WildcardPattern.ContainsWildcardCharacters(arg)) { // See if the current working directory is a filesystem provider location // We won't do the expansion if it isn't since native commands can only access the file system. var cwdinfo = Context.EngineSessionState.CurrentLocation; // If it's a filesystem location then expand the wildcards if (string.Equals(cwdinfo.Provider.Name, Microsoft.PowerShell.Commands.FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase)) { bool normalizePath = true; // On UNIX, paths starting with ~ are not normalized if (arg.Length > 0 && arg[0] == '~') { normalizePath = false; } // See if there are any matching paths otherwise just add the pattern as the argument var paths = Context.EngineSessionState.InvokeProvider.ChildItem.Get(arg, false); if (paths.Count > 0) { bool first = true; foreach (var path in paths) { object pbo = path.BaseObject; if (!first) { _arguments.Append(" "); } else { if (!(pbo is System.IO.FileSystemInfo)) { // If the object is not a filesystem object, then just append // the pattern unchanged _arguments.Append(arg); break; } first = false; } var expandedPath = (pbo as System.IO.FileSystemInfo).FullName; if (normalizePath) { expandedPath = Context.SessionState.Path.NormalizeRelativePath(expandedPath, cwdinfo.ProviderPath); } // If the path contains spaces, then add quotes around it. if (NeedQuotes(expandedPath)) { _arguments.Append("\""); _arguments.Append(expandedPath); _arguments.Append("\""); } else { _arguments.Append(expandedPath); } } } else { _arguments.Append(arg); } } else { _arguments.Append(arg); } } else { // Even if there are no wildcards, we still need to possibly // expand ~ into the filesystem provider home directory path ProviderInfo fileSystemProvider = Context.EngineSessionState.GetSingleProvider( Microsoft.PowerShell.Commands.FileSystemProvider.ProviderName); string home = fileSystemProvider.Home; if (string.Equals(arg, "~")) { _arguments.Append(home); } else if (arg.StartsWith("~/", StringComparison.OrdinalIgnoreCase)) { var replacementString = home + arg.Substring(1); _arguments.Append(replacementString); } else { _arguments.Append(arg); } } #else _arguments.Append(arg); #endif } } } } while (list != null); }
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 object GetDynamicParameters() { this._commandRuntime = (MshCommandRuntime)base.commandRuntime; if (this._scriptBlock.HasDynamicParameters) { ArrayList resultList = new ArrayList(); this._functionContext._outputPipe = new Pipe(resultList); this.RunClause(this._runOptimized ? this._scriptBlock.DynamicParamBlock : this._scriptBlock.UnoptimizedDynamicParamBlock, AutomationNull.Value, AutomationNull.Value); if (resultList.Count > 1) { throw PSTraceSource.NewInvalidOperationException("AutomationExceptions", "DynamicParametersWrongType", new object[] { PSObject.ToStringParser(base.Context, resultList) }); } if (resultList.Count != 0) { return(PSObject.Base(resultList[0])); } } return(null); }
/// <summary> /// Stringize a non-IEnum argument to a native command, adding quotes /// and trailing spaces as appropriate. An array gets added as multiple arguments /// each of which will be stringized. /// </summary> /// <param name="context">Execution context instance</param> /// <param name="obj">The object to append</param> /// <param name="argArrayAst">If the argument was an array literal, the Ast, otherwise null</param> /// <param name="sawVerbatimArgumentMarker">true if the argument occurs after --%</param> /// <param name="usedQuotes">True if the argument was a quoted string (single or double)</param> private void appendOneNativeArgument(ExecutionContext context, object obj, ArrayLiteralAst argArrayAst, bool sawVerbatimArgumentMarker, bool usedQuotes) { IEnumerator list = LanguagePrimitives.GetEnumerator(obj); Diagnostics.Assert(argArrayAst == null || obj is object[] && ((object[])obj).Length == argArrayAst.Elements.Count, "array argument and ArrayLiteralAst differ in number of elements"); int currentElement = -1; string separator = ""; do { string arg; if (list == null) { arg = PSObject.ToStringParser(context, obj); } else { if (!ParserOps.MoveNext(context, null, list)) { break; } arg = PSObject.ToStringParser(context, ParserOps.Current(null, list)); currentElement += 1; if (currentElement != 0) { separator = GetEnumerableArgSeparator(argArrayAst, currentElement); } } if (!String.IsNullOrEmpty(arg)) { _arguments.Append(separator); if (sawVerbatimArgumentMarker) { arg = Environment.ExpandEnvironmentVariables(arg); _arguments.Append(arg); } else { // We need to add quotes if the argument has unquoted spaces. The // quotes could appear anywhere inside the string, not just at the start, // e.g. // $a = 'a"b c"d' // echoargs $a 'a"b c"d' a"b c"d // // The above should see 3 identical arguments in argv (the command line will // actually have quotes in different places, but the Win32 command line=>argv parser // erases those differences. // // We need to check quotes that the win32 argument parser checks which is currently // just the normal double quotes, no other special quotes. Also note that mismatched // quotes are supported if (NeedQuotes(arg)) { _arguments.Append('"'); // need to escape all trailing backslashes so the native command receives it correctly // according to http://www.daviddeley.com/autohotkey/parameters/parameters.htm#WINCRULESDOC _arguments.Append(arg); for (int i = arg.Length - 1; i >= 0 && arg[i] == '\\'; i--) { _arguments.Append('\\'); } _arguments.Append('"'); } else { PossiblyGlobArg(arg, usedQuotes); } } } } while (list != null); }
private CommandProcessorBase CreateCommandProcessor( out int index, ExecutionContext context) { index = 0; CommandProcessorBase commandProcessorBase = (CommandProcessorBase)null; if (this._expression != null) { return((CommandProcessorBase) new ScriptCommandProcessor(ScriptBlock.CreateSynthesized(this._expression, this.NodeToken), context, false)); } bool createScope; SessionStateInternal commandSessionState; bool forceSessionState; object commandName = this.GetCommandName(out createScope, out index, out commandSessionState, out forceSessionState, context); switch (commandName) { case ScriptBlock scriptblock: commandProcessorBase = CommandDiscovery.CreateCommandProcessorForScript(scriptblock, context, createScope); if (commandProcessorBase.CommandSessionState == null || forceSessionState) { commandProcessorBase.CommandSessionState = commandSessionState; break; } break; case CommandInfo commandInfo: commandProcessorBase = context.CommandDiscovery.LookupCommandProcessor(commandInfo, context.EngineSessionState.currentScope.ScopeOrigin, new bool?(false)); break; case string stringParser: label_7: if (string.IsNullOrEmpty(stringParser)) { throw InterpreterError.NewInterpreterException(commandName, typeof(RuntimeException), (Token)this._elements[0], "BadExpression", (object)((Token)this._elements[0]).TokenText); } try { if (commandSessionState != context.EngineSessionState) { SessionStateInternal engineSessionState = context.EngineSessionState; try { context.EngineSessionState = commandSessionState; commandProcessorBase = context.CreateCommand(stringParser); break; } finally { context.EngineSessionState = engineSessionState; } } else { commandProcessorBase = context.CreateCommand(stringParser); break; } } catch (ParseException ex) { throw; } catch (RuntimeException ex) { if (ex.ErrorRecord.InvocationInfo == null) { ex.ErrorRecord.SetInvocationInfo(new InvocationInfo((CommandInfo)null, (Token)this._elements[0], context)); } throw; } default: stringParser = PSObject.ToStringParser(context, commandName); goto label_7; } if (commandProcessorBase.CommandSessionState == null || forceSessionState) { commandProcessorBase.CommandSessionState = commandSessionState; } InternalCommand command = commandProcessorBase.Command; command.MyInvocation.ScriptToken = (Token)this._elements[0]; if (context.IsStrictVersion(2) && this._elements.Count == index + 1 && (this._elements[index - 1] is Token && this._elements[index] is ArrayLiteralNode)) { Token element = (Token)this._elements[index - 1]; if (element.Script[element.End] == '(') { throw InterpreterError.NewInterpreterException((object)null, typeof(RuntimeException), (Token)this._elements[index - 1], "StrictModeFunctionCallWithParens"); } } if (createScope) { switch (command) { case ScriptCommand _: case PSScriptCmdlet _: commandProcessorBase.UseLocalScope = true; commandProcessorBase.CommandScope = commandProcessorBase.CommandSessionState == null?context.EngineSessionState.NewScope(commandProcessorBase.FromScriptFile) : commandProcessorBase.CommandSessionState.NewScope(commandProcessorBase.FromScriptFile); goto label_27; } } commandProcessorBase.UseLocalScope = false; commandProcessorBase.CommandScope = commandProcessorBase.CommandSessionState.CurrentScope; label_27: commandProcessorBase.Command.CallingToken = (Token)this._elements[0]; return(commandProcessorBase); }
/// <summary> /// Stringize a non-IEnum argument to a native command, adding quotes /// and trailing spaces as appropriate. An array gets added as multiple arguments /// each of which will be stringized. /// </summary> /// <param name="context">Execution context instance.</param> /// <param name="parameter">The parameter associated with the operation.</param> /// <param name="obj">The object to append.</param> /// <param name="argArrayAst">If the argument was an array literal, the Ast, otherwise null.</param> /// <param name="sawVerbatimArgumentMarker">True if the argument occurs after --%.</param> /// <param name="stringConstantType">Bare, SingleQuoted, or DoubleQuoted.</param> private void AppendOneNativeArgument(ExecutionContext context, CommandParameterInternal parameter, object obj, ArrayLiteralAst argArrayAst, bool sawVerbatimArgumentMarker, StringConstantType stringConstantType) { IEnumerator list = LanguagePrimitives.GetEnumerator(obj); Diagnostics.Assert((argArrayAst == null) || (obj is object[] && ((object[])obj).Length == argArrayAst.Elements.Count), "array argument and ArrayLiteralAst differ in number of elements"); int currentElement = -1; string separator = string.Empty; do { string arg; object currentObj; if (list == null) { arg = PSObject.ToStringParser(context, obj); currentObj = obj; } else { if (!ParserOps.MoveNext(context, null, list)) { break; } currentObj = ParserOps.Current(null, list); arg = PSObject.ToStringParser(context, currentObj); currentElement += 1; if (currentElement != 0) { separator = GetEnumerableArgSeparator(argArrayAst, currentElement); } } if (!string.IsNullOrEmpty(arg)) { // Only add the separator to the argument string rather than adding a separator to the ArgumentList. _arguments.Append(separator); if (sawVerbatimArgumentMarker) { arg = Environment.ExpandEnvironmentVariables(arg); _arguments.Append(arg); // we need to split the argument on spaces _argumentList.AddRange(arg.Split(' ', StringSplitOptions.RemoveEmptyEntries)); } else { // We need to add quotes if the argument has unquoted spaces. The // quotes could appear anywhere inside the string, not just at the start, // e.g. // $a = 'a"b c"d' // echoargs $a 'a"b c"d' a"b c"d // // The above should see 3 identical arguments in argv (the command line will // actually have quotes in different places, but the Win32 command line=>argv parser // erases those differences. // // We need to check quotes that the win32 argument parser checks which is currently // just the normal double quotes, no other special quotes. Also note that mismatched // quotes are supported if (NeedQuotes(arg)) { _arguments.Append('"'); if (stringConstantType == StringConstantType.DoubleQuoted) { _arguments.Append(ResolvePath(arg, Context)); AddToArgumentList(parameter, ResolvePath(arg, Context)); } else { _arguments.Append(arg); AddToArgumentList(parameter, arg); } // need to escape all trailing backslashes so the native command receives it correctly // according to http://www.daviddeley.com/autohotkey/parameters/parameters.htm#WINCRULESDOC for (int i = arg.Length - 1; i >= 0 && arg[i] == '\\'; i--) { _arguments.Append('\\'); } _arguments.Append('"'); } else { if (argArrayAst != null && UseArgumentList) { // We have a literal array, so take the extent, break it on spaces and add them to the argument list. foreach (string element in argArrayAst.Extent.Text.Split(' ', StringSplitOptions.RemoveEmptyEntries)) { PossiblyGlobArg(element, parameter, stringConstantType); } break; } else { PossiblyGlobArg(arg, parameter, stringConstantType); } } } } else if (UseArgumentList && currentObj != null) { // add empty strings to arglist, but not nulls AddToArgumentList(parameter, arg); } }while (list != null); }
/// <summary> /// Stringize a non-IEnum argument to a native command, adding quotes /// and trailing spaces as appropriate. An array gets added as multiple arguments /// each of which will be stringized. /// </summary> /// <param name="context">Execution context instance</param> /// <param name="obj">The object to append</param> /// <param name="separator">A space or comma used when obj is enumerable</param> /// <param name="sawVerbatimArgumentMarker">true if the argument occurs after --%</param> private void appendOneNativeArgument(ExecutionContext context, object obj, char separator, bool sawVerbatimArgumentMarker) { IEnumerator list = LanguagePrimitives.GetEnumerator(obj); bool needSeparator = false; do { string arg; if (list == null) { arg = PSObject.ToStringParser(context, obj); } else { if (!ParserOps.MoveNext(context, null, list)) { break; } arg = PSObject.ToStringParser(context, ParserOps.Current(null, list)); } if (!String.IsNullOrEmpty(arg)) { if (needSeparator) { _arguments.Append(separator); } else { needSeparator = true; } if (sawVerbatimArgumentMarker) { arg = Environment.ExpandEnvironmentVariables(arg); _arguments.Append(arg); } else { // We need to add quotes if the argument has unquoted spaces. The // quotes could appear anywhere inside the string, not just at the start, // e.g. // $a = 'a"b c"d' // echoargs $a 'a"b c"d' a"b c"d // // The above should see 3 identical arguments in argv (the command line will // actually have quotes in different places, but the Win32 command line=>argv parser // erases those differences. // // We need to check quotes that the win32 arugment parser checks which is currently // just the normal double quotes, no other special quotes. Also note that mismatched // quotes are supported. bool needQuotes = false; int quoteCount = 0; for (int i = 0; i < arg.Length; i++) { if (arg[i] == '"') { quoteCount += 1; } else if (char.IsWhiteSpace(arg[i]) && (quoteCount % 2 == 0)) { needQuotes = true; } } if (needQuotes) { _arguments.Append('"'); _arguments.Append(arg); _arguments.Append('"'); } else { _arguments.Append(arg); } } } } while (list != null); }