Powershell 如何从模块函数中获取退出代码值?
我已将模块放入我的用户配置文件目录中。组织要求我的主目录位于网络共享上Powershell 如何从模块函数中获取退出代码值?,powershell,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
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
如果我使用退出8,那么我的交互式主机将立即退出。使用
$Host.SetShouldExit
也一样,您可以尝试简单地将值赋给变量,例如:
[Int32] $myRc = myfunc;
$myRc;
“8”出现在控制台上的事实表明PowerShell正在使用Out Default,因为您没有告诉它如何处理该值
当然,如果您希望以PowerShell的方式执行操作,则应该在函数中使用写输出,如果该函数将用作cmdlet,而不是“helper”函数
祝你好运
$LASTEXITCODE
用于本机应用程序和.ps1
脚本,不用于函数。@PetSerAl-Ok。如果我打开PowerShell交互式主机并调用函数,是否有方法获取退出代码值?我必须调用cmdlet(.ps1)脚本才能获取函数返回值吗?同样,函数没有要获取的退出代码。若你们谈论的是管道输出,那个么你们需要把它分配给变量或者通过管道传递给下一个命令。