public static Collection <PSObject> ExecutePS(this string script) { return(PowerShellInstance .AddScript(script) .AddCommand("Out-String") .Invoke()); }
private void FormShowService_Load(object sender, EventArgs e) { PowerShellInstance = PowerShell.Create(); //string script = "get-service -name dhcp"; inputname = "dnscache"; string gwmi_win32_service = "gwmi win32_Service"; string nameservice = "Where-Object {$_.name -eq " + "\"" + inputname + "\"}"; //string selectpathname = "select pathname"; string scriptget = gwmi_win32_service + "|" + nameservice; //string script = "gwmi win32_Service | Where-Object {$_.name -eq \"dhcp\"}"; // this script has a sleep in it to simulate a long running script PowerShellInstance.AddScript(scriptget); //PowerShellInstance.AddParameter("param1", "dhcp"); // begin invoke execution on the pipeline //IAsyncResult result = PowerShellInstance.BeginInvoke(); PSOutput = PowerShellInstance.Invoke(); labelServicename_value.Text = PSOutput[0].Members["Name"].Value.ToString().ToUpper(); labelDisplayname_value.Text = PSOutput[0].Members["DisplayName"].Value.ToString().ToUpper(); labelServicePath_value.Text = PSOutput[0].Members["Pathname"].Value.ToString(); labelService_status_value.Text = PSOutput[0].Members["state"].Value.ToString(); comboBoxSV_Startup_type_value.Items.Add(PSOutput[0].Members["StartMode"].Value.ToString()); comboBoxSV_Startup_type_value.SelectedItem = PSOutput[0].Members["StartMode"].Value.ToString(); }
PowerShellInstance createInstance( IShellUI ui, string remoteComputerName) { var instance = new PowerShellInstance(ui, remoteComputerName); instance.ExecDone += onExecDone; instance.ExitRequested += onExitRequested; return instance; }
public static void ExecuteScriptEntryPoint(this string scriptEntryPoint, object argument = null) { foreach (var file in GetScriptsToRun(scriptEntryPoint)) { var results = PowerShellInstance .AddCommand(file) .AddParameter("stuff", argument) .AddCommand("Out-String") .Invoke(); foreach (var item in results) { Debug.WriteLine(item); } } }
protected virtual void Dispose(bool disposing) { if (disposing) { if (_runspace != null) { _runspace.Close(); _runspace.Dispose(); } if (PowerShellInstance != null) { PowerShellInstance.Dispose(); } PowerShellInstance = null; } }
private void buttonSV_Start_Click(object sender, EventArgs e) { inputname = "dnscache"; string gwmi_win32_service = "gwmi win32_Service"; string nameservice = "Where-Object {$_.name -eq " + "\"" + inputname + "\"}"; //string selectpathname = "select pathname"; string scriptget = gwmi_win32_service + "|" + nameservice; PowerShellInstance.AddScript("$a = " + scriptget); PSOutput = PowerShellInstance.Invoke(); PowerShellInstance.AddScript("$a.StartService()"); PSOutput = PowerShellInstance.Invoke(); PowerShellInstance.AddScript("$a.State"); PSOutput = PowerShellInstance.Invoke(); int countcheck = 0; while (PSOutput[0].ToString() != "Running") { PowerShellInstance.AddScript("$a.State"); PSOutput = PowerShellInstance.Invoke(); countcheck++; Thread.Sleep(500); if (countcheck > 15 || PSOutput[0].ToString() == "Running") { break; } } labelService_status_value.Text = PSOutput[0].ToString(); MessageBox.Show("Service " + inputname + " đã mở!", "Thông báo", MessageBoxButtons.OK); }
private void InitializeRoot() { // Module.Type Match match = ModuleAndTypeRegex.Match(_rootInfo); if (!match.Success) { // Handling a case like: myModule#Test\FamilyTree#Austin match = TryExcludeFQProviderPath(_rootInfo); if (match == null) { _provider.ThrowError(Resources.Resource.InvalidRootFormat.StringFormat(_rootInfo), ErrorId.InvalidRootFormat); return; } } //first we need to make sure the module is loaded var moduleCommand = "import-module {0}; get-module {0} -verbose".StringFormat(match.Groups[1], match.Groups[1]); _provider.WriteVerbose(moduleCommand); //get the module var module = _provider.SessionState.InvokeCommand.InvokeScript(moduleCommand, null).FirstOrDefault(); if (module == null || !(module.BaseObject is PSModuleInfo)) { // The reason that not using _provider.WriteError() here is because it is not terminatoring process // at this time, mearning the drive is actually gets created but not usable. //_provider.WriteError() _provider.ThrowError(Resources.Resource.CannotGetModule.StringFormat(match.Groups[1]), ErrorId.CannotGetModule); return; } //create powershell instance and load the modules currently referenced var moduleBaseObj = (PSModuleInfo)module.BaseObject; var modulePath = Path.Combine((moduleBaseObj).ModuleBase, (moduleBaseObj).Name.TrimEnd() + ".psd1"); if (!File.Exists(modulePath)) { _provider.WriteWarning(Resources.Resource.FileNotExist.StringFormat(modulePath)); modulePath = moduleBaseObj.Path; _provider.WriteWarning(Resources.Resource.Trying.StringFormat(modulePath)); } _provider.WriteVerbose(modulePath); //create the instance of root module var createRootInstance = string.Format(CultureInfo.InvariantCulture, @"using module '{0}'; $mod=get-module {1}; &($mod){{[{2}]::new('{2}')}}", modulePath, match.Groups[1], match.Groups[2]); _provider.WriteVerbose(createRootInstance); //ifdef #newrunspace PowerShellInstance = CreatePowerShellObject(_provider.Host, modulePath); PowerShellInstance.AddScript(createRootInstance); var errors = new ConcurrentBag <ErrorRecord>(); var rootPsObject = PSScriptRunner.CallPowerShellScript(createRootInstance, PowerShellInstance, (sender, e) => PSScriptRunner.error_DataAdded(sender, e, errors)); //var rootPsObject = PowerShellInstance.Invoke().FirstOrDefault(); if (rootPsObject == null || !rootPsObject.Any()) { var message = Resources.Resource.CannotCreateInstance.StringFormat(match.Groups[2], modulePath, match.Groups[2], match.Groups[2]); if (errors.WhereNotNull().Any()) { var error = errors.FirstOrDefault(); message += Environment.NewLine; message += error.ErrorDetails == null ? error.Exception.Message : error.ErrorDetails.Message; } _provider.ThrowError(message, ErrorId.CannotCreateInstance); return; } var node = rootPsObject.FirstOrDefault().ToNode(); if (node == null) { _provider.ThrowError(Resources.Resource.InvalidRootNode, ErrorId.NotContainerNode); } if (string.IsNullOrWhiteSpace(node.Name)) { _provider.ThrowError(Resources.Resource.NameWithNullOrEmpty.StringFormat(string.IsNullOrWhiteSpace(node.Name) ? "root" : node.Name), ErrorId.NodeNameIsNullOrEmpty); } if (node.IsLeaf) { _provider.ThrowError(Resources.Resource.InvalidRootNodeType.StringFormat(Constants.Leaf), ErrorId.RootNodeTypeMustBeContainer); } RootNode = node; RootPathNode = new ContainerNodeService(this, node, null); // Getting the Get-ChildItem default parameters before running any commands. It will be used for checking // whether a user is passing in any dynamic parameters. _getChildItemDefaultParameters = GetChildItemDefaultParameters; }