public CimActivityImplementationContext(ActivityImplementationContext activityImplementationContext, string computerName, PSCredential credential, string certificateThumbprint, AuthenticationMechanism? authenticationMechanism, bool useSsl, uint port, PSSessionOption sessionOption, CimSession session, CimSessionOptions cimSessionOptions, string moduleDefinition, Uri resourceUri) { if (activityImplementationContext != null) { base.PowerShellInstance = activityImplementationContext.PowerShellInstance; this.ResourceUri = resourceUri; this.ComputerName = computerName; base.PSCredential = credential; base.PSCertificateThumbprint = certificateThumbprint; base.PSAuthentication = authenticationMechanism; base.PSUseSsl = new bool?(useSsl); base.PSPort = new uint?(port); base.PSSessionOption = sessionOption; this.Session = session; this.SessionOptions = cimSessionOptions; if (moduleDefinition != null) { CimActivityImplementationContext._moduleScriptBlock = ScriptBlock.Create(moduleDefinition); this._moduleDefinition = moduleDefinition; } return; } else { throw new ArgumentNullException("activityImplementationContext"); } }
internal FunctionInfo(string verb, string noun, ScriptBlock function, IEnumerable<ParameterAst> explicitParams, ScopedItemOptions options) : this(verb + "-" + noun, function, explicitParams, options) { Verb = verb; Noun = noun; }
/// <summary> /// </summary> /// <param name="name">The name of the variable, without the preceeding $.</param> /// <param name="onGet">The get accessor for the variable. The return value will be used as the variable's value.</param> /// <param name="onSet">The set accessor for the variable. Use $Args[0] to access the new variable.</param> /// <param name="isCollection">True to wrap the value of the variable in a collection even if only a single value is returned.</param> public DynamicVariable(string name, ScriptBlock onGet, ScriptBlock onSet, bool isCollection) : base(name, null, ScopedItemOptions.AllScope) { OnGet = onGet; OnSet = onSet; IsCollection = isCollection; }
internal SessionStateFunctionEntry(string name, string definition, ScopedItemOptions options, SessionStateEntryVisibility visibility, System.Management.Automation.ScriptBlock scriptBlock, string helpFile) : base(name, visibility) { this._definition = definition; this._options = options; this._scriptBlock = scriptBlock; this._helpFile = helpFile; }
public void Set(string name, ScriptBlock function, string description = "") { var qualName = new SessionStateScope<FunctionInfo>.QualifiedName(name); var info = new FunctionInfo(qualName.UnqualifiedName, function); info.Description = description; _scope.Set(name, info, true, true); }
private static object InvokeScript(string methodName, ScriptBlock script, object @this, object[] arguments) { object obj2; try { obj2 = script.DoInvokeReturnAsIs(true, ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe, AutomationNull.Value, AutomationNull.Value, @this, arguments); } catch (SessionStateOverflowException exception) { throw new MethodInvocationException("ScriptMethodSessionStateOverflowException", exception, ExtendedTypeSystem.MethodInvocationException, new object[] { methodName, arguments.Length, exception.Message }); } catch (RuntimeException exception2) { throw new MethodInvocationException("ScriptMethodRuntimeException", exception2, ExtendedTypeSystem.MethodInvocationException, new object[] { methodName, arguments.Length, exception2.Message }); } catch (TerminateException) { throw; } catch (FlowControlException exception3) { throw new MethodInvocationException("ScriptMethodFlowControlException", exception3, ExtendedTypeSystem.MethodInvocationException, new object[] { methodName, arguments.Length, exception3.Message }); } catch (PSInvalidOperationException exception4) { throw new MethodInvocationException("ScriptMethodInvalidOperationException", exception4, ExtendedTypeSystem.MethodInvocationException, new object[] { methodName, arguments.Length, exception4.Message }); } return obj2; }
internal FunctionInfo(string name, ScriptBlock function, ScopedItemOptions options) : base(name, CommandTypes.Function) { ScriptBlock = function; Options = options; ScopeUsage = ScopeUsages.NewScope; }
private HelpCommentsParser(CommandInfo commandInfo, List<string> parameterDescriptions) { this._sections = new CommentHelpInfo(); this._parameters = new Dictionary<string, string>(); this._examples = new List<string>(); this._inputs = new List<string>(); this._outputs = new List<string>(); this._links = new List<string>(); FunctionInfo info = commandInfo as FunctionInfo; if (info != null) { this.scriptBlock = info.ScriptBlock; this.commandName = info.Name; } else { ExternalScriptInfo info2 = commandInfo as ExternalScriptInfo; if (info2 != null) { this.scriptBlock = info2.ScriptBlock; this.commandName = info2.Path; } } this.commandMetadata = commandInfo.CommandMetadata; this.parameterDescriptions = parameterDescriptions; }
internal Breakpoint(string script, ScriptBlock action) { this.Enabled = true; this.Script = script; this.Id = _lastID++; this.Action = action; this.HitCount = 0; }
public SessionStateFunctionEntry(string name, string definition, ScopedItemOptions options, string helpFile) : base(name, SessionStateEntryVisibility.Public) { this._definition = definition; base._commandType = CommandTypes.Function; this._options = options; this._scriptBlock = System.Management.Automation.ScriptBlock.Create(this._definition); this._helpFile = helpFile; }
public LogFile(string filename, StreamType streams = StreamType.All, ScriptBlock errorCallback = null) { fileName = System.IO.Path.GetFileName(filename); path = System.IO.Path.GetDirectoryName(filename); Streams = streams; ErrorCallback = errorCallback; }
internal ExternalScriptInfo(string path, ScopeUsages scopeUsage = ScopeUsages.NewScope) : base(path, CommandTypes.ExternalScript) { Path = path; ScopeUsage = scopeUsage; _scriptContents = null; _scriptBlock = null; }
/// <summary> /// constructor /// </summary> /// <param name="scriptBlock"></param> /// <exception cref="ArgumentNullException"></exception> internal MshExpression(ScriptBlock scriptBlock) { if (scriptBlock == null) { throw PSTraceSource.NewArgumentNullException("scriptBlock"); } Script = scriptBlock; }
internal Breakpoint(string script, ScriptBlock action) { Enabled = true; Script = script; Id = s_lastID++; Action = action; HitCount = 0; }
internal Breakpoint(string script, ScriptBlock action, int id) { Enabled = true; Script = script; Id = id; Action = action; HitCount = 0; }
public AsyncJob(ScriptBlock Script, Hashtable Parameters) : this(Script) { foreach(DictionaryEntry param in Parameters) { this.Pipeline.AddParameter((string)param.Key, param.Value); } }
protected ScriptCommandProcessorBase(ScriptBlock scriptBlock, ExecutionContext context, bool useLocalScope, CommandOrigin origin, SessionStateInternal sessionState) { this._dontUseScopeCommandOrigin = false; base.CommandInfo = new ScriptInfo(string.Empty, scriptBlock, context); base._fromScriptFile = false; this.CommonInitialization(scriptBlock, context, useLocalScope, sessionState); base.Command.CommandOriginInternal = origin; }
public PowerShellProcessInstance(Version powerShellVersion, PSCredential credential, ScriptBlock initializationScript, bool useWow64) { this._syncObject = new object(); string pSExePath = PSExePath; if (useWow64) { string environmentVariable = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE"); if (!string.IsNullOrEmpty(environmentVariable) && (environmentVariable.Equals("amd64", StringComparison.OrdinalIgnoreCase) || environmentVariable.Equals("ia64", StringComparison.OrdinalIgnoreCase))) { pSExePath = PSExePath.ToLowerInvariant().Replace(@"\system32\", @"\syswow64\"); if (!System.IO.File.Exists(pSExePath)) { throw new PSInvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.IPCWowComponentNotPresent, new object[] { pSExePath })); } } } string str4 = string.Empty; Version version = powerShellVersion ?? PSVersionInfo.PSVersion; if (null == version) { version = new Version(3, 0); } str4 = string.Format(CultureInfo.InvariantCulture, "-Version {0}", new object[] { new Version(version.Major, version.Minor) }); str4 = string.Format(CultureInfo.InvariantCulture, "{0} -s -NoLogo -NoProfile", new object[] { str4 }); if (initializationScript != null) { string str5 = initializationScript.ToString(); if (!string.IsNullOrEmpty(str5)) { string str6 = Convert.ToBase64String(Encoding.Unicode.GetBytes(str5)); str4 = string.Format(CultureInfo.InvariantCulture, "{0} -EncodedCommand {1}", new object[] { str4, str6 }); } } ProcessStartInfo info = new ProcessStartInfo { FileName = useWow64 ? pSExePath : PSExePath, Arguments = str4, UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, WindowStyle = ProcessWindowStyle.Hidden, CreateNoWindow = true, LoadUserProfile = true }; this._startInfo = info; if (credential != null) { NetworkCredential networkCredential = credential.GetNetworkCredential(); this._startInfo.UserName = networkCredential.UserName; this._startInfo.Domain = string.IsNullOrEmpty(networkCredential.Domain) ? "." : networkCredential.Domain; this._startInfo.Password = credential.Password; } System.Diagnostics.Process process = new System.Diagnostics.Process { StartInfo = this._startInfo, EnableRaisingEvents = true }; this._process = process; }
/// <summary> /// This constructor is used primarily via PowerShell scripts. /// </summary> /// <param name="scriptBlock"></param> public ArgumentCompleterAttribute(ScriptBlock scriptBlock) { if (scriptBlock == null) { throw PSTraceSource.NewArgumentNullException("scriptBlock"); } ScriptBlock = scriptBlock; }
public WorkflowInfo( string name, string definition, ScriptBlock workflow, string xamlDefinition, WorkflowInfo[] workflowsCalled) : base(name, workflow, null) { }
public AsyncJob(ScriptBlock Script) : base(Script.ToString()) { this.Pipeline = PSRunspace.Instance.NewPipeline(); this.Pipeline.AddCommand(Script.ToString()); this.Pipeline.InvocationStateChanged += Pipeline_InvocationStateChanged; this.PSJobTypeName = "RunspaceJob"; this.Name = string.Format("Async{0}", this.Id); }
internal FunctionInfo(string verb, string noun, ScriptBlock function, ScopedItemOptions options) : base(verb + "-" + noun, CommandTypes.Function) { ScriptBlock = function; Options = options; Verb = verb; Noun = noun; ScopeUsage = ScopeUsages.NewScope; }
public static void CreateWizard(string name, ScriptBlock[] sb) { UIAutomation.Commands.NewUIAWizardCommand cmdlet = new UIAutomation.Commands.NewUIAWizardCommand(); cmdlet.Name = name; cmdlet.StartAction = sb; UIANewWizardCommand command = new UIANewWizardCommand(cmdlet); command.Execute(); }
internal FunctionInfo(string name, ScriptBlock function, IEnumerable<ParameterAst> explicitParams, ScopedItemOptions options) : base(name, CommandTypes.Function) { ScriptBlock = function; Options = options; ScopeUsage = ScopeUsages.NewScope; _explicitParameters = explicitParams == null ? new ReadOnlyCollection<ParameterAst>(new ParameterAst[0]) : explicitParams.ToReadOnlyCollection(); }
/// <summary> /// Creates an instance of the ScriptInfo class with the specified name, and script. /// </summary> /// /// <param name="name"> /// The name of the script. /// </param> /// /// <param name="script"> /// The script definition /// </param> /// /// <param name="context"> /// The execution context for the script. /// </param> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="script"/> is null. /// </exception> /// internal ScriptInfo(string name, ScriptBlock script, ExecutionContext context) : base(name, CommandTypes.Script, context) { if (script == null) { throw PSTraceSource.NewArgumentException("script"); } this.ScriptBlock = script; } // ScriptInfo ctor
public void BeginInvoke(ScriptBlock scriptblock, PSObject inputObject) { _percentComplete = 0; string command = $"param($_,$PSItem, $PSPArallelIndex,$PSParallelProgressId){scriptblock}"; _powerShell.AddScript(command) .AddParameter("_", inputObject) .AddParameter("PSItem", inputObject) .AddParameter("PSParallelIndex", _index) .AddParameter("PSParallelProgressId", _index + 1000); _powerShell.BeginInvoke(_input, _output); }
public ScriptBlockOutputSubscriber(ScriptBlock onWriteOutput, ScriptBlock onWriteDebug, ScriptBlock onWriteVerbose, ScriptBlock onWriteError, ScriptBlock onWriteWarning) { this.OnWriteOutput = onWriteOutput; this.OnWriteDebug = onWriteDebug; this.OnWriteVerbose = onWriteVerbose; this.OnWriteError = onWriteError; this.OnWriteWarning = onWriteWarning; }
/// <summary> /// Constructs a ScriptParameterBinder with the specified context /// </summary> /// /// <param name="script"> /// The script block representing the code being run /// </param> /// /// <param name="invocationInfo"> /// The invocation information about the code that is being run. /// </param> /// /// <param name="context"> /// The context under which the shell function is executing. /// </param> /// /// <param name="command"> /// The command instance that represents the script in a pipeline. May be null. /// </param> /// /// <param name="localScope"> /// If binding in a new local scope, the scope to set variables in. If dotting, the value is null. /// </param> internal ScriptParameterBinder( ScriptBlock script, InvocationInfo invocationInfo, ExecutionContext context, InternalCommand command, SessionStateScope localScope) : base(invocationInfo, context, command) { Diagnostics.Assert(script != null, "caller to verify script is not null."); this.Script = script; this.LocalScope = localScope; }
public PSScriptProperty(string name, ScriptBlock getterScript) { if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException("name"); } base.name = name; if (getterScript == null) { throw PSTraceSource.NewArgumentNullException("getterScript"); } this.getterScript = getterScript; }
internal ScriptParameterBinderController(ScriptBlock script, InvocationInfo invocationInfo, ExecutionContext context, InternalCommand command, SessionStateScope localScope) : base(invocationInfo, context, new ScriptParameterBinder(script, invocationInfo, context, command, localScope)) { this.DollarArgs = new List<object>(); if (script.HasDynamicParameters) { base.UnboundParameters = base.BindableParameters.ReplaceMetadata(script.ParameterMetadata); } else { base._bindableParameters = script.ParameterMetadata; base.UnboundParameters = new List<MergedCompiledCommandParameter>(base._bindableParameters.BindableParameters.Values); } }
private List <VariableExpressionAst> GetUsingVariables(System.Management.Automation.ScriptBlock localScriptBlock) { List <UsingExpressionAst> source = new List <UsingExpressionAst>(); foreach (Ast ast in UsingExpressionAstSearcher.FindAllUsingExpressionExceptForWorkflow(localScriptBlock.Ast).ToList <Ast>()) { UsingExpressionAst usingExpr = ast as UsingExpressionAst; if (ScriptBlockToPowerShellConverter.IsUsingExpressionInFunction(usingExpr, localScriptBlock.Ast)) { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(AutomationExceptions.UsingVariableNotSupportedInFunctionOrFilter), "UsingVariableNotSupportedInFunctionOrFilter", ErrorCategory.InvalidOperation, ast); base.ThrowTerminatingError(errorRecord); } else { source.Add(usingExpr); } } return(source.Select <UsingExpressionAst, VariableExpressionAst>(new Func <UsingExpressionAst, VariableExpressionAst>(UsingExpressionAst.ExtractUsingVariable)).ToList <VariableExpressionAst>()); }
protected override void BeginProcessing() { base.BeginProcessing(); if (this.filePath != null) { this.scriptBlock = this.GetScriptBlockFromFile(this.filePath, this.IsLiteralPath); } try { this._powershellv3 = this._powershellv2 = this.scriptBlock.GetPowerShell(this.args); } catch (ScriptBlockToPowerShellNotSupportedException) { } switch (base.ParameterSetName) { case "FilePathComputerName": case "LiteralFilePathComputerName": case "ComputerName": { string[] resolvedComputerNames = null; base.ResolveComputerNames(this.ComputerName, out resolvedComputerNames); base.ResolvedComputerNames = resolvedComputerNames; this.CreateHelpersForSpecifiedComputerNames(); return; } case "FilePathRunspace": case "Session": base.ValidateRemoteRunspacesSpecified(); this.CreateHelpersForSpecifiedRunspaces(); return; case "FilePathUri": case "Uri": this.CreateHelpersForSpecifiedUris(); return; } }
public PSCustomFileTemplateLoader(SMA.ScriptBlock getPathFunc, SMA.ScriptBlock loadFunc) { _getPathScript = getPathFunc; _loadTemplateScript = loadFunc; }
internal FilterInfo(string name, ScriptBlock filter, ExecutionContext context) : this(name, filter, context, null) { }
public WorkflowInfo(string name, string definition, ScriptBlock workflow, string xamlDefinition, WorkflowInfo[] workflowsCalled, PSModuleInfo module) : this(name, definition, workflow, xamlDefinition, workflowsCalled) { base.SetModule(module); }
/// <summary> /// Creates an instance of the FunctionInfo class with the specified name and ScriptBlock. /// </summary> /// <param name="name"> /// The name of the function. /// </param> /// <param name="function"> /// The ScriptBlock for the function /// </param> /// <param name="options"> /// The options to set on the function. Note, Constant can only be set at creation time. /// </param> /// <param name="context"> /// The execution context for the function. /// </param> /// <param name="helpFile"> /// The name of the help file associated with the function. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="function"/> is null. /// </exception> internal FunctionInfo(string name, ScriptBlock function, ScopedItemOptions options, ExecutionContext context, string helpFile) : this(name, function, context, helpFile) { _options = options; }
internal DlrScriptCommandProcessor(ScriptBlock scriptBlock, ExecutionContext context, bool useNewScope, CommandOrigin origin, SessionStateInternal sessionState) : base(scriptBlock, context, useNewScope, origin, sessionState) { Init(); }
/// <summary> /// Creates an instance of the FunctionInfo class with the specified name and ScriptBlock. /// </summary> /// <param name="name"> /// The name of the function. /// </param> /// <param name="function"> /// The ScriptBlock for the function /// </param> /// <param name="context"> /// The execution context for the function. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="function"/> is null. /// </exception> internal FunctionInfo(string name, ScriptBlock function, ExecutionContext context) : this(name, function, context, null) { }
internal FilterInfo(string name, ScriptBlock filter, ScopedItemOptions options, ExecutionContext context) : this(name, filter, options, context, null) { }
public ScriptBlock(System.Management.Automation.ScriptBlock scriptBlock) { _scriptBlock = scriptBlock; _variables = new List <PSVariable>(); _toString = _scriptBlock.ToString(); }
internal WorkflowInfo(string name, ScriptBlock workflow, ScopedItemOptions options, ExecutionContext context) : this(name, workflow, options, context, null) { }
internal WorkflowInfo(string name, ScriptBlock workflow, ExecutionContext context) : this(name, workflow, context, null) { }
/// <summary> /// Create suggestion with scriptblock rule and scriptblock suggestion with arguments. /// </summary> private static Hashtable NewSuggestion(int id, string category, SuggestionMatchType matchType, ScriptBlock rule, ScriptBlock suggestion, object[] suggestionArgs, bool enabled) { Hashtable result = NewSuggestion(id, category, matchType, rule, suggestion, enabled); result.Add("SuggestionArgs", suggestionArgs); return(result); }
private void LoadScriptInfo() { if (this._context.RunspaceConfiguration == null) { return; } foreach (ScriptConfigurationEntry script in (IEnumerable <ScriptConfigurationEntry>) this._context.RunspaceConfiguration.Scripts) { try { this.cachedScriptInfo.Add(script.Name, new ScriptInfo(script.Name, ScriptBlock.Create(this._context, script.Definition), this._context)); } catch (ArgumentException ex) { throw CommandDiscovery.tracer.NewNotSupportedException("DiscoveryExceptions", "DuplicateScriptName", (object)script.Name); } } }
/// <summary> /// Updates a function. /// </summary> /// /// <param name="newFunction"> /// The script block that the function should represent. /// </param> /// /// <param name="force"> /// If true, the script block will be applied even if the filter is ReadOnly. /// </param> /// /// <param name="options"> /// Any options to set on the new function, null if none. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="newFunction"/> is null. /// </exception> /// internal void Update(ScriptBlock newFunction, bool force, ScopedItemOptions options) { Update(newFunction, force, options, null); }
/// <summary> /// Updates a function. /// </summary> /// <param name="newFunction"> /// The script block that the function should represent. /// </param> /// <param name="force"> /// If true, the script block will be applied even if the filter is ReadOnly. /// </param> /// <param name="options"> /// Any options to set on the new function, null if none. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="newFunction"/> is null. /// </exception> internal void Update(ScriptBlock newFunction, bool force, ScopedItemOptions options) { Update(newFunction, force, options, null); this.DefiningLanguageMode = newFunction.LanguageMode; }
/// <summary> /// Set a function in the current scope of session state. /// </summary> /// <param name="name"> /// The name of the function to set. /// </param> /// <param name="function"> /// The new value of the function being set. /// </param> /// <param name="originalFunction"> /// The original function (if any) from which the ScriptBlock is derived. /// </param> /// <param name="force"> /// If true, the function will be set even if its ReadOnly. /// </param> /// <param name="origin"> /// The origin of the caller /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// or /// If <paramref name="function"/> is not a <see cref="FilterInfo">FilterInfo</see> /// or <see cref="FunctionInfo">FunctionInfo</see> /// </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="function"/> is null. /// </exception> /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the function is read-only or constant. /// </exception> internal FunctionInfo SetFunction( string name, ScriptBlock function, FunctionInfo originalFunction, bool force, CommandOrigin origin) { if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException("name"); } if (function == null) { throw PSTraceSource.NewArgumentNullException("function"); } string originalName = name; FunctionLookupPath path = new FunctionLookupPath(name); name = path.UnqualifiedPath; if (string.IsNullOrEmpty(name)) { SessionStateException exception = new SessionStateException( originalName, SessionStateCategory.Function, "ScopedFunctionMustHaveName", SessionStateStrings.ScopedFunctionMustHaveName, ErrorCategory.InvalidArgument); throw exception; } ScopedItemOptions options = ScopedItemOptions.None; if (path.IsPrivate) { options |= ScopedItemOptions.Private; } FunctionScopeItemSearcher searcher = new FunctionScopeItemSearcher( this, path, origin); FunctionInfo result = null; SessionStateScope scope = searcher.InitialScope; if (searcher.MoveNext()) { scope = searcher.CurrentLookupScope; name = searcher.Name; if (path.IsPrivate) { // Need to add the Private flag FunctionInfo existingFunction = scope.GetFunction(name); options |= existingFunction.Options; result = scope.SetFunction(name, function, originalFunction, options, force, origin, ExecutionContext); } else { result = scope.SetFunction(name, function, force, origin, ExecutionContext); } } else { if (path.IsPrivate) { result = scope.SetFunction(name, function, originalFunction, options, force, origin, ExecutionContext); } else { result = scope.SetFunction(name, function, force, origin, ExecutionContext); } } return(result); }
/// <summary> /// Set a function in the current scope of session state. /// /// BUGBUG: this overload is preserved because a lot of tests use reflection to /// call it. The tests should be fixed and this API eventually removed. /// </summary> /// <param name="name"> /// The name of the function to set. /// </param> /// <param name="function"> /// The new value of the function being set. /// </param> /// <param name="force"> /// If true, the function will be set even if its ReadOnly. /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// or /// If <paramref name="function"/> is not a <see cref="FilterInfo">FilterInfo</see> /// or <see cref="FunctionInfo">FunctionInfo</see> /// </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="function"/> is null. /// </exception> /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the function is read-only or constant. /// </exception> internal FunctionInfo SetFunction(string name, ScriptBlock function, bool force) { return(SetFunction(name, function, null, force, CommandOrigin.Internal)); }
internal static List <string> GetSuggestion(HistoryInfo lastHistory, object lastError, ArrayList errorList) { var returnSuggestions = new List <string>(); PSModuleInfo invocationModule = new PSModuleInfo(true); invocationModule.SessionState.PSVariable.Set("lastHistory", lastHistory); invocationModule.SessionState.PSVariable.Set("lastError", lastError); int initialErrorCount = 0; // Go through all of the suggestions foreach (Hashtable suggestion in s_suggestions) { initialErrorCount = errorList.Count; // Make sure the rule is enabled if (!LanguagePrimitives.IsTrue(suggestion["Enabled"])) { continue; } SuggestionMatchType matchType = (SuggestionMatchType)LanguagePrimitives.ConvertTo( suggestion["MatchType"], typeof(SuggestionMatchType), CultureInfo.InvariantCulture); // If this is a dynamic match, evaluate the ScriptBlock if (matchType == SuggestionMatchType.Dynamic) { object result = null; ScriptBlock evaluator = suggestion["Rule"] as ScriptBlock; if (evaluator is null) { suggestion["Enabled"] = false; throw new ArgumentException( SuggestionStrings.RuleMustBeScriptBlock, "Rule"); } try { result = invocationModule.Invoke(evaluator, null); } catch (Exception) { // Catch-all OK. This is a third-party call-out. suggestion["Enabled"] = false; continue; } // If it returned results, evaluate its suggestion if (LanguagePrimitives.IsTrue(result)) { string suggestionText = GetSuggestionText(suggestion["Suggestion"], (object[])suggestion["SuggestionArgs"], invocationModule); if (!string.IsNullOrEmpty(suggestionText)) { string returnString = string.Format( CultureInfo.CurrentCulture, "Suggestion [{0},{1}]: {2}", (int)suggestion["Id"], (string)suggestion["Category"], suggestionText); returnSuggestions.Add(returnString); } } } else { string matchText = string.Empty; // Otherwise, this is a Regex match against the // command or error if (matchType == SuggestionMatchType.Command) { matchText = lastHistory.CommandLine; } else if (matchType == SuggestionMatchType.Error) { if (lastError != null) { Exception lastException = lastError as Exception; if (lastException != null) { matchText = lastException.Message; } else { matchText = lastError.ToString(); } } } else if (matchType == SuggestionMatchType.ErrorId) { if (lastError != null && lastError is ErrorRecord errorRecord) { matchText = errorRecord.FullyQualifiedErrorId; } } else { suggestion["Enabled"] = false; throw new ArgumentException( SuggestionStrings.InvalidMatchType, "MatchType"); } // If the text matches, evaluate the suggestion if (Regex.IsMatch(matchText, (string)suggestion["Rule"], RegexOptions.IgnoreCase)) { string suggestionText = GetSuggestionText(suggestion["Suggestion"], (object[])suggestion["SuggestionArgs"], invocationModule); if (!string.IsNullOrEmpty(suggestionText)) { string returnString = string.Format( CultureInfo.CurrentCulture, "Suggestion [{0},{1}]: {2}", (int)suggestion["Id"], (string)suggestion["Category"], suggestionText); returnSuggestions.Add(returnString); } } } // If the rule generated an error, disable it if (errorList.Count != initialErrorCount) { suggestion["Enabled"] = false; } } return(returnSuggestions); }
/// <summary> /// Creates an instance of the FunctionInfo class with the specified name and ScriptBlock. /// </summary> /// <param name="name"> /// The name of the function. /// </param> /// <param name="function"> /// The ScriptBlock for the function /// </param> /// <param name="options"> /// The options to set on the function. Note, Constant can only be set at creation time. /// </param> /// <param name="context"> /// The execution context for the function. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="function"/> is null. /// </exception> internal FunctionInfo(string name, ScriptBlock function, ScopedItemOptions options, ExecutionContext context) : this(name, function, options, context, null) { }
internal WorkflowInfo(string name, ScriptBlock workflow, ScopedItemOptions options, ExecutionContext context, string helpFile) : base(name, workflow, options, context, helpFile) { this._definition = ""; base.SetCommandType(CommandTypes.Workflow); }
internal static PowerShell Convert(ScriptBlockAst body, ReadOnlyCollection <ParameterAst> functionParameters, bool isTrustedInput, ExecutionContext context, Dictionary <string, object> variables, bool filterNonUsingVariables, bool?createLocalScope, object[] args) { ExecutionContext.CheckStackDepth(); if (args == null) { args = Array.Empty <object>(); } // Perform validations on the ScriptBlock. GetSimplePipeline can allow for more than one // pipeline if the first parameter is true, but Invoke-Command doesn't yet support multiple // pipelines in a PowerShell (it just grabs the last command directly.) The rest of this // code properly supports multiple pipelines, so it should just work to change the false to true // if/when Invoke-Command can support multiple pipelines. string errorId; string errorMsg; body.GetSimplePipeline(true, out errorId, out errorMsg); if (errorId != null) { throw new ScriptBlockToPowerShellNotSupportedException(errorId, null, errorMsg); } var checker = new ScriptBlockToPowerShellChecker { ScriptBeingConverted = body }; if (functionParameters != null) { foreach (var parameter in functionParameters) { parameter.InternalVisit(checker); } } body.InternalVisit(checker); // When the context is null (or they haven't supplied any variables), throw, but only if we really need the // context (basically, if we have some variable reference to resolve). if (context == null && (checker.HasUsingExpr || checker.UsesParameter) && (variables == null)) { throw new PSInvalidOperationException(AutomationExceptions.CantConvertScriptBlockWithNoContext); } try { var converter = new ScriptBlockToPowerShellConverter { _context = context, _createLocalScope = createLocalScope }; if (checker.HasUsingExpr) { converter._usingValueMap = GetUsingValues(body, isTrustedInput, context, variables, filterNonUsingVariables).Item1; } if (checker.UsesParameter) { // If any parameters are used, we create a new scope and bind the parameters. var newScope = context.EngineSessionState.NewScope(false); context.EngineSessionState.CurrentScope = newScope; context.EngineSessionState.CurrentScope.ScopeOrigin = CommandOrigin.Internal; var locals = MutableTuple.MakeTuple(Compiler.DottedLocalsTupleType, Compiler.DottedLocalsNameIndexMap); // Get the parameter metadata for the script block. // If 'functionParameters' is not null, then the ScriptBlockAst is actually the body of a FunctionDefinitionAst, and it doesn't have a ParamBlock. // If 'functionParameters' is null, then the ScriptBlockAst may have parameters defined in its ParamBlock. bool usesCmdletBinding = false; var parameters = functionParameters != null ? Compiler.GetParameterMetaData(functionParameters, true, ref usesCmdletBinding) : ((IParameterMetadataProvider)body).GetParameterMetadata(true, ref usesCmdletBinding); object[] remainingArgs = ScriptBlock.BindArgumentsForScriptblockInvoke( (RuntimeDefinedParameter[])parameters.Data, args, context, false, null, locals); locals.SetAutomaticVariable(AutomaticVariable.Args, remainingArgs, context); newScope.LocalsTuple = locals; } foreach (var pipeline in body.EndBlock.Statements.OfType <PipelineAst>()) { converter._powershell.AddStatement(); converter.ConvertPipeline(pipeline, isTrustedInput); } return(converter._powershell); } finally { if (checker.UsesParameter) { context.EngineSessionState.RemoveScope(context.EngineSessionState.CurrentScope); } } }
/// <summary> /// Create suggestion with scriptblock rule and suggestion. /// </summary> private static Hashtable NewSuggestion(int id, string category, SuggestionMatchType matchType, ScriptBlock rule, ScriptBlock suggestion, bool enabled) { Hashtable result = new Hashtable(StringComparer.CurrentCultureIgnoreCase); result["Id"] = id; result["Category"] = category; result["MatchType"] = matchType; result["Rule"] = rule; result["Suggestion"] = suggestion; result["Enabled"] = enabled; return(result); }
internal PSEventSubscriber(System.Management.Automation.ExecutionContext context, int id, object source, string eventName, string sourceIdentifier, ScriptBlock action, bool supportEvent, bool forwardEvent, int maxTriggerCount) : this(context, id, source, eventName, sourceIdentifier, supportEvent, forwardEvent, maxTriggerCount) { if (action != null) { ScriptBlock block = this.CreateBoundScriptBlock(action); this.action = new PSEventJob(context.Events, this, block, sourceIdentifier); } }
internal FilterInfo(string name, ScriptBlock filter, ScopedItemOptions options, ExecutionContext context, string helpFile) : base(name, filter, options, context, helpFile) { base.SetCommandType(CommandTypes.Filter); }
/// <summary> /// For diagnostic purposes. /// </summary> /// <returns></returns> public override string ToString() { return(ScriptBlock.ToString()); }
/// <summary> /// Get using values in the array form. /// </summary> internal static object[] GetUsingValuesAsArray(ScriptBlock scriptBlock, bool isTrustedInput, ExecutionContext context, Dictionary <string, object> variables) { return(GetUsingValues(scriptBlock.Ast, isTrustedInput, context, variables, false).Item2); }
// internals internal ScriptInfo(string name, ScriptBlock script) : base(name, CommandTypes.Script) { ScriptBlock = script; }