Powershell:函数中的 $LASTEXITCODE

标签 powershell powershell-2.0 powershell-ise

您好,我注意到以下代码片段出现了一些奇怪的行为

function test
{
    $LASTEXITCODE = $null
    ping asdfs
    Write-Host "Last exitcode: $LASTEXITCODE"
}

test
Write-Host "Last exitcode: $LASTEXITCODE"

输出是

Ping request could not find host asdfs. Please check the name and try again.
Last exitcode: 
Last exitcode: 1

为什么在 test() 函数中没有设置 $LASTEXITCODE?

这是我现在遇到的问题的概括,当我从函数内调用 Win32 .exe 时,$LASTEXITCODE 没有返回我期望从函数内返回的值

最佳答案

因为你不应该像那样设置自动变量。您正在创建一个局部变量并将其取消。删除 $LASTEXITCODE = $null 行,您将得到预期的结果。或者你可以这样做 $global:LASTEXITCODE = $null

关于Powershell:函数中的 $LASTEXITCODE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10943554/

相关文章:

powershell - 从快捷方式打开特定目录中的 Powershell

powershell - 通过WebClient在FTP凭据中使用特殊字符(斜杠)

xml - 如何使用 Powershell 从 XML 文件中删除特定标签?

powershell - 如何在PowerShell中获取详细的异常

html - 将空格转换为表格单元格

object - 如何从数组向 PowerShell 对象添加属性

powershell - 从后台作业获取输出

powershell - 在Powershell中打印有用的变量值(特别是涉及$ null/空字符串)

powershell - 从事件日志中的消息中提取帐户名称 - powershell