2013-01-21 38 views
2

我工作在C#在Office 365的插件,並試圖此PowerShell命令:PowerShell的變量和C#

$newLicense = New-MsolLicenseOptions -AccountSkuId example:ENTERPRISEPACK -DisabledPlans SHAREPOINTWAC,MCOSTANDARD,SHAREPOINTENTERPRISE 
Set-MsolUserLicense -UserPrincipalName [email protected] -AddLicenses "example:ENTERPRISEPACK" -LicenseOptions $newLicense 

在PS,這個效果很好。在C#中,我無法運行此命令。 這裏是我的C#代碼,從PowerShellInvoker類:

var iss = InitialSessionState.CreateDefault(); 
iss.ImportPSModule(new[] { MsOnline }); 
iss.ThrowOnRunspaceOpenError = true; 
_runspace = RunspaceFactory.CreateRunspace(iss); 
_runspace.Open(); 
_invoker = new RunspaceInvoke(_runspace); 

我試過很多方法:

scriptText_ = "$newLicense = New-MsolLicenseOptions -AccountSkuId {1} -DisabledPlans SHAREPOINTWAC,MCOSTANDARD,SHAREPOINTENTERPRISE\n"+ 
"Set-MsolUserLicense -UserPrincipalName [email protected] -AddLicenses \"example:ENTERPRISEPACK\" -LicenseOptions $newLicense"); 

我用這個下面的方法來執行其他命令其完美的作品:

_invoker.Invoke(scriptText_); 

還有:

var pipeline = _runspace.CreatePipeline(); 
pipeline.Commands.AddScript(scriptText_); 
return pipeline.Invoke(); // and getting back the variable 

我也嘗試添加該變量在運行空間對象:

_runspace.SessionStateProxy.SetVariable ("newLicense", pipeline.Invoke()); 

但命令不起作用,並且不返回任何錯誤。 我不太瞭解PowerShell環境(我是這個初學者)。

在此先感謝您提供的所有幫助。

+0

你有沒有嘗試過寫變量PowerShell的命令的輸出,然後讀取'Invoke'的輸出? (這應該有助於識別變量是否進入腳本。) – Richard

+0

要輸出PS命令嗎?你會更清楚嗎?我試圖從沒有變量的命令中獲取PSObject,它可以工作。我有我的「LicenseOption」對象。因此,我試圖直接將它作爲參數添加,如下所示:'var cmd = new Command(「New-MsolLicenseOptions -AccountSkuId example:ENTERPRISEPACK -DisabledPlans SHAREPOINTWAC,MCOSTANDARD,SHAREPOINTENTERPRISE」,true); cmd.Parameters.Add(variableName_,variableValue_); pipeline.Commands.Add(CMD); var result = pipeline.Invoke();'失敗。我真的不明白C#如何正確處理變量(和參數btw)。 – Gnial0id

+0

我的意思是在被調用的命令中加入'$ myVariable'並檢查返回的值是否正確(即確認SetVariable正在工作)調試:當你的工具被限制*或者你正在假設什麼工作時當它不是*而後者是最有可能的。 – Richard

回答

3

我懷疑你遇到PowerShell引擎沒有顯示你的錯誤。試試這個辦法,而不是觀察非終止錯誤:

var ps = PowerShell.Create(); 
ps.AddScript(@"Get-ChildItem c:\xyzzy"); 
var results = ps.Invoke(); 
if (ps.HadErrors) 
{ 
    foreach (var errorRecord in ps.Streams.Error) 
    { 
     Console.WriteLine(errorRecord); 
    } 
} 
foreach (var result in results) 
{ 
    Console.WriteLine(result); 
}