c# - 从 C# 调用 PowerShell : two PSObjects returned

标签 c# powershell

我得到了以下 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/

相关文章:

c# - 所有国家下拉列表

Azure Powershell - 跨 EA 中的多个订阅

powershell - 添加 SharePoint Powershell 管理单元时出错

powershell - 为什么在 PowerShell 中运行 "main"会打开我的鼠标属性

python - 获取远程主机列表的时间

c# - 什么时候可以在 Dispose 中调用 Finalize?

c# - Windows 10 uwp粘性后台服务?

c# - 使用嵌套母版页检查身份验证和授权的最佳方法是什么

c# - 是否可以在 Controller 内执行 ViewComponent 并将 HTML 存储为字符串

azure - Azure NSG 的备份机制