/// <summary> /// Attach some script to the current PowerShell instance /// Attach Rule : /// 1. If the script is start with "$", we directly add it to the pipeline /// 2. If the current script is storage cmdlet, we need to add the current storage context to it. /// 3. Otherwise, split the script into [CommandName] and many [-Parameter][Value] pairs, attach them using PowerShell command interface(AddParameter/AddCommand/etc) /// //TODO update the step 3 /// </summary> /// <param name="ps">PowerShell instance</param> private void AttachPipeline(PowerShell ps) { foreach (string cmd in pipeLine) { if (cmd.Length > 0 && cmd[0] == '$') { ps.AddScript(cmd); } else { string[] cmdOpts = cmd.Split(' '); string cmdName = cmdOpts[0]; ps.AddCommand(cmdName); string opts = string.Empty; bool skip = false; for (int i = 1; i < cmdOpts.Length; i++) { if (skip) { skip = false; continue; } if (cmdOpts[i].IndexOf("-") != 0) { ps.AddArgument(cmdOpts[i]); } else { if (i + 1 < cmdOpts.Length && cmdOpts[i + 1].IndexOf("-") != 0) { ps.BindParameter(cmdOpts[i].Substring(1), cmdOpts[i + 1]); skip = true; } else { ps.BindParameter(cmdOpts[i].Substring(1)); skip = false; } } } //add storage context for azure storage cmdlet //It make sure all the storage cmdlet in pipeline use the same storage context if (cmdName.ToLower().IndexOf("-azurestorage") != -1) { AddCommonParameters(ps); } } } }
public static void DoCommand(string command, object[] args) { ps.AddCommand(command); if (args != null) { foreach (object s in args) { ps.AddArgument(s); } } ps.Invoke(); /* * foreach (PSObject result in ps.Invoke()) * { * Console.WriteLine( * "{0,-24}{1}", * result.Members["ProcessName"].Value, * result.Members["Id"].Value); * } */ }
/// <summary> /// App uninstaller /// </summary> private string RemoveUWP() { string success = "Successfully removed:\n"; string failed = "Failed to remove:\n"; foreach (var item in LstUWPRemove.Items) { powerShell.Commands.Clear(); powerShell.AddCommand("Get-AppxPackage"); powerShell.AddArgument(item.ToString()); powerShell.AddCommand("remove-appxpackage"); List <PSObject> PSOutput = new List <PSObject>(powerShell.Invoke()); foreach (var p in powerShell.Streams.Progress) { if (p.Activity.Contains(item.ToString()) && p.StatusDescription == "Completed") // Removed successfully { success += "\t" + item.ToString() + "\n"; // Console.WriteLine(success + item.ToString()); break; } else if (p.Activity.Contains(item.ToString()) && p.StatusDescription == "Error") // NOT removed { if (!failed.Contains(item.ToString())) { failed += "\t" + item.ToString() + "\n"; } // Console.WriteLine(failed + p.Activity); } } powerShell.Streams.Progress.Clear(); /* Detailed log OFF * if (powerShell.HadErrors) foreach (var p in powerShell.Streams.Error) { Console.WriteLine("\n\nERROR:\n" + p.ToString() + "\n\n"); } */ } string outputPS; if (powerShell.HadErrors) { outputPS = success + "\n" + failed; powerShell.Streams.Error.Clear(); } else { outputPS = success; } return(outputPS); }
public static void InitalizeProgramms() { using (PowerShell PowerShellInstance = PowerShell.Create()) { PowerShellInstance.AddCommand("Get-ItemProperty"); PowerShellInstance.AddArgument(@"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\*"); Dictionary <string, string> programs = new Dictionary <string, string>(); PowerShellInstance.AddCommand("Select-Object"); PowerShellInstance.AddArgument(new List <string>() { "PSChildName", "(Default)" }); Collection <PSObject> PSOutput = PowerShellInstance.Invoke(); foreach (var item in PSOutput) { string[] result = item.ToString().Split(';'); var name = result[0].Substring(14); var path = result[1].Substring(11).Replace("}", string.Empty); if (name.Contains(".exe") /* && path != ""*/) { programs.Add(name, path); Word data = new Word(); Mean mean = new Mean(); data.word = name.Replace(".exe", string.Empty).ToLower(); mean.type = "target"; data.list = new List <Mean>(); mean.list = new List <string>(); mean.list.Add(name.Replace(".exe", string.Empty).ToLower()); data.list.Add(mean); Word.Write(); } } } }
public void RunCommandWithArguments(string commandName, IEnumerable <string> arguments, Action <Collection <PSObject> > processComandResult) { using (PowerShell powershell = PowerShell.Create()) { powershell.AddCommand(commandName); foreach (var parameter in arguments) { powershell.AddArgument(parameter); } Collection <PSObject> results = powershell.Invoke(); processComandResult?.Invoke(results); } }
/// <summary> /// Adds a reference in the Windows Defender Firewall for both /// incoming and outgoing connections for a specific program (executable) /// </summary> /// <param name="filePath"></param> /// <param name="result"></param> /// <returns>true: on successful execution of the batch script</returns> private bool blockFirewall(string filePath, ref string outRes) { try { using (Runspace myRunSpace = RunspaceFactory.CreateRunspace()) { myRunSpace.Open(); using (PowerShell powershell = PowerShell.Create()) { // add the command to run the bat file powershell.AddCommand(".\\" + BATCHFILENAME); powershell.AddArgument(filePath); // first argument: file path for the file which is to be blocked powershell.AddArgument(Path.GetFileName(filePath)); // second argument: filename of the file which is to be blocked // execute the script var results = powershell.Invoke(); powershell.Streams.ClearStreams(); powershell.Commands.Clear(); // convert the script result into a single string StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < results.Count() - 1; i++) // -1 to omit the final line as it is garbage { stringBuilder.AppendLine(results[i].ToString()); } outRes = stringBuilder.ToString(); return(true); } } } catch (Exception e) { outRes = e.Message; return(false); } }
private void GetIPAddress(VagrantVM vm) { try { Collection <PSObject> PSOutput; using (PowerShell ps = PowerShell.Create()) { ps.AddCommand("vboxmanage"); ps.AddArgument("showvminfo"); ps.AddArgument(vm.vbname); ps.AddCommand("select-string"); ps.AddParameter("pattern", "Bridged"); PSOutput = ps.Invoke(); string output = PSOutput[0].ToString(); int mac = output.IndexOf("MAC"); string m = output.Substring(mac + 5, 12); ps.Commands.Clear(); ps.AddCommand("vboxmanage"); ps.AddArgument("guestproperty"); ps.AddArgument("enumerate"); ps.AddArgument(vm.vbname); ps.AddCommand("select-string"); ps.AddParameter("pattern", m); PSOutput = ps.Invoke(); string s = (PSOutput[0].ToString().Split('/'))[4]; ps.Commands.Clear(); ps.AddCommand("vboxmanage"); ps.AddArgument("guestproperty"); ps.AddArgument("get"); ps.AddArgument(vm.vbname); ps.AddArgument(String.Format(@"/VirtualBox/GuestInfo/Net/{0}/V4/IP", s)); PSOutput = ps.Invoke(); s = PSOutput[0].ToString().Replace("Value: ", ""); vm.task.IPAddress = s; log(String.Format("VM Ip address is {0}", vm.task.IPAddress)); } } catch (Exception ex) {; } }
/// <summary> /// Return the last output to the user. This will be null if the operation did not succeed. /// outputAction is the action that will be performed whenever an object is outputted to the powershell pipeline /// </summary> /// <typeparam name="T"></typeparam> /// <param name="powershell"></param> /// <param name="command"></param> /// <param name="outputAction"></param> /// <param name="errorAction"></param> /// <param name="args"></param> /// <returns></returns> internal static T InvokeFunction <T>(this PowerShell powershell, string command, EventHandler <DataAddedEventArgs> outputAction, EventHandler <DataAddedEventArgs> errorAction, params object[] args) { if (powershell != null) { powershell.Clear().AddCommand(command); foreach (var arg in args) { powershell.AddArgument(arg); } #if DEBUG NativeMethods.OutputDebugString("[Cmdlet:debugging] -- InvokeFunction ({0}, {1})".format(command, args.Select(each => (each ?? "<NULL>").ToString()).JoinWithComma(), powershell.InvocationStateInfo.Reason)); #endif var input = new PSDataCollection <PSObject>(); input.Complete(); var output = new PSDataCollection <PSObject>(); if (outputAction != null) { output.DataAdded += outputAction; } if (errorAction != null) { powershell.Streams.Error.DataAdded += errorAction; } powershell.Invoke(null, output, new PSInvocationSettings()); if (output.Count == 0) { return(default(T)); } // return the last output to the user PSObject last = output.Last(); if (last != null) { // convert last to T return((T)last.ImmediateBaseObject); } } return(default(T)); }
/// <summary> /// Gets the CommandInfo instance for a command with a particular name. /// </summary> /// <param name="commandName">The name of the command.</param> /// <param name="runspace">The Runspace to use for running Get-Command.</param> /// <returns>A CommandInfo object with details about the specified command.</returns> public static CommandInfo GetCommandInfo( string commandName, Runspace runspace) { CommandInfo commandInfo = null; using (PowerShell powerShell = PowerShell.Create()) { powerShell.Runspace = runspace; powerShell.AddCommand("Get-Command"); powerShell.AddArgument(commandName); commandInfo = powerShell.Invoke <CommandInfo>().FirstOrDefault(); } return(commandInfo); }
internal static IEnumerable <T> InvokeFunction <T>(this PowerShell powershell, string command, params object[] args) { if (powershell != null) { powershell.Clear().AddCommand(command); foreach (var arg in args) { powershell.AddArgument(arg); } #if DEBUG PackageManagement.Utility.Platform.NativeMethods.OutputDebugString("[Cmdlet:debugging] -- InvokeFunction ({0}, {1})".format(command, args.Select(each => (each ?? "<NULL>").ToString()).JoinWithComma(), powershell.InvocationStateInfo.Reason)); #endif return((powershell.EndInvoke(powershell.BeginInvoke()) ?? Enumerable.Empty <PSObject>()).Select(each => each.ImmediateBaseObject).Cast <T>()); } return(Enumerable.Empty <T>()); }
public void TM1_0_NewLoginTest() { PowerShell ps = PowerShell.Create(); ps.AddCommand("Add-PSSnapIn"); ps.AddArgument("ShareFile"); Collection <PSObject> psObjects = ps.Invoke(); ps.Commands.Clear(); ps.AddCommand("New-SFClient"); ps.AddParameter("Name", Utils.LoginFilePath); psObjects = ps.Invoke(); Assert.AreEqual <int>(1, psObjects.Count); }
// https://stackoverflow.com/questions/31626244/retrieving-the-com-class-factory-for-component-with-clsid-688eeee5-6a7e-422f-b2 private bool InvokeCommand(string command) { PowerShell ps = PowerShell.Create(); ps.AddCommand(command); // ps.AddArgument("QBitNinja"); ps.AddArgument("W3SVC"); var result = ps.Invoke(); if (ps.Streams.Error.Count > 0) { return(false); } else { return(true); } }
private void btnDisable_Click(object sender, EventArgs e) { PowerShell ps = PowerShell.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); ps.Runspace = runspace; ps.AddCommand("Invoke-Expression"); //ps.AddArgument("netsh interface set interface \"Local Area Connection\" admin=enable"); ps.AddArgument("netsh interface set interface \"Ethernet\" admin=disable"); // ps.AddArgument("netsh interface ipv4 show interfaces"); // if you need the result save it in a psobject Collection <PSObject> result = ps.Invoke(); runspace.Close(); }
static void Main(string[] args) { PowerShell ps = PowerShell.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); ps.Runspace = runspace; ps.AddCommand("Invoke-Expression"); //ps.AddArgument("netsh interface set interface \"Local Area Connection\" admin=enable"); //ps.AddArgument("set address name= \"Local Area Connection\" source=static addr=192.168.19.235 mask=255.255.240.0 gateway=192.168.19.238"); ps.AddArgument("netsh interface ipv4 show interfaces"); // if you need the result save it in a psobject Collection <PSObject> result = ps.Invoke(); runspace.Close(); }
protected Collection <T> ThreadSafeInvoke <T>(string cmd, params object[] args) { // TODO: It doesn't look like a PowerShell instance is thread-safe // so we're going to have to design this to either do a lot of locking // around PS invocations which won't scale too well or setup a mechanism // to support pooling of PS contexts _poshLock.WaitOne(); try { _posh.Commands.Clear(); _posh.AddCommand(cmd); foreach (var a in args) { _posh.AddArgument(a); } var result = _posh.Invoke <T>(EMPTY_INPUT); if (Logger.IsEnabled(LogLevel.Trace)) { Logger.LogTrace($"ThreadSafeInvoke({cmd}) >>>>>>>>>>>>"); if (result == null || result.Count == 0) { Logger.LogTrace(" (NULL/EMPTY result)"); } else { foreach (var r in result) { Logger.LogTrace(" >> {resultItem}", r); } } } return(result); } finally { _poshLock.ReleaseMutex(); } }
private void btnSetAdapter_Click(object sender, EventArgs e) { PowerShell ps = PowerShell.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); ps.Runspace = runspace; ps.AddCommand("Invoke-Expression"); //ps.AddArgument("netsh interface set interface \"Local Area Connection\" admin=enable"); // ps.AddArgument("netsh interface ipv4 set address \"Ethernet\" static 192.168.19.234 255.255.240.0 192.168.19.238 1"); ps.AddArgument("netsh interface ipv4 set address \"Ethernet\" static " + txtIP.Text + " " + txtSubnet.Text + " " + txtGateway.Text + " 1"); // ps.AddArgument("netsh interface ipv4 show interfaces"); // if you need the result save it in a psobject Collection <PSObject> result = ps.Invoke(); runspace.Close(); }
// Private methods private void RunScript() { _ps.Commands.Clear(); _ps.AddScript(_sb.ToString()); if (_argumentList != null) { foreach (var arg in _argumentList) { _ps.AddArgument(arg); } } // Using variables if (_usingValuesMap != null && _usingValuesMap.Count > 0) { _ps.AddParameter(VERBATIM_ARGUMENT, _usingValuesMap); } _ps.BeginInvoke <object, PSObject>(_input, _output); }
public Uid Create(ObjectClass objClass, ICollection <ConnectorAttribute> attrs, OperationOptions options) { StringBuilder sb = new StringBuilder(); ConnectorAttribute NameAttribute = ConnectorAttributeUtil.Find(Name.NAME, attrs); if (NameAttribute == null) { throw new ConnectorException("The name operational attribute cannot be null"); } string parameter = ConnectorAttributeUtil.GetAsStringValue(NameAttribute); string[] login = parameter.Split('@'); PowerShell PowerShellInstance = PowerShell.Create(); PowerShellInstance.AddCommand(this.config.createScript + "create.ps1"); PowerShellInstance.AddArgument(login[0]); Collection <PSObject> results; Collection <ErrorRecord> errors; results = PowerShellInstance.Invoke(); errors = PowerShellInstance.Streams.Error.ReadAll(); if (errors.Count > 0) { foreach (ErrorRecord error in errors) { sb.AppendLine(error.ToString()); } throw new ConnectorException(sb.ToString()); } else { return(new Uid(ConnectorAttributeUtil.GetAsStringValue(NameAttribute))); } }
/// <summary> /// Gets the command's "Synopsis" documentation section. /// </summary> /// <param name="commandInfo">The CommandInfo instance for the command.</param> /// <param name="runspace">The Runspace to use for getting command documentation.</param> /// <returns></returns> public static string GetCommandSynopsis( CommandInfo commandInfo, Runspace runspace) { string synopsisString = string.Empty; PSObject helpObject = null; if (commandInfo != null && (commandInfo.CommandType == CommandTypes.Cmdlet || commandInfo.CommandType == CommandTypes.Function || commandInfo.CommandType == CommandTypes.Filter)) { using (PowerShell powerShell = PowerShell.Create()) { powerShell.Runspace = runspace; powerShell.AddCommand("Get-Help"); powerShell.AddArgument(commandInfo); helpObject = powerShell.Invoke <PSObject>().FirstOrDefault(); } if (helpObject != null) { // Extract the synopsis string from the object synopsisString = (string)helpObject.Properties["synopsis"].Value ?? string.Empty; // Ignore the placeholder value for this field if (string.Equals(synopsisString, "SHORT DESCRIPTION", System.StringComparison.InvariantCultureIgnoreCase)) { synopsisString = string.Empty; } } } return(synopsisString); }
static void Main(string[] args) { PowerShell ps = PowerShell.Create(); ps.AddCommand("Restart-Computer"); ps.AddArgument("Computer"); ps.AddScript("Get-Content C:\\machineslist.txt"); SecureString secureString = new NetworkCredential("", "Password").SecurePassword; PSCredential psc = new PSCredential("Administrator", secureString); ps.AddParameter("Credential", psc); ps.AddParameter("Force"); var results = ps.Invoke(); foreach (var error in ps.Streams.Error) { Console.WriteLine(error); } foreach (PSObject result in results) { //Console.WriteLine("{0,-24}{1}", result.Members["Length"].Value, result.Members["Name"].Value); } }
private void btnShowNICS_Click(object sender, EventArgs e) { PowerShell ps = PowerShell.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); ps.Runspace = runspace; ps.AddCommand("Invoke-Expression"); //ps.AddArgument("netsh interface set interface \"Local Area Connection\" admin=enable"); //ps.AddArgument("set address name= \"Local Area Connection\" source=static addr=192.168.19.235 mask=255.255.240.0 gateway=192.168.19.238"); ps.AddArgument("netsh interface ipv4 show interfaces"); // if you need the result save it in a psobject Collection <PSObject> result = ps.Invoke(); runspace.Close(); foreach (PSObject obj in result) { lstSystemMessage.Items.Add(obj.BaseObject); } }
public Uid Update(ObjectClass objclass, Uid uid, ICollection <ConnectorAttribute> replaceAttributes, OperationOptions options) { StringBuilder sb = new StringBuilder(); PowerShell PowerShellInstance = PowerShell.Create(); ConnectorAttribute StatusAttribute = ConnectorAttributeUtil.Find(OperationalAttributes.ENABLE_NAME, replaceAttributes); String enable = ConnectorAttributeUtil.GetAsStringValue(StatusAttribute).ToLower(); string parameter = ConnectorAttributeUtil.GetAsStringValue(uid); string[] login = parameter.Split('@'); if (enable.Equals("false")) { PowerShellInstance.AddCommand(this.config.createScript + "disable.ps1"); PowerShellInstance.AddArgument(login[0]); Collection <PSObject> results; Collection <ErrorRecord> errors; results = PowerShellInstance.Invoke(); errors = PowerShellInstance.Streams.Error.ReadAll(); if (errors.Count > 0) { foreach (ErrorRecord error in errors) { sb.AppendLine(error.ToString()); } throw new ConnectorException(sb.ToString()); } else { return(uid); } } else if (enable.Equals("true")) { PowerShellInstance.AddCommand(this.config.createScript + "enable.ps1"); PowerShellInstance.AddArgument(login[0]); Collection <PSObject> results; Collection <ErrorRecord> errors; results = PowerShellInstance.Invoke(); errors = PowerShellInstance.Streams.Error.ReadAll(); if (errors.Count > 0) { foreach (ErrorRecord error in errors) { sb.AppendLine(error.ToString()); } throw new ConnectorException(sb.ToString()); } else { return(uid); } } else { return(uid); } }
public void AddArgument(String Arg) { ps.AddArgument(Arg); }
private void AttachPipeline(PowerShell ps) { foreach (string cmd in pipeLine) { if (cmd.Length > 0 && cmd[0] == '$') { ps.AddScript(cmd); } else { string[] cmdOpts = cmd.Split(' '); string cmdName = cmdOpts[0]; ps.AddCommand(cmdName); string opts = string.Empty; bool skip = false; for (int i = 1; i < cmdOpts.Length; i++) { if (skip) { skip = false; continue; } if (cmdOpts[i].IndexOf("-") != 0) { ps.AddArgument(cmdOpts[i]); } else { if (i + 1 < cmdOpts.Length && cmdOpts[i + 1].IndexOf("-") != 0) { ps.AddParameter(cmdOpts[i].Substring(1), cmdOpts[i + 1]); skip = true; } else { ps.AddParameter(cmdOpts[i].Substring(1)); skip = false; } } } //add storage context for azure storage cmdlet //It make sure all the storage cmdlet in pipeline use the same storage context if (cmdName.ToLower().IndexOf("-azurestorage") != -1) { AddCommonParameters(ps); } } } }
public static ActionResult ExecPowershell(Session session, string scriptName, string functionName = "") { //System.Diagnostics.Debugger.Launch(); PowerShell powerShell = PowerShell.Create(); //disable powershell restrictions for the CA session SetProcessExecution(session, "Unrestricted"); Log(session, string.Format("Start Exec Powershell script {0}, function {1}", scriptName, functionName)); string include = string.Format(". \".\\{0}\"", scriptName); string param = "Param([Microsoft.Deployment.WindowsInstaller.Session]$session)"; string callFunc = string.Format("{0}($session)", functionName); string loadInterop = String.Format("$msi = Add-Type -AssemblyName \"Microsoft.Deployment.WindowsInstaller\" -PassThru"); //if no function name specified, create a small script to bootstrap the script to be executed and pass the $session string scriptPath = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), scriptName); string scriptbody = string.Empty; if (functionName == string.Empty) { scriptbody += new StreamReader(scriptPath).ReadToEnd(); powerShell.AddScript(scriptbody); powerShell.AddArgument(session); } else { scriptbody += param + Environment.NewLine; scriptbody += include + Environment.NewLine; //scriptbody += loadInterop + Environment.NewLine; scriptbody += callFunc + Environment.NewLine; powerShell.AddScript(scriptbody); powerShell.AddArgument(session); } try { System.Collections.ObjectModel.Collection <PSObject> results = powerShell.Invoke(); foreach (InformationRecord rec in powerShell.Streams.Information.ReadAll()) { Log(session, rec.MessageData.ToString()); } if (powerShell.Streams.Error.Count > 0) { Log(session, string.Format("Script Failed with {0} errors", powerShell.Streams.Error.Count)); foreach (ErrorRecord rec in powerShell.Streams.Error.ReadAll()) { Log(session, rec.Exception.Message); Log(session, rec.ScriptStackTrace); Log(session, rec.ToString()); } return(ActionResult.Failure); } } catch (Exception ex) { Log(session, "Powershell Execution failed!"); Log(session, ex.Message); Log(session, ex.StackTrace); } return(ActionResult.Success); }
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member public PSInvocationResult(string script, IPSInvocationContext context, PowerShell powerShell, object[] variableKeys, params object[] arguments) #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member { ErrorRecord error = null; try { if (context.UseLocalScope.HasValue) { powerShell.AddScript(script, context.UseLocalScope.Value); } else { powerShell.AddScript(script); } if (arguments != null && arguments.Length > 0) { foreach (object a in arguments) { powerShell.AddArgument(a); } } _output = powerShell.Invoke(); #if !PSLEGACY _hadErrors = powerShell.HadErrors; #endif _ranToCompletion = true; } catch (RuntimeException exception) { error = exception.ErrorRecord; _hadErrors = true; } catch (ArgumentException exception) { error = new ErrorRecord(exception, "UnexpectedInvalidArgument", ErrorCategory.InvalidArgument, script); _hadErrors = true; } catch (Exception exception) { error = new ErrorRecord(exception, "UnexpectedError", ErrorCategory.NotSpecified, script); _hadErrors = true; } _errors = powerShell.Streams.Error.ReadAll(); if (error != null) { _errors.Add(error); } #if PSLEGACY if (_errors.Count > 0) { _hadErrors = true; } #endif _warnings = powerShell.Streams.Warning.ReadAll(); _verbose = powerShell.Streams.Verbose.ReadAll(); _debug = powerShell.Streams.Debug.ReadAll(); if (_output == null) { _output = new Collection <PSObject>(); } _variables = new Hashtable(); foreach (object key in variableKeys) { _variables[key] = powerShell.Runspace.SessionStateProxy.GetVariable((key is string) ? key as string : key.ToString()); } }
public static DscBreakpointCapability CheckForCapability( RunspaceDetails runspaceDetails, PowerShellContextService powerShellContext, ILogger logger) { DscBreakpointCapability capability = null; // DSC support is enabled only for Windows PowerShell. if ((runspaceDetails.PowerShellVersion.Version.Major < 6) && (runspaceDetails.Context != RunspaceContext.DebuggedRunspace)) { using (PowerShell powerShell = PowerShell.Create()) { powerShell.Runspace = runspaceDetails.Runspace; // Attempt to import the updated DSC module powerShell.AddCommand("Import-Module"); powerShell.AddArgument(@"C:\Program Files\DesiredStateConfiguration\1.0.0.0\Modules\PSDesiredStateConfiguration\PSDesiredStateConfiguration.psd1"); powerShell.AddParameter("PassThru"); powerShell.AddParameter("ErrorAction", "Ignore"); PSObject moduleInfo = null; try { moduleInfo = powerShell.Invoke().FirstOrDefault(); } catch (RuntimeException e) { logger.LogException("Could not load the DSC module!", e); } if (moduleInfo != null) { logger.LogTrace("Side-by-side DSC module found, gathering DSC resource paths..."); // The module was loaded, add the breakpoint capability capability = new DscBreakpointCapability(); runspaceDetails.AddCapability(capability); powerShell.Commands.Clear(); powerShell .AddCommand("Microsoft.PowerShell.Utility\\Write-Host") .AddArgument("Gathering DSC resource paths, this may take a while...") .Invoke(); // Get the list of DSC resource paths powerShell.Commands.Clear(); powerShell .AddCommand("Get-DscResource") .AddCommand("Select-Object") .AddParameter("ExpandProperty", "ParentPath"); Collection <PSObject> resourcePaths = null; try { resourcePaths = powerShell.Invoke(); } catch (CmdletInvocationException e) { logger.LogException("Get-DscResource failed!", e); } if (resourcePaths != null) { capability.dscResourceRootPaths = resourcePaths .Select(o => (string)o.BaseObject) .ToArray(); logger.LogTrace($"DSC resources found: {resourcePaths.Count}"); } else { logger.LogTrace($"No DSC resources found."); } } else { logger.LogTrace($"Side-by-side DSC module was not found."); } } } return(capability); }
private async Task<bool> RunScript(string path) { PowerShellInstance = PowerShell.Create(); PowerShellInstance.AddScript(LoadScript(path)); PowerShellInstance.AddArgument(CredentialHelper.GetFormRegistery(CredentialHelper.SourceRepoUserName)); PowerShellInstance.AddArgument(CredentialHelper.GetFormRegistery(CredentialHelper.SourceRepoPassword)); PowerShellInstance.AddArgument(CredentialHelper.GetFormRegistery(CredentialHelper.TargetRepoUserName)); PowerShellInstance.AddArgument(CredentialHelper.GetFormRegistery(CredentialHelper.TargetRepoPassword)); PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>(); outputCollection.DataAdded += outputCollection_DataAdded; PowerShellInstance.Streams.Error.DataAdded += Error_DataAdded; IAsyncResult result = PowerShellInstance.BeginInvoke<PSObject,PSObject>(null, outputCollection); while (result.IsCompleted == false) { await Task.Delay(100); } return PowerShellInstance.HadErrors; }
/// <summary> /// Runs the PowerShell script. /// </summary> /// <param name="script">The script.</param> /// <param name="scriptArguments">The PowerShell script arguments.</param> /// <param name="scriptParameters">The PowerShell script parameters.</param> /// <returns>The output of the script.</returns> private object RunScript(string script, IEnumerable scriptArguments, Dictionary <string, object> scriptParameters) { Logger.Instance.WriteMethodEntry(EventIdentifier.RunPowerShellScriptRunScript); WindowsImpersonationContext context = null; LogOnUser logOnUser = null; try { PSCredential credential = this.GetPowerShellCredential(); logOnUser = this.LogOnUser(credential); if (logOnUser != null) { context = logOnUser.Impersonate(); } // Establish a new runspace for the Powershell script InitialSessionState initialSessionState = InitialSessionState.CreateDefault(); bool progressPreference = Logger.Instance.ShouldTrace(TraceEventType.Information); bool debugPreference = Logger.Instance.ShouldTrace(TraceEventType.Information); bool verbosePreference = Logger.Instance.ShouldTrace(TraceEventType.Verbose); initialSessionState.Variables.Add(new SessionStateVariableEntry("ProgressPreference", progressPreference ? "Continue" : "SilentlyContinue", string.Empty)); initialSessionState.Variables.Add(new SessionStateVariableEntry("DebugPreference", debugPreference ? "Continue" : "SilentlyContinue", string.Empty)); initialSessionState.Variables.Add(new SessionStateVariableEntry("VerbosePreference", verbosePreference ? "Continue" : "SilentlyContinue", string.Empty)); initialSessionState.Variables.Add(new SessionStateVariableEntry("AECWorkflowInstanceId", Logger.GetContextItem("WorkflowInstanceId"), string.Empty)); initialSessionState.Variables.Add(new SessionStateVariableEntry("AECRequestId", Logger.GetContextItem("RequestId"), string.Empty)); initialSessionState.Variables.Add(new SessionStateVariableEntry("AECActorId", Logger.GetContextItem("ActorId"), string.Empty)); initialSessionState.Variables.Add(new SessionStateVariableEntry("AECTargetId", Logger.GetContextItem("TargetId"), string.Empty)); initialSessionState.Variables.Add(new SessionStateVariableEntry("AECWorkflowDefinitionId", Logger.GetContextItem("WorkflowDefinitionId"), string.Empty)); initialSessionState.Variables.Add(new SessionStateVariableEntry("Credential", credential, null)); using (Runspace runspace = RunspaceFactory.CreateRunspace(initialSessionState)) { runspace.Open(); using (PowerShell shell = PowerShell.Create()) { shell.Runspace = runspace; SetupStreamEventHandlers(shell); // Add the script to the PowerShell instance to prepare for execution shell.AddScript(script); StringBuilder scriptParams = new StringBuilder(); if (scriptParameters != null) { foreach (string s in scriptParameters.Keys) { shell.AddParameter(s, scriptParameters[s]); scriptParams.AppendFormat(CultureInfo.InvariantCulture, "-{0} '{1}' ", s, scriptParameters[s]); } } else if (scriptArguments != null) { foreach (object o in scriptArguments) { shell.AddArgument(o); scriptParams.AppendFormat(CultureInfo.InvariantCulture, "'{0}' ", o); } } if (this.InputType != PowerShellInputType.None) { Logger.Instance.WriteVerbose(EventIdentifier.RunPowerShellScriptRunScript, "The PowerShell script parameters are: '{0}'.", scriptParams); } // Execute the script and identify if any errors occurred // In most circumstances, errors will not be raised as exceptions but will instead // be presented in the Error collection for the PowerShell instance Collection <PSObject> results; try { results = shell.Invoke(); } catch (Exception ex) { throw Logger.Instance.ReportError(EventIdentifier.RunPowerShellScriptRunScriptInvocationError, new WorkflowActivityLibraryException(Messages.RunPowerShellScript_ScriptInvocationError, ex, ex.Message)); } if (shell.Streams.Error.Count == 0) { if (this.ReturnType == PowerShellReturnType.None) { return(null); } if (results != null && results.Count == 1) { return(results[0].BaseObject); } if (results == null || results.Count < 1) { return(null); } // If multiple values were found for the lookup, verify that they are of a consistent type Type type = null; bool consistentType = true; foreach (PSObject pso in results) { if (type == null) { type = pso.BaseObject.GetType(); Logger.Instance.WriteVerbose(EventIdentifier.RunPowerShellScriptRunScript, "The PowerShell script returned type: '{0}'.", type); } else if (pso.BaseObject.GetType() != type) { consistentType = false; Logger.Instance.WriteError(EventIdentifier.RunPowerShellScriptRunScriptInconsistentScriptReturnTypeError, Messages.RunPowerShellScript_InconsistentScriptReturnTypeError, pso.BaseObject.GetType(), type); } } // If we have multiple values of an inconsistent type, there is a problem // which needs to be addressed by the administrator if (!consistentType) { throw Logger.Instance.ReportError(EventIdentifier.RunPowerShellScriptRunScriptInconsistentScriptReturnTypeError, new WorkflowActivityLibraryException(Messages.RunPowerShellScript_InvalidReturnTypeError)); } // Because we have multiple values returned for the PowerShell script, // we want to return them in the form of a strongly-typed list // For example: List<string> instead of List<object> // Use reflection to create a new strongly-typed list Type listType = typeof(List <>).MakeGenericType(new Type[] { type }); var typedList = Activator.CreateInstance(listType); // Using reflection, fetch the add method for the new list // and invoke it to add each value from the original PSobject collection to the new collection // Return the strongly-typed list MethodInfo add = listType.GetMethod("Add"); foreach (PSObject pso in results) { add.Invoke(typedList, new object[] { pso.BaseObject }); } return(typedList); } StringBuilder message = new StringBuilder(); message.AppendFormat(Messages.RunPowerShellScript_ScriptExecutionFailedError, shell.Streams.Error.Count); foreach (ErrorRecord error in shell.Streams.Error) { message.AppendFormat("{0}\n", error); } throw Logger.Instance.ReportError(EventIdentifier.RunPowerShellScriptRunScriptExecutionFailedError, new WorkflowActivityLibraryException(message.ToString())); } } } catch (Exception ex) { throw Logger.Instance.ReportError(EventIdentifier.RunPowerShellScriptRunScriptExecutionFailedError, ex); } finally { if (context != null) { context.Undo(); } if (logOnUser != null) { logOnUser.Dispose(); } Logger.Instance.WriteMethodExit(EventIdentifier.RunPowerShellScriptRunScript); } }
protected void InitPowerShell() { Logger.LogInformation("***********************************************"); Logger.LogInformation("Constructing PowerShell execution context"); _posh = PowerShell.Create(); // Need to create our own runspace so we can pass in our own custom PSHost // which ties the PowerShell context to our custom handler environment _posh.Runspace = RunspaceFactory.CreateRunspace(new Ps5CustomHost(Logger, name: "PS5Host")); _posh.Runspace.Open(); // Register some context-supporting variables in scope _posh.AddCommand("Microsoft.PowerShell.Utility\\Set-Variable"); _posh.AddParameter("Name", PS_VAR_HANDLER_LOGGER); _posh.AddParameter("Option", "ReadOnly"); _posh.AddParameter("Description", "ILogger to be used by handler cmdlet"); _posh.AddParameter("Value", new PsLogger(Logger)); _posh.Invoke(); _posh.Commands.Clear(); // Register some context-supporting variables in scope _posh.AddCommand("Microsoft.PowerShell.Utility\\Set-Variable"); _posh.AddParameter("Name", PS_VAR_HANDLER_APP_CONFIGURATION); _posh.AddParameter("Option", "ReadOnly"); _posh.AddParameter("Description", "App-wide configuration (read-only)"); _posh.AddParameter("Value", new ReadOnlyConfiguration(AppConfig)); _posh.Invoke(); _posh.Commands.Clear(); // Set the CWD for the PowerShell cmdlets to run from _posh.AddCommand("Microsoft.PowerShell.Management\\Set-Location"); _posh.AddArgument(_bootstrapFullpath); var result = _posh.Invoke(); _posh.Commands.Clear(); Logger.LogInformation("Relocated PWD for current execution context >>>>>>>>>>>>>>"); foreach (var r in result) { Logger.LogWarning(">> " + r.ToString()); } // If a bootstrap script was provided in the app settings // let's invoke it and capture the results for diagnostics if (BootstrapScript != null && BootstrapScript.Count() > 0) { Logger.LogInformation("Bootstrap Script found"); Logger.LogDebug("--8<---------------------------------"); foreach (var s in BootstrapScript) { Logger.LogDebug(s); _posh.AddScript(s); } Logger.LogDebug("--------------------------------->8--"); result = _posh.Invoke(); _posh.Commands.Clear(); Logger.LogInformation("Bootstrap Script executed"); Logger.LogDebug("--8<---------------------------------"); foreach (var r in result) { Logger.LogDebug(">> " + r.ToString()); } Logger.LogDebug("--------------------------------->8--"); } }