簡體   English   中英

從C#調用遠程powershell命令

[英]Invoke remote powershell command from C#

我正在嘗試使用C#運行invoke-command cmdlet,但我無法找出正確的語法。 我只想運行這個簡單的命令:

invoke-command -ComputerName mycomp.mylab.com -ScriptBlock {"get-childitem C:\windows"}

在C#代碼中,我完成了以下操作:

InitialSessionState initial = InitialSessionState.CreateDefault();
Runspace runspace = RunspaceFactory.CreateRunspace(initial);
runspace.Open();
PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
ps.AddCommand("invoke-command");
ps.AddParameter("ComputerName", "mycomp.mylab.com");
ps.AddParameter("ScriptBlock", "get-childitem C:\\windows");
foreach (PSObject obj in ps.Invoke())
{
   // Do Something
}

當我運行它時,我得到一個例外:

Cannot bind parameter 'ScriptBlock'. Cannot convert the "get-childitem C:\windows" value of type "System.String" to type "System.Management.Automation.ScriptBlock".

我猜我需要在某處使用ScriptBlock類型,但不知道該怎么做。 這只是一個簡單的示例,真正的用例將涉及運行一個包含多個命令的更大的腳本塊,因此任何有關如何執行此操作的幫助都將受到高度贊賞。

謝謝

啊,ScriptBlock本身的參數需要是ScriptBlock類型。

完整代碼:

InitialSessionState initial = InitialSessionState.CreateDefault();
Runspace runspace = RunspaceFactory.CreateRunspace(initial);
runspace.Open();
PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
ps.AddCommand("invoke-command");
ps.AddParameter("ComputerName", "mycomp.mylab.com");
ScriptBlock filter = ScriptBlock.Create("Get-childitem C:\\windows");
ps.AddParameter("ScriptBlock", filter);
foreach (PSObject obj in ps.Invoke())
{
   // Do Something
}

如果有人發現將來有用,請在此處給出答案

scriptblock字符串應與“{...}”格式匹配。使用以下代碼即可:

ps.AddParameter("ScriptBlock", "{ get-childitem C:\\windows }");

你使用短格式:

ps.AddParameter("ScriptBlock", ScriptBlock.Create("Get-childitem C:\\Windows"));

如果在某些情況下可能更合適,則采用另一種方法。

        var remoteComputer = new Uri(String.Format("{0}://{1}:5985/wsman", "HTTP", "ComputerName"));
        var connection = new WSManConnectionInfo(remoteComputer, null, TopTest.GetCredential());

        var runspace = RunspaceFactory.CreateRunspace(connection);
        runspace.Open();

        var powershell = PowerShell.Create();
        powershell.Runspace = runspace;

        powershell.AddScript("$env:ComputerName");

        var result = powershell.Invoke();

https://blogs.msdn.microsoft.com/schlepticons/2012/03/23/powershell-automation-and-remoting-ac-love-story/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM