PowerShell 中函数调用的条件 [英] Condition with a function call in PowerShell
问题描述
这种语言真的很奇怪.我正在尝试执行一个函数并将其结果值用作条件.这是我的代码:
Something is really weird with this language. I'm trying to execute a function and use its result value as condition. This is my code:
function Get-Platform()
{
# Determine current Windows architecture (32/64 bit)
if ([System.Environment]::GetEnvironmentVariable("ProgramFiles(x86)") -ne $null)
{
echo "x64"
return "x64"
}
else
{
echo "x86"
return "x86"
}
}
if (Get-Platform -eq "x64")
{
echo "64 bit platform"
}
if (Get-Platform -eq "x86")
{
echo "32 bit platform"
}
预期的输出是这样的:
x64
64 bit platform
但实际输出是这样的:
64 bit platform
32 bit platform
这是怎么回事?如何解决这个问题?我在网上找不到任何在 if
条件中使用函数的例子.在Powershell中这可能吗?我使用的是 Windows 7,没有特殊设置,所以我有随附的任何 PS 版本.
What's going on here? How can this be fixed? I couldn't find any examples on the web that use functions inside an if
condition. Is that possible at all in Powershell? I'm on Windows 7 with no special setup, so I have whatever PS version comes with it.
推荐答案
如果要在条件中比较函数的返回值,则必须对函数调用进行分组(即放在括号中)或(如 ""
也不是 0
也不是 $null
,因此它的计算结果为 $true
,导致显示两条消息.
If you want to compare the return value of a function in a conditional, you must group the function call (i.e. put it in parentheses) or (as @FlorianGerhardt suggested) assign the return value of the function to a variable and use that variable in the conditional. Otherwise the comparison operator and the other operand would be passed as arguments to the function (where in your case they're silently discarded). Your function then returns a result that is neither ""
nor 0
nor $null
, so it evaluates to $true
, causing both messages to be displayed.
这应该可以满足您的要求:
This should do what you want:
...
if ( (Get-Platform) -eq 'x64' ) {
echo "64 bit platform"
}
...
顺便说一句,对于互斥的条件,您应该避免使用单独的 if
语句.对于平台检查 if..then..elseif
BTW, you should avoid using separate if
statements for conditions that are mutually exclusive. For a platform check an if..then..elseif
$platform = Get-Platform
if ($platform -eq "x64") {
...
} elseif ($platform -eq "x86") {
...
}
或 switch
语句
Switch (Get-Platform) {
"x86" { ... }
"x64" { ... }
}
会更合适.
我也会避免在函数内部回显.只需返回值并使用返回值执行任何可能需要的回显.函数内回显的任何内容也将返回给调用者.
I'd also avoid echoing inside the function. Just return the value and do any echoing that might be required in with the returned value. Anything echoed inside the function will also be returned to the caller.
最后一点:我个人宁愿不依赖特定文件夹或环境变量的存在来确定操作系统架构.使用 WMI 执行此任务让我觉得更可靠:
One last note: personally I'd rather not rely on the existence of a particular folder or environment variable for determining the operating system architecture. Using WMI for this task deems me a lot more reliable:
function Get-Platform {
return (gwmi Win32_OperatingSystem).OSArchitecture
}
此函数将返回一个字符串 "32-Bit"
或 "64-Bit"
,具体取决于操作系统架构.
This function will return a string "32-Bit"
or "64-Bit"
, depending on the operating system architecture.
这篇关于PowerShell 中函数调用的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!