2015-11-20 110 views
0

所以我嘗試從ASPX/C#應用程序調用PS腳本。當我從命令行(PS C:\scripts> ./do-barrelRoll.ps1 -s remoteComputer)運行PS腳本時,它按預期工作。但是當我使用C#時,它無法連接到遠程計算機(錯誤的用戶/密碼)。有趣的事實:使用的用戶和密碼在PS腳本本身的配置部分內(參見$SETUP變量)!我究竟做錯了什麼?Powershell調用命令ASPX/C#與命令行

從ASPX確切的錯誤信息(服務器名稱是正確的!):

[remoteComputer] Connecting to remote server remoteComputer failed with the following error message : The user name or password is incorrect 

的PS腳本的相關部分:

ASPX/C#應用程序的
set-alias new New-Object 
$passwd = $SETUP["password"] | ConvertTo-SecureString -asplaintext -force 
$session = new -TypeName System.Management.Automation.PSCredential -argumentlist $SETUP["user"], $passwd 

Invoke-Command –ComputerName $PARAM["s"] -Credential $session –ScriptBlock { 
    # Do a barrel roll 
} 

相關部分:

using System.Management.Automation; 

public ActionResult doAction(string server, string action) 
{ 
    var split = server.Split(';'); 
    //... 
    var ps = PowerShell.Create(); 
    ps.AddScript("Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned -f; C:\\scripts\\do-barrelRoll.ps1 -s " + split[1]); 
    Collection<PSObject> results = ps.Invoke(); 
    // Here I retrive the results and the content of the error stream and display them 
} 

回答

0

它在命令行中按預期工作很可能是因爲您的帳戶具有完整的腳本訪問權限,一切。 .NET運行的帳戶應該更受限制。您必須檢查該帳戶是否有權運行無限制的腳本。檢查當地的政策,然後從那裏上去。您很可能與.NET應用程序運行的帳戶不同。

+0

是的,但是使用的證書在PS腳本里面......並且我在執行腳本之前提升了過程的嚴格性。該腳本確實運行(請參閱錯誤消息) –

+0

@MarcoAlka這不是關於您在腳本中擁有的憑據,而是運行執行腳本的過程,您需要注意。在大多數安全環境中,默認情況下禁用不受限制的腳本。 – Josh

+0

但是爲什麼它會抱怨用戶名/密碼呢?我在運行.NET應用程序的服務器上和目標服務器上運行了'Set-ExecutionPolicy -f unrestricted'。問題依然存在。 –