簡體   English   中英

從C#運行Powershell

[英]Run Powershell from C#

我需要從C#啟動Powershell腳本,並在Pipeline.Invoke()上獲取PSSSecurityException。

AuthorizationManager檢查失敗。

我的代碼:

RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
{
    runspace.Open();
    Pipeline pipeline = runspace.CreatePipeline();
    Command scriptCommand = new Command(scriptfile);
    pipeline.Commands.Add(scriptCommand);
    pipeline.Invoke();
}

問題

  1. 我懷疑我需要設置PSCredential。 但是我無法對此進行提示,因此我必須在代碼中進行處理。 可以安全的方式進行嗎? 不是這種情況

查看此SuperUser帖子: https : //superuser.com/questions/106360/how-to-enable-execution-of-powershell-scripts

您可能只需要允許運行未簽名的腳本即可。 在PS控制台中,鍵入以下內容:

set-executionpolicy remotesigned

另一個資源也與此相呼應: http : //tgnp.me/2011/09/powershell-authorizationmanager-check-failed-resolution/

試試看,讓我知道會發生什么。

要捕獲腳本的輸出,請嘗試以下操作:

Collection output = pipeline.Invoke();
foreach (PSObject psObject in output)
{
    <here you can ToString the psObject for the output and write it line by line to your log>
}

問題在於該腳本已放置在共享上。 要在此共享上運行腳本,我需要將該共享添加到“受信任的站點”。

在此處輸入圖片說明

在此處輸入圖片說明

暫無
暫無

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

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