public void execToPowerShell(string[] server, string query, string ps1path) { try { //exec script RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); Pipeline pipeline = runspace.CreatePipeline(); Command myCommand = new Command(ps1path); CommandParameter a = new CommandParameter("server", server); CommandParameter b = new CommandParameter("query", query); myCommand.Parameters.Add(a); myCommand.Parameters.Add(b); pipeline.Commands.Add(myCommand); // Execute PowerShell script Collection <PSObject> results = pipeline.Invoke(); } catch (Exception ex) { MessageBox.Show("Error : " + ex.InnerException.Message); } }
/// <summary> /// トースト通知 /// </summary> /// <param name="text">通知する文字列</param> private static void ToastNotification(string text) { var code = new string[] { "$ErrorActionPreference = \"Stop\"", $"$notificationTitle = \"{text}\"", "[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null", "$template = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)", "$toastXml = [xml] $template.GetXml()", "$toastXml.GetElementsByTagName(\"text\").AppendChild($toastXml.CreateTextNode($notificationTitle)) > $null", "$xml = New-Object Windows.Data.Xml.Dom.XmlDocument", "$xml.LoadXml($toastXml.OuterXml)", "$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)", "$toast.Tag = \"PowerShell\"", "$toast.Group = \"PowerShell\"", "$toast.ExpirationTime = [DateTimeOffset]::Now.AddMinutes(5)", "$notifier = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier(\"PowerShell\")", "$notifier.Show($toast);" }; using (var invoker = new RunspaceInvoke()) { invoker.Invoke(string.Join("\n", code), new object[] { }); } }
public void execToPowerShell(string query, string ps1path) { try { //exec script RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); Pipeline pipeline = runspace.CreatePipeline(); Command myCommand = new Command(ps1path); //CommandParameter a = new CommandParameter("server", server); CommandParameter b = new CommandParameter("query", query); //myCommand.Parameters.Add(a); myCommand.Parameters.Add(b); pipeline.Commands.Add(myCommand); // Execute PowerShell script Collection <PSObject> results = pipeline.Invoke(); //foreach (PSObject s in results) //{ // //Process p = s.BaseObject as Process; // string e = s.Members["PercentComplete"].Value.ToString(); // MessageBox.Show(e); //} } catch (Exception ex) { MessageBox.Show("Error : " + ex.InnerException.Message); } }
private void ShowInfo() { try { var runspaceConfiguration = RunspaceConfiguration.Create(); using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration)) { runspace.Open(); using (var scriptInvoker = new RunspaceInvoke(runspace)) { scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted"); using (var pipeline = runspace.CreatePipeline()) { Command myCommand = new Command(@".\Command.ps1"); pipeline.Commands.Add(myCommand); var res = pipeline.Invoke(); this.notifyIcon1.BalloonTipText = res.Aggregate("", (c, n) => this.FormatOutput(c, n.BaseObject.ToString())); if (string.IsNullOrEmpty(this.notifyIcon1.BalloonTipText)) { this.notifyIcon1.BalloonTipText = "script returns no results"; } } } } } catch (Exception ex) { this.notifyIcon1.BalloonTipText = ex.ToString(); } this.notifyIcon1.ShowBalloonTip(500); }
private static void AdduserNotExpire(string fNm, string lNm, string uNm, string pWd, string gpUser) { RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); Pipeline pipeline = runspace.CreatePipeline(); string scriptfile = @"C:\temp\addusernotexpire.ps1"; Command myCommand = new Command(scriptfile); CommandParameter p1 = new CommandParameter("fname", fNm); CommandParameter p2 = new CommandParameter("lname", lNm); CommandParameter p3 = new CommandParameter("uname", uNm); CommandParameter p4 = new CommandParameter("pWd", pWd); CommandParameter p5 = new CommandParameter("grpUser", gpUser); myCommand.Parameters.Add(p1); myCommand.Parameters.Add(p2); myCommand.Parameters.Add(p3); myCommand.Parameters.Add(p4); myCommand.Parameters.Add(p5); pipeline.Commands.Add(myCommand); // invoke execution on the pipeline (ignore output) pipeline.Invoke(); }
public static void CreateFirewallRules() { // create Powershell runspace Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace); runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted"); // create a pipeline and feed it the script text Pipeline pipeline = runspace.CreatePipeline(); Command command = new Command(_scriptPath); //foreach (var file in filesToMerge) //{ // command.Parameters.Add(null, file); //} //command.Parameters.Add(null, outputFilename); pipeline.Commands.Add(command); pipeline.Invoke(); runspace.Close(); }
static void Main(string[] args) { StringBuilder sb = new StringBuilder(); try { Runspace rs = RunspaceFactory.CreateRunspace(); rs.Open(); RunspaceInvoke ri = new RunspaceInvoke(rs); Pipeline pipe = rs.CreatePipeline(); pipe.Commands.AddScript(args[0]); pipe.Commands.Add("Out-String"); Collection <PSObject> output = pipe.Invoke(); rs.Close(); foreach (PSObject line in output) { sb.AppendLine(line.ToString()); } Console.WriteLine(sb.ToString()); } catch (Exception e) { Console.WriteLine(e.Message); } }
/// <summary> /// 파워셀 - db 원격스크립트 수행 - 티베로 gisLoader, tbloader /// </summary> /// <param name="scriptfile"></param> private void ExPsScript(string scriptfile) { RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(); scriptInvoker.Invoke("Set-ExecutionPolicy RemoteSigned"); Pipeline pipeline = runspace.CreatePipeline(); //Here's how you add a new script with arguments Command myCommand = new Command(scriptfile); //CommandParameter testParam = new CommandParameter("key", "value"); //myCommand.Parameters.Add(testParam); pipeline.Commands.Add(myCommand); // Execute PowerShell script pipeline.Invoke(); }
public static Collection <PSObject> RunScript(string scriptfile, string pKey1 = "", string pValue1 = "") { var runspaceConfiguration = RunspaceConfiguration.Create(); var runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); runspace.Open(); var scriptInvoker = new RunspaceInvoke(runspace); var pipeline = runspace.CreatePipeline(); // Here's how you add a new script with arguments var rolePath = Environment.GetEnvironmentVariable("RoleRoot"); var path = Path.Combine(rolePath, "approot", "bin", "scripts"); var myCommand = new Command(Path.Combine(path, scriptfile)); if (!String.IsNullOrEmpty(pKey1)) { var testParam = new CommandParameter(pKey1, pValue1); myCommand.Parameters.Add(testParam); } pipeline.Commands.Add(myCommand); // Execute PowerShell script var results = pipeline.Invoke(); return(results); }
/// <summary> /// This sample uses the RunspaceInvoke class to execute /// a script that calls exit. The host application looks at /// this and prints out the result. /// </summary> /// <param name="args">Unused</param> static void Main(string[] args) { // Create an instance of this class so that the engine will have // access to the ShouldExit and ExitCode parameters. Host01 me = new Host01(); // Now create the host instance to use MyHost myHost = new MyHost(me); // Pass this in when creating the runspace and invoker... Runspace myRunSpace = RunspaceFactory.CreateRunspace(myHost); myRunSpace.Open(); RunspaceInvoke invoker = new RunspaceInvoke(myRunSpace); // Now use the runspace invoker to execute the script "exit (2+2)" string script = "exit (2+2)"; invoker.Invoke(script); // Check the flags and see if they were set propertly... Console.WriteLine( "ShouldExit={0} (should be True); ExitCode={1} (should be 4)", me.ShouldExit, me.ExitCode); // close the runspace... myRunSpace.Close(); Console.WriteLine("Hit any key to exit..."); Console.ReadKey(); }
public static string Exec() { RunspaceConfiguration rsconfig = RunspaceConfiguration.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(rsconfig); runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); Pipeline pipeline = runspace.CreatePipeline(); // our malicious command String cmd = "Start-Process notepad.exe"; pipeline.Commands.AddScript(cmd); // added for easier output pipeline.Commands.Add("Out-String"); Collection <PSObject> results = pipeline.Invoke(); runspace.Close(); // convert records to strings StringBuilder stringBuilder = new StringBuilder(); foreach (PSObject obj in results) { stringBuilder.Append(obj); } return(stringBuilder.ToString().Trim()); }
//Based on Jared Atkinson's And Justin Warner's Work public static string RunPSCommand(string cmd) { //Init stuff Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); Pipeline pipeline = runspace.CreatePipeline(); //Add commands pipeline.Commands.AddScript(cmd); //Prep PS for string output and invoke pipeline.Commands.Add("Out-String"); Collection <PSObject> results = pipeline.Invoke(); runspace.Close(); //Convert records to strings StringBuilder stringBuilder = new StringBuilder(); foreach (PSObject obj in results) { stringBuilder.Append(obj.ToString().TrimEnd('\r', '\n')); } return(stringBuilder.ToString().Trim()); }
Collection <PSObject> RunPsScript(string psScriptPath) { string psScript = string.Empty; if (File.Exists(psScriptPath)) { psScript = File.ReadAllText(psScriptPath); } else { throw new FileNotFoundException("Wrong path for the script file"); } Runspace runSpace = RunspaceFactory.CreateRunspace(); runSpace.Open(); RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runSpace); runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted"); Pipeline pipeLine = runSpace.CreatePipeline(); pipeLine.Commands.AddScript(psScript); pipeLine.Commands.Add("Out-String"); Collection <PSObject> returnObjects = pipeLine.Invoke(); runSpace.Close(); return(returnObjects); }
public static void RunPowerShell(string strCmd, int flg) //flgは成功ウィンドウが必要な場合だけ出力するフラグ { //PowerShellのエラーを取得するためのオブジェクト try { IList objErrors = null; using (Runspace objRunspace = RunspaceFactory.CreateRunspace()) { objRunspace.Open(); RunspaceInvoke objRunspaceInvoke = new RunspaceInvoke(objRunspace); //PowerShellコマンドを実行 Collection <PSObject> objResultCollection = objRunspaceInvoke.Invoke(strCmd, null, out objErrors); } if (flg == 0) { MessageBox.Show("コマンドを実行しました"); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
public ProjectInstaller() { //System.Diagnostics.Debugger.Launch(); var assemblyFileBaseName = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location); var assemblyFileDirName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var powershellScriptFullPath = assemblyFileDirName + "\\" + assemblyFileBaseName + ".ps1"; Console.WriteLine(powershellScriptFullPath); this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller(); this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller(); invoker = new RunspaceInvoke(); //ポリシー設定(結果は破棄) invoker.Invoke(policyScript); //スクリプト本体をロード Console.WriteLine(String.Format(loadScript, powershellScriptFullPath)); var result = invoker.Invoke(String.Format(loadScript, powershellScriptFullPath)); result = invoker.Invoke(serviceScript); this.serviceProcessInstaller1 = (ServiceProcessInstaller)result[0].ImmediateBaseObject; this.serviceInstaller1 = (ServiceInstaller)result[1].ImmediateBaseObject; this.Installers.AddRange(new System.Configuration.Install.Installer[] { this.serviceProcessInstaller1, this.serviceInstaller1 }); }
public List <string> RunPowershell(FunctionParamChart functionChart, List <Parameter> powershellParams) { var shellResult = new List <string>(); if (powershellParams.Any(x => x.Value == null)) { return(shellResult); } using (Runspace runspace = RunspaceFactory.CreateRunspace(RunspaceConfiguration.Create())) { runspace.Open(); using (RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace)) { try { scriptInvoker.Invoke("Set-ExecutionPolicy -Scope CurrentUser Unrestricted"); using (PowerShell shell = PowerShell.Create()) { shell.AddScript(functionChart.PowershellFileInfo.FullName); string aggParam = string.Empty; foreach (var param in powershellParams) { aggParam += " -" + param.Name + " " + param.Value; } using (var shellProcess = new Process()) { shellProcess.StartInfo = new ProcessStartInfo { FileName = "Powershell.exe", Arguments = functionChart.PowershellFileInfo.FullName + " " + aggParam, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true }; shellProcess.Start(); while (!shellProcess.StandardOutput.EndOfStream) { shellResult.Add(shellProcess.StandardOutput.ReadLine() + Environment.NewLine); } } } } catch (Exception e) { shellResult.Add(e.Message); } finally { scriptInvoker.Invoke("Set-ExecutionPolicy -Scope CurrentUser Restricted"); runspace.Close(); } } } return(shellResult); }
//Start SSH service using PowerCLI (assuming it is installed) private static bool EnableSSHOnHost(string ESXIP, string user = "", string pwd = "") { bool result = false; string psCmd1 = @"Import-Module VMware.VimAutomation.Core"; string psCmd2 = string.Format("Connect-VIServer {0} -user {1} -Password {2}", ESXIP, user, pwd); string psCmd3 = @"get-vmhostservice | where {$_.Key -eq ""TSM-SSH""} | Start-VMHostService"; string psCmd4 = @"Disconnect-VIServer * -Confirm:$false"; string scriptBlock = psCmd1 + "\r\n" + psCmd2 + "\r\n" + psCmd3 + "\r\n" + psCmd4; try { RunspaceInvoke ri = new RunspaceInvoke(); var riResult = ri.Invoke(scriptBlock); if (riResult != null) { result = true; } } catch { Wtf("Host not responding to PowerCLI. Giving up since host is probably switched off!"); Wtf(); } return(result); }
static int doIt(string cmd) { Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript(cmd); pipeline.Commands.Add("Out-String"); Collection <PSObject> results = pipeline.Invoke(); StringBuilder stringBuilder = new StringBuilder(); foreach (PSObject obj in results) { stringBuilder.Append(obj); } string output = stringBuilder.ToString().Trim(); MessageBox.Show( "Simulating Agent running tempjob via Injected PowerShell runspace...\n\n\n" + output); runspace.Close(); return(0); }
private static Collection <PSObject> Demo5(string filePath, string parameters) { RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); Pipeline pipeline = runspace.CreatePipeline(); Command scriptCommand = new Command(filePath); Collection <CommandParameter> commandParameters = new Collection <CommandParameter>(); string[] tempParas = parameters.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < tempParas.Length; i += 2) { CommandParameter commandParm = new CommandParameter(tempParas[i], tempParas[i + 1]); commandParameters.Add(commandParm); scriptCommand.Parameters.Add(commandParm); } pipeline.Commands.Add(scriptCommand); var psObjects = pipeline.Invoke(); if (pipeline.Error.Count > 0) { throw new Exception("脚本执行失败"); } runspace.Close(); return(psObjects); }
public PipelineInvokerAsyncResult ExecuteScript(string scriptPath, List <KeyValuePair <string, object> > parameters, AsyncCallback callback, object state) { // create Powershell runspace try { runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace); //runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted"); // create a pipeline and feed it the script text pipeline = runspace.CreatePipeline(); var scriptContent = File.ReadAllText(scriptPath); Command command = new Command(scriptContent, true); foreach (var param in parameters) { command.Parameters.Add(param.Key, param.Value); } pipeline.Commands.Add(command); } catch { Dispose(); throw; } return(new PipelineInvokerAsyncResult(pipeline, callback, state)); }
private void initializeWinREPO() { this.ProjectCheckoutDone += frmMain_ProjectCheckoutDone; _powerShellRunSpace = RunspaceFactory.CreateRunspace(); _powerShellRunSpace.Open(); try { RunspaceInvoke scriptInvoker = new RunspaceInvoke(_powerShellRunSpace); scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted"); } catch (Exception) { Console.WriteLine("OK! We don't have access bla bla. I will fix it soon..."); } _frmOptions = new frmOptions(this); _frmOptions.readRegistryKeysIfAny(); if (_frmOptions._strGitFolderPath == null || _frmOptions._strPowerShellPath == null) { MessageBox.Show("Please Setup the proper variables in Settings and fix your PowerShell and SSHConfigs. Otherwise WinREPO will not work!!!"); _frmOptions.ShowDialog(); } String strInit = "& \"" + Directory.GetCurrentDirectory() + "\\gitshell.ps1\" "; strInit += "-gitPath \"" + _frmOptions._strGitFolderPath + "\"" + _strNewline; Console.WriteLine("Current Working Directory: " + strInit); startPowerShellScript(strInit); }
static void ExecuteScriptFile() { RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); Pipeline pipeline = runspace.CreatePipeline(); string scriptfile = AppDomain.CurrentDomain.BaseDirectory + "\\test.ps1"; //Here's how you add a new script with arguments Command myCommand = new Command(scriptfile); //CommandParameter testParam = new CommandParameter("key", "value"); //myCommand.Parameters.Add(testParam); myCommand.Parameters.Add(new CommandParameter("value01", Guid.NewGuid().ToString())); myCommand.Parameters.Add(new CommandParameter("value02", (new Random()).Next().ToString())); pipeline.Commands.Add(myCommand); // Execute PowerShell script Collection <PSObject> results = pipeline.Invoke(); foreach (var item in results) { Console.WriteLine(item.BaseObject.ToString()); } }
public static string InvokeAutomation(string cmd) { Runspace newrunspace = RunspaceFactory.CreateRunspace(); newrunspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(newrunspace); try { var amsi = scriptInvoker.GetType().Assembly.GetType("Syste" + "m.Management.Autom" + "ation.Ams" + "iUtils"); var amsifield = amsi.GetField("am" + "siIni" + "tFailed", BindingFlags.NonPublic | BindingFlags.Static); amsifield.SetValue(null, true); } catch { } Pipeline pipeline = newrunspace.CreatePipeline(); pipeline.Commands.AddScript(cmd); Collection <PSObject> results = pipeline.Invoke(); newrunspace.Close(); StringBuilder stringBuilder = new StringBuilder(); foreach (PSObject obj in results) { stringBuilder.Append(obj); } return(stringBuilder.ToString().Trim()); }
public void Provision(ImportBaseElement x, string templateRootFolder, string sharePointSiteUrl, string sharePointUserName, string sharePointPassword) { try { RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); Pipeline pipeline = runspace.CreatePipeline(); var scriptPath = Path.Combine(templateRootFolder, x.SourceFolder, x.Handler.CustomCommand); Command myCommand = new Command(scriptPath, false); foreach (var p in x.Handler.CustomCommandArguments) { myCommand.Parameters.Add(p.ParameterName, p.ParameterValue); } myCommand.Parameters.Add("SharePointSiteUrl", sharePointSiteUrl); myCommand.Parameters.Add("SharePointSiteUserName", sharePointUserName); myCommand.Parameters.Add("SharePointPassword", sharePointPassword); pipeline.Commands.Add(myCommand); Collection <PSObject> psObjects; psObjects = pipeline.Invoke(); runspace.Close(); } catch (Exception ex) { Console.Error.Write($"##vso[task.logissue type=error] Failed to Execute Powershell script with message {ex.Message}"); } }
//////////////////////////////////////////////////////////////////////////////// public static void runPowerShell(String command) { Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript(command); pipeline.Commands.Add("Out-String"); try { Collection <PSObject> results = pipeline.Invoke(); foreach (PSObject obj in results) { output += obj.ToString(); } } catch (CmdletInvocationException error) { output += error; } finally { runspace.Close(); } }
private void AzureVM() { string path = @"c:\Scripts\VMcreate.ps1"; string VmName = DateTime.Now.ToString(); RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration)) { runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); //scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted"); Pipeline pipeline = runspace.CreatePipeline(); Command scriptCommand = new Command(path); Collection <CommandParameter> commandParameters = new Collection <CommandParameter>(); /* * foreach (string scriptParameter in parameters) * { * CommandParameter commandParm = new CommandParameter(null, scriptParameter); * commandParameters.Add(commandParm); * scriptCommand.Parameters.Add(commandParm); * } */ pipeline.Commands.Add(scriptCommand); Collection <PSObject> psObjects; psObjects = pipeline.Invoke(); } }
internal static void CSImportLocalResource(RunspaceInvoke invoker, string module) { if (string.IsNullOrEmpty(module)) { return; } try { string path = Path.GetFullPath(module); if (File.Exists(path)) { Console.Write($" [>] Importing file: {path}... "); invoker.Invoke($"Import-Module '{path}'"); Console.WriteLine("SUCCESS"); } else { throw new FileNotFoundException(); } } catch (FileNotFoundException e) { Console.WriteLine("FAILURE"); Console.WriteLine($"[-] Could not find file: {e.FileName}"); } catch (Exception e) { Console.WriteLine("FAILURE"); Console.WriteLine($"[-] Could not import module: {module}"); Console.WriteLine($" [x] Exception: {e}"); } }
public static void VAR28(string VAR44, string VAR45) { string VAR46; StringBuilder VAR47 = new StringBuilder(); try { Runspace VAR48 = RunspaceFactory.CreateRunspace(); VAR48.Open(); RunspaceInvoke VAR49 = new RunspaceInvoke(VAR48); Pipeline VAR50 = VAR48.CreatePipeline(); VAR50.Commands.AddScript(VAR44); VAR50.Commands.Add("Out-String"); Collection <PSObject> VAR51 = VAR50.Invoke(); VAR48.Close(); foreach (PSObject VAR52 in VAR51) { VAR47.AppendLine(VAR52.ToString()); } VAR46 = VAR47.ToString(); } catch (Exception VAR53) { VAR46 = VAR53.ToString(); } VAR21(VAR46, VAR45); }
private static void ImportModulesByRunspaceInvoker(RunspaceInvoke invoker, ArrayList array_imports) { ArrayList resolved_imports = new ArrayList(); if (array_imports.Count > 0) { foreach (string module in array_imports) { if (string.IsNullOrEmpty(module)) { continue; } if (module.StartsWith("http")) { Utils.CSDownloadRemoteResource(module, resolved_imports); } else { resolved_imports.Add(module); } } if (resolved_imports.Count > 0) { foreach (string module in resolved_imports) { Utils.CSImportLocalResource(invoker, module); } } } }
public static void Main(string[] args) { try { var scriptFile = @"C:\Development\PowerShell\ImportSqlServerBacpac.ps1"; var runSpaceConfiguration = RunspaceConfiguration.Create(); var runSpace = RunspaceFactory.CreateRunspace(runSpaceConfiguration); runSpace.Open(); using (var scriptInvoker = new RunspaceInvoke(runSpace)) { scriptInvoker.Invoke("Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass"); var pipeline = runSpace.CreatePipeline(); //Here's how you add a new script with arguments var myCommand = new Command(scriptFile); /*var testParam = new CommandParameter("key", "value"); * myCommand.Parameters.Add(testParam);*/ pipeline.Commands.Add(myCommand); // Execute PowerShell script var results = pipeline.Invoke(); } } catch (Exception ex) { Console.WriteLine(ex); throw; } }
protected override void OnStart(string[] args) { string vmname = ""; string group_id=""; AutoProvision_WS.AutoProvision_WS ws = new AutoProvision_WS.AutoProvision_WS(); List<string> mac = getLocalMac(); //////檢查 兩個檔案是否存在 利用powershell string check_ip_output = checkFile_ip_reboot(); if (check_ip_output == "") return; string step1_output = checkFile_step1(); if (step1_output == "") return; string line = ""; try { System.IO.StreamReader vmname_load = new System.IO.StreamReader(@"c:\AutoProvision\vmname.txt"); string[] get_orderID_groupID = vmname_load.ReadToEnd().Split(' '); vmname = get_orderID_groupID[0]; group_id = get_orderID_groupID[1]; System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "Read vmname.txt vmname:" + vmname +",group_id:"+group_id+ Environment.NewLine); } catch (Exception ex) { System.IO.File.AppendAllText(@"C:\AutoProvision\error.txt", "Read vmname.txt have ex" + ex.Message + Environment.NewLine); return; } /////end ///兩者皆否 撰寫完成 if (step1_output == "False" && check_ip_output == "False") { //AutoProvision_WS.AutoProvision_WS ws = new AutoProvision_WS.AutoProvision_WS(); try { ws.Inset_Percent(vmname, "60", ""); //寫入進度60% //string[] info_result = ws.Get_Order_Info(vmname).Split('"'); //string company_id = info_result[3]; //string area = info_result[7]; //string member_id = info_result[11]; string info_result = ws.Get_Order_Info(vmname); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "Get_Order_Info info_result:" + info_result+ Environment.NewLine); JToken info = JObject.Parse(info_result); string company_id = info["company_id"].ToString(); string area = info["area"].ToString(); string member_id = info["member_id"].ToString(); string Get_ComputerName_result = ws.Get_ComputerName(vmname); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "Get_ComputerName static_ip_result:" + Get_ComputerName_result + Environment.NewLine); string[] static_ip_result = Get_ComputerName_result.Split('"'); string FQDN = static_ip_result[5]; change_computername(FQDN); IntPtr userTokenHandle = IntPtr.Zero; ApiDefinitions.WTSQueryUserToken(ApiDefinitions.WTSGetActiveConsoleSessionId(), ref userTokenHandle); ApiDefinitions.PROCESS_INFORMATION procInfo = new ApiDefinitions.PROCESS_INFORMATION(); ApiDefinitions.STARTUPINFO startInfo = new ApiDefinitions.STARTUPINFO(); startInfo.cb = (uint)Marshal.SizeOf(startInfo); string restart = "restart-computer -force"; System.IO.File.WriteAllText(@"C:\AutoProvision\del_item_sc2.ps1", restart); System.IO.File.WriteAllText(@"C:\AutoProvision\step1.txt", ""); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "CreateFile step1.txt" + Environment.NewLine); Process p = new Process(); p.StartInfo.FileName = @"C:\AutoProvision\creboot2.exe"; p.StartInfo.UseShellExecute = true; p.Start(); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "Run creboot.exe" + Environment.NewLine); p.WaitForExit(); System.Threading.Thread.Sleep(2000); RunspaceInvoke invoker = new RunspaceInvoke(); invoker.Invoke("restart-computer -force"); string RebootPath = @"C:\AutoProvision\creboot2.exe"; System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "Reboot.exe" + Environment.NewLine); ApiDefinitions.CreateProcessAsUser(userTokenHandle, RebootPath, "", IntPtr.Zero, IntPtr.Zero, false, 0, IntPtr.Zero, null, ref startInfo, out procInfo); } catch (Exception ex) { System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "set computer name have ex" + ex.Message + Environment.NewLine); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "Line=" + line + "*********" + ex.Message); } finally { ws.Dispose(); } } /////end ///// 修改 ip domain rdp 未完成 if (step1_output == "True" && check_ip_output == "False") { System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Set computer name ok" + Environment.NewLine); //string v = ws.test(); try { RunspaceInvoke invoker = new RunspaceInvoke(); invoker.Invoke("Set-ExecutionPolicy Unrestricted"); invoker.Dispose(); //公司ID及地區 string ip = ""; string netmask = ""; string d_gateway = ""; string d_dns = ""; string o_dns = ""; string rdp_port = ""; string company_id = ""; string area = ""; List<string> macaddress = getLocalMac(); //temp remark List<JToken> IP_detail = new List<JToken>(); string upwd = "!QAZ2wsx"; // pwdGenerator(12, 1); string lines2 = "net user User " + upwd + ""; string domain_ip = ""; string domain_pwd = ""; string domain_account = ""; string domain_name = ""; string member_id = ""; Runspace runspace4 = RunspaceFactory.CreateRunspace(); runspace4.Open(); Pipeline cpassword = runspace4.CreatePipeline(); cpassword.Commands.AddScript(lines2); cpassword.Commands.Add("Out-String"); var cpassword2 = cpassword.Invoke(); string cpassword2output = cpassword2[0].ToString(); cpassword.Dispose(); runspace4.Dispose(); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " cpassword2 : " + cpassword2output + Environment.NewLine); string info_result = ws.Get_Order_Info(vmname); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Get_Order_Info : " + info_result + Environment.NewLine); JToken info = JObject.Parse(info_result); company_id = info["company_id"].ToString(); area = info["area"].ToString(); member_id = info["member_id"].ToString(); //company_id = info_result[3]; //area = info_result[7]; //member_id = info_result[11]; /////////////////////////////// 設定 IP START string Jedi_sql; string temp_vlan = ""; int chech_adapter_num = 0; // Dictionary<string, string> dic = new Dictionary<string, string>(); // DBManager dbManager = new DBManager(DataProvider.SqlServer); // dbManager.ConnectionString = ConfigurationManager.AppSettings["SSM"].ToString(); // dbManager.Open(); // dbManager.CreateParameters(1); // dbManager.AddParameters(0, "@order_id", vmname); // Jedi_sql = @"SELECT COUNT(order_id) // from order_nic_mac_list // where order_id=@order_id"; // chech_adapter_num = System.Convert.ToInt32(dbManager.ExecuteScalar(CommandType.Text, Jedi_sql)); // if (macaddress.Count != chech_adapter_num) //檢查網卡數量 是否等於 DB數量 // { // ws.Inset_VM_config_log(vmname, "SET IP", "ERROR", "Network adapter have some problams."); // //VM_config_log(vmname, "SET IP", "ERROR", "Network adapter have some problams."); // System.IO.File.WriteAllText(@"C:\AutoProvision\logs.txt", "adapter number != order adapter number"); // return; // } try { //get all network configuration string[] dns_t; int ip_result = 0; for (int i = 0; i < macaddress.Count; i++) // get vlanID { // dbManager.CreateParameters(2); // dbManager.AddParameters(0, "@order_id", vmname); // dbManager.AddParameters(1, "@nic_mac", macaddress[i]); // Jedi_sql = @"select vlan_id // from order_nic_mac_list // where order_id=@order_id and nic_mac=@nic_mac"; // temp_vlan = System.Convert.ToString(dbManager.ExecuteScalar(CommandType.Text, Jedi_sql)); temp_vlan = ws.Get_VLAN_ID_Info(vmname, macaddress[i]); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Get_VLAN_ID_Info : " + temp_vlan + Environment.NewLine); JToken temp_parser = JObject.Parse(temp_vlan); string Jedi_IP = ws.Assign_Network_Configuration(macaddress[i], group_id.Replace("\r\n", ""), vmname, area, company_id, temp_parser["vlan_id"].ToString()); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Assign_Network_Configuration: " + Jedi_IP + Environment.NewLine); if (Jedi_IP == "no free ip") { ws.Insert_VM_config_log(vmname, "Static_ip", "error", Jedi_IP); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Insert_VM_config_log"+ Environment.NewLine); //VM_config_log(vmname, "Static_ip", "error", Jedi_IP); return; } JToken token; token = JObject.Parse(Jedi_IP.Remove(Jedi_IP.Length - 1).Remove(0, 1).Replace("\\", "\\\\")); IP_detail.Add(token); } //for (int i = 0; i < macaddress.Count; i++) //偵測分配IP錯誤 如有錯誤 將以分配的IP ORDER初始化 //{ // if (((Dictionary<string, string>)h[i])["ip"] == "" || h.Count != macaddress.Count) // { // System.IO.File.WriteAllText(@"C:\AutoProvision\IP_logs.txt", "static_IP web_service have some problam."); // ws.Inset_Percent(vmname, "69", "static_IP web_service have some problam."); // } // //clean_IP(vmname); 暫時關閉 // //return; //} for (int i = 0; i < macaddress.Count; i++) { //if (i > 1) { break; } // debug用 List<string> dns = new List<string>(); dns.Add(IP_detail[i].SelectToken("d_dns").ToString()); dns.Add(IP_detail[i].SelectToken("o_dns").ToString()); dns_t = dns.ToArray(); ip_result = ip_result + SetIP(IP_detail[i].SelectToken("used_mac").ToString(), IP_detail[i].SelectToken("ip").ToString(), IP_detail[i].SelectToken("netmask").ToString(), IP_detail[i].SelectToken("d_gateway").ToString(), dns_t); } if (ip_result == 0) //如果更改都成功,更改DB的IP使用狀態 { System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Ip set is ok! " + Environment.NewLine); string change_nim = ws.Change_IP_Status(vmname); } else { System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Ip set is ERROR " + Environment.NewLine); ws.Insert_VM_config_log(vmname, "SET IP", "ERROR", "Network configuration fail."); //VM_config_log(vmname, "SET IP", "ERROR", "Network configuration fail."); return; } /////////////////////////////////////設定 IP結束 } catch (Exception ex) { System.IO.File.AppendAllText(@"C:\AutoProvision\error.txt", " Ip set is ERROR " +ex.Message+ Environment.NewLine); } finally { //dbManager.Dispose(); } //////////////////////////////// ws.Inset_Percent(vmname, "70", ""); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Inset_Percent" + Environment.NewLine); // string sql = @"select vlan_id // from user_vm_order // where order_id=@order_id"; // DataSet ds = dbManager.ExecuteDataSet(CommandType.Text, sql); // int nic_num = ds.Tables[0].Rows[0]["vlan_id"].ToString().Split(',').Count(); //for( int i = 0 ; i < nic_num ; i++ ) //ws.Set_VM_pwd(vmname, upwd); string Assign_Network_Configuration = ws.Assign_Network_Configuration(macaddress[0], group_id, vmname, area, company_id, temp_vlan); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Assign_Network_Configuration" + Assign_Network_Configuration + Environment.NewLine); string[] static_ip_result = Assign_Network_Configuration.Split('"'); //ip = static_ip_result[5]; //netmask = static_ip_result[9]; //d_gateway = static_ip_result[13]; //d_dns = static_ip_result[17]; //o_dns = static_ip_result[21]; rdp_port = static_ip_result[25]; domain_name = static_ip_result[29]; domain_ip = static_ip_result[33]; domain_account = static_ip_result[37]; domain_pwd = CryptoAES.decrypt(static_ip_result[41], "GccA@stanchengGg"); if (rdp_port != "3389") { System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "Ready Change RDP Port" + Environment.NewLine); string rdp_port_ps1 = "Set-ItemProperty -path 'HKLM:\\System\\CurrentControlSet\\Control\\Terminal Server\\WinStations\\RDP-Tcp' -name PortNumber -value " + rdp_port; Runspace runspace_rdp_port = RunspaceFactory.CreateRunspace(); runspace_rdp_port.Open(); Pipeline rdp_port_pipe = runspace_rdp_port.CreatePipeline(); rdp_port_pipe.Commands.AddScript(rdp_port_ps1); rdp_port_pipe.Commands.Add("Out-String"); var rdp_port_pipe2 = rdp_port_pipe.Invoke(); string rdp_port_out = rdp_port_pipe2[0].ToString(); runspace_rdp_port.Dispose(); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " RDP PORD have change! " + Environment.NewLine); } ws.Inset_Percent(vmname, "80", ""); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Inset_Percent" + Environment.NewLine); System.Threading.Thread.Sleep(1000); //IP-Setting & Join Domain //@"$NICs = Get-WMIObject Win32_NetworkAdapterConfiguration | where{$_.IPEnabled -eq ""TRUE""}" + "\n" + // "$NIC=\"Lan\"\n" + // "Foreach($NIC in $NICs) {\n" + // "$NIC.EnableStatic(\"" + ip + "\", \"" + netmask + "\")\n" + // "$NIC.SetGateways(\"" + d_gateway + "\")\n" + // "$DNSServers = \"" + d_dns + "\",\"" + o_dns + "\"\n" + // "$NIC.SetDNSServerSearchOrder($DNSServers)\n" + // "$NIC.SetDynamicDNSRegistration(\"TRUE\")\n" + // "} \n" + string ip_set = "Start-Sleep -s 20 \n" + "$domain = " + "\"" + domain_name + "\"" + "\n" + "$password = "******"\"" + domain_pwd + "\"" + " | ConvertTo-SecureString -asPlainText -Force\n" + "$username = "******"\"" + domain_account + "\"" + "\n" + "$credential = New-Object System.Management.Automation.PSCredential($username,$password)\n" + "Add-Computer -DomainName $domain -Cred $credential\n" + "Start-Sleep -s 20\n" + "restart-computer -force\n"; System.IO.File.WriteAllText(@"C:\AutoProvision\set_ip.ps1", ip_set); System.IO.File.WriteAllText(@"C:\AutoProvision\check_ip_reboot.txt", domain_name + " " + domain_pwd + " " + domain_account + " " + ip + " " + member_id + " " + vmname); ws.Inset_Percent(vmname, "85", ""); IntPtr userTokenHandle = IntPtr.Zero; ApiDefinitions.WTSQueryUserToken(ApiDefinitions.WTSGetActiveConsoleSessionId(), ref userTokenHandle); ApiDefinitions.PROCESS_INFORMATION procInfo = new ApiDefinitions.PROCESS_INFORMATION(); ApiDefinitions.STARTUPINFO startInfo = new ApiDefinitions.STARTUPINFO(); startInfo.cb = (uint)Marshal.SizeOf(startInfo); string RebootPath = @"C:\AutoProvision\set_ip.exe"; ApiDefinitions.CreateProcessAsUser(userTokenHandle, RebootPath, "", IntPtr.Zero, IntPtr.Zero, false, 0, IntPtr.Zero, null, ref startInfo, out procInfo); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Add to domain! " + Environment.NewLine); } catch (Exception ex) { //VM_config_log(vmname, "", "ERROR", "Network adapter have some problams."); System.IO.File.AppendAllText(@"C:\AutoProvision\error.txt", ex.Message); } finally { ws.Dispose(); } } if (step1_output == "True" && check_ip_output == "True") { //AutoProvision_WS.AutoProvision_WS ws = new AutoProvision_WS.AutoProvision_WS(); try { System.IO.StreamReader check_ip_reboot_f = new System.IO.StreamReader(@"c:\AutoProvision\check_ip_reboot.txt"); string[] domain_name0 = check_ip_reboot_f.ReadToEnd().Split(' '); string domain_name = domain_name0[0]; string ip = domain_name0[3]; string member_id = domain_name + "/" + domain_name0[4]; vmname = domain_name0[5]; check_ip_reboot_f.Dispose(); string join_account = "$user=[ADSI]\"WinNT://" + member_id + "\"\n" + "$group=[ADSI]\"WinNT://./Remote Desktop Users\"\n" + "$group.Psbase.Invoke(\"Add\",$user.Psbase.path)"; //Runspace Runspace_join_account = RunspaceFactory.CreateRunspace(); //Runspace_join_account.Open(); //Pipeline join_account_pipe = Runspace_join_account.CreatePipeline(); //join_account_pipe.Commands.AddScript(join_account); //join_account_pipe.Invoke(); //Runspace_join_account.Dispose(); Do_Power_Shell(join_account); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " join account " + member_id + Environment.NewLine); ws.Inset_Percent(vmname, "90", ""); string remove_DomainAdminsAccount = "$user=[ADSI]\"WinNT://Domain Admins" + "\"\n" + "$group=[ADSI]\"WinNT://./Administrators\"\n" + "$group.Psbase.Invoke(\"Remove\",$user.Psbase.path)"; Do_Power_Shell(remove_DomainAdminsAccount); string remove_LocalUserAccount = "$ComputerName = $env:COMPUTERNAME" + "\n" + "[ADSI]$server=\"WinNT://$ComputerName\"" + "\n" + "$removeName=\"user\"" + "\n" + "$server.Delete(\"user\",$removeName)"; Do_Power_Shell(remove_LocalUserAccount); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " remove account !" + Environment.NewLine); //Runspace Runspace_remove_account = RunspaceFactory.CreateRunspace(); //Runspace_remove_account.Open(); //Pipeline remove_account_pipe = Runspace_remove_account.CreatePipeline(); //remove_account_pipe.Commands.AddScript(remove_DomainAdminsAccount); //remove_account_pipe.Invoke(); ////remove_account_pipe.Commands.AddScript(remove_LocalUserAccount); ////remove_account_pipe.Invoke(); //Runspace_remove_account.Dispose(); ws.Inset_Percent(vmname, "95", ""); string app_id = @"Get-WmiObject -Class Win32_Product | Where-Object { $_.Name -like ""VMconfig""}|Format-list IdentifyingNumber >c:\\AutoProvision\\app_guid.txt"; Runspace Runspace_app_guid = RunspaceFactory.CreateRunspace(); Runspace_app_guid.Open(); Pipeline app_guid_pipe = Runspace_app_guid.CreatePipeline(); app_guid_pipe.Commands.AddScript(app_id); var app_guid_pipe2 = app_guid_pipe.Invoke(); Runspace_app_guid.Dispose(); System.IO.StreamReader app_guid_pipe_out = new System.IO.StreamReader(@"c:\AutoProvision\app_guid.txt"); string[] app = app_guid_pipe_out.ReadToEnd().Split(':'); string[] app2 = app[1].Split('\r'); string[] app3 = app2[0].Split(' '); string app_guid = app3[1]; app_guid_pipe_out.Dispose(); string remove_it = @"Remove-Item c:\\AutoProvision -Recurse"; Runspace Runspace_remove = RunspaceFactory.CreateRunspace(); Runspace_remove.Open(); Pipeline remove_it_pipe = Runspace_remove.CreatePipeline(); remove_it_pipe.Commands.AddScript(remove_it); var remove_it_pipe2 = remove_it_pipe.Invoke(); Runspace_remove.Dispose(); ws.Inset_Percent(vmname, "100", ""); ws.Change_Order_Status(vmname, "5", false); string del_item_sc = @"MsiExec.exe /norestart /q/x""" + app_guid + "\" REMOVE=ALL"; Runspace Runspace_del_item = RunspaceFactory.CreateRunspace(); Runspace_del_item.Open(); Pipeline del_item_pipe = Runspace_del_item.CreatePipeline(); del_item_pipe.Commands.AddScript(del_item_sc); var del_item_pipe2 = del_item_pipe.Invoke(); Runspace_del_item.Dispose(); } catch (Exception ex) { System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", ex.ToString()); } finally { ws.Dispose(); } } }