Windows ortamının en kullanışlı araçlarının başında Powershell komutları gelmektedir. Bu araç sayesinde bir çok işlem kolayca yapılabilmektedir. Powershell komutlarının C# içerisinde kullanılması da aynı şekilde zorlu birçok işlemin kolayca yapılmasını sağlar.
Şimdi adımları yazalım:
- System.Management.Automation referansını projemize ekliyoruz.
- “System.Collections.Objectmodel” ve “System.Management.Automation”
referanslarını using ifadesi ile sayfaya ekliyoruz.
- Powershell işlemini yapacak nesne oluşturulur.
using (PowerShell PowerShellInstance = PowerShell.Create()) { }
- Oluşturulan powershell nesnesine komut ve parametreler eklenir.
using (PowerShell PowerShellInstance = PowerShell.Create()) { PowerShellInstance.AddScript("param($param1) $d = get-date; $s = 'test string value'; " +"$d; $s; $param1; get-service"); PowerShellInstance.AddParameter("param1", "parameter 1 value!"); }
- Powershell komutunun çalıştırılması
Collection<PSObject> PSOutput = PowerShellInstance.Invoke(); foreach (PSObject outputItem in PSOutput) { if (outputItem != null) { //TODO: do something with the output item // outputItem.BaseOBject } }
Örnek çalışma:
using (PowerShell PowerShellInstance = PowerShell.Create()) { // İşlemi 7 saniye durduran komutun eklenmesi PowerShellInstance.AddScript("start-sleep -s 7; get-service"); // komutun çalıştırılması IAsyncResult result = PowerShellInstance.BeginInvoke(); while (result.IsCompleted == false) { Console.WriteLine("Waiting for pipeline to finish..."); Thread.Sleep(1000); // might want to place a timeout here... } Console.WriteLine("Finished!"); }