2017-04-04 68 views
0

我想從C#代碼調用PowerShell命令和需要傳遞的參數字節數組,但它在錯誤的格式轉換。 C#代碼:C#運行PowerShell命令如何傳遞字節數組

var command = new Command("Set-UserPhoto"); 
command.Parameters.Add("Identity", login); 
command.Parameters.Add("Confirm", false); 
command.Parameters.Add("PictureData", pictureData); //byte array 

其實PowerShell的:

Set-UserPhoto -Identity:'[email protected]' -Confirm:$False -PictureData:'255','216','255','224',...,'0','16' 

所需的PowerShell:

Set-UserPhoto -Identity:'[email protected]' -Confirm:$False -PictureData:(255,216,255,224,...,0,16) 

與功能AddScript PowerShell中使用無法運行。

+0

你不會做,與實際的PowerShell?命令。您將加載一個文件,將其管道輸入命令並使用管道對象作爲參數。事實上,'設置UserPhoto'作品一樣好與流,而不是一個字節的緩衝區 –

+0

正交也許你的問題,但你爲什麼要使用C#打電話PowerShell的?難道你不能直接調用腳本正在使用的任何API,繞過所有的PowerShell限制嗎? –

回答

0

如果你的「命令」類的相當於System.Management.Automation.PSCommand,你這樣做是正確的。

下面的代碼我用來執行此操作:

const string connectionUri = "https://outlook.office365.com/powershell-liveid/?proxymethod=rps"; 
const string schemaUri = "http://schemas.microsoft.com/powershell/Microsoft.Exchange"; 

const string loginPassword = "password"; 
SecureString secpassword = new SecureString(); 
foreach (char c in loginPassword) 
{ 
    secpassword.AppendChar(c); 
} 
PSCredential exchangeCredential = new PSCredential("[email protected]", secpassword); 

WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri(connectionUri), schemaUri, exchangeCredential) 
{ 
    MaximumConnectionRedirectionCount = 5, 
    AuthenticationMechanism = AuthenticationMechanism.Basic 
}; 

using (var remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo)) 
{ 
    remoteRunspace.Open(); 

    using (PowerShell powershell = PowerShell.Create()) 
    { 
     powershell.Runspace = remoteRunspace; 

     var command = new PSCommand() 
      .AddCommand("Set-UserPhoto") 
      .AddParameter("Identity", "[email protected]") 
      .AddParameter("PictureData", File.ReadAllBytes(@"C:\Test\MyProfilePictures\pic.jpg")) 
      .AddParameter("Confirm", false); 
     powershell.Commands = command; 
     powershell.Invoke(); 
    } 
} 

proxymethod = RPSis important to support >10Ko files

希望能夠幫助