如何从模块函数中获取退出代码值?

时间:2016-12-31 22:23:04

标签: powershell

我已将模块放入我的用户个人资料目录。组织要求我的主目录位于网络共享上。

16:06:09.74 \\COMPNAME\SHNAME\Users\lit  H:\My Documents\WindowsPowerShell\Modules\MyUtils
H:>type MyUtils.psm1
function MyFunc()
{
    [cmdletbinding()]
    Param()

    Write-Host "now from myfunc"
    return 8
}

Export-ModuleMember -Function MyFunc

当我运行MyFunc时,它似乎按预期运行。但是,$LASTEXITCODE始终为Null

PS C:\src\powershell> MyFunc
now from myfunc
8
PS C:\src\powershell> if (!$LASTEXITCODE) { Write-Host "LASTEXITCODE is null"}
LASTEXITCODE is null

如果我使用exit 8,那么我的互动主机会立即退出。使用$Host.SetShouldExit也是一样。

1 个答案:

答案 0 :(得分:0)

您可以尝试简单地将值分配给变量,例如:

[Int32] $myRc = myfunc;
$myRc;

控制台上出现'8'这一事实表明PowerShell正在采用 Out-Default ,因为您还没有告诉它如何处理该值。

当然,如果你想以PowerShell的方式做事,你在函数中使用 Write-Output ,如果该函数将用作cmdlet,而不是“帮助”函数。

祝你好运!

相关问题