c# - PowerShell 变量和 C#

标签 c# variables powershell office365

我正在使用 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/

相关文章:

powershell - 何时可以使用方法以及何时使用命令行选项?

c# - 从 http 传输到 https asp.net c#

c# - 什么是 "native"和 "literal"关键字

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

带有 shell 命令和变量的 c makefile

powershell - 仅当以管理员身份运行时无法从 .bat 文件找到 powershell 文件的文件路径

c# - 如 Smartr 中所示提取社交资料信息

c# - 找不到类型或命名空间名称 'XmlDocument'。您是否缺少程序集引用?

bash - 如何在变量中存储标准错误

powershell - 使用Powershell更新Sharepoint Wiki页面的aspx