我得到了以下 PowerShell 脚本:
[Other stuff]
try {
$Mailbox.user = $auser
$Mailbox.SetInfo()
$return = New-Object PSObject -property @{ReturnCode=0; ReturnString = "Account " + $Alias + " Quota successfully modified"}
$return
}
catch {
$return = New-Object PSObject -property @{ReturnCode=1;ReturnString="Account " + $Alias + " ERROR while Quota modification"}
$return
}
当我在 PowerShell 中调用该脚本时,我收到一个结果“配额成功修改”
现在我从 C# 中调用相同的脚本(具有相同的参数):
var result = powerShellProcessor.ExcecutePowerShell(scriptPath, parameters);
现在结果不包含一个 PSObject,而是两个。 result 中的第一个元素为 NULL,第二个元素包含“配额成功修改”(就像直接从 PowerShell 调用时的唯一结果)。
当然我可以只获取第二个结果,但我很好奇。怎么会发生这种事?
(ExecutePowerShell 使用 Powershell.Invoke
作为返回值:)
public Collection<PSObject> ExcecutePowerShell(string scriptFile, IEnumerable<PSCommandParameter> parameters)
{
PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
ps.AddScript(GetScriptContent(scriptFile));
Collection<CommandParameter> commandParameters = new Collection<CommandParameter>();
foreach (PSCommandParameter scriptParameter in parameters)
{
ps.AddParameter(scriptParameter.ParameterName, scriptParameter.ParameterValue);
}
Collection<PSObject> ret = ps.Invoke();
return ret
}
最佳答案
从您描述的症状来看,SetInfo()
方法似乎返回了一个 null 对象。你可以直接扔掉 null 对象;例如:
[Void] Mailbox.SetInfo()
我还建议该模式
$return = some_expression
$return
可以缩短为
some_expression
如果您需要在此时终止该函数,您可以编写
return some_expression
关于c# - 从 C# 调用 PowerShell : two PSObjects returned,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29493775/