我正在使用 C# 开发 Office 365 插件并尝试此 PowerShell 命令:
$newLicense = New-MsolLicenseOptions -AccountSkuId example:ENTERPRISEPACK -DisabledPlans SHAREPOINTWAC,MCOSTANDARD,SHAREPOINTENTERPRISE
Set-MsolUserLicense -UserPrincipalName <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="077362747347627f666a776b622964686a" rel="noreferrer noopener nofollow">[email protected]</a> -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 <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6f1b0a1c1b2f0a170e021f030a410c0002" rel="noreferrer noopener nofollow">[email protected]</a> -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 对象中添加变量:
_runspace.SessionStateProxy.SetVariable ("newLicense", pipeline.Invoke());
但是该命令不起作用,并且没有返回任何错误。 我不太了解 PowerShell 环境(我是这方面的初学者)。
预先感谢您提供的所有帮助。
最佳答案
我怀疑您遇到了 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);
}
关于c# - PowerShell 变量和 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14440952/