在PowerShell中调用函数的条件

ygo*_*goe 8 powershell

这种语言真是奇怪.我正在尝试执行一个函数并将其结果值用作条件.这是我的代码:

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"
}
Run Code Online (Sandbox Code Playgroud)

预期的输出是这样的:

x64
64 bit platform
Run Code Online (Sandbox Code Playgroud)

但实际输出是这样的:

64 bit platform
32 bit platform
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?怎么解决这个问题?我在网上找不到任何在if条件中使用函数的例子.在Powershell中,这有可能吗?我在Windows 7上没有特殊的设置,所以我有任何PS版本附带它.

Ans*_*ers 19

如果要比较条件函数的返回值,则必须对函数调用进行分组(即将其置于括号中)或(如@FlorianGerhardt建议的那样)将函数的返回值赋给变量并使用该变量有条件的.否则,比较运算符和另一个操作数将作为参数传递给函数(在您的情况下,它们将被静默丢弃).然后,您的函数返回的结果既不是""也不0$null,因此它的计算结果为$true,导致两条消息都显示出来.

这应该做你想要的:

...
if ( (Get-Platform) -eq 'x64' ) {
  echo "64 bit platform"
}
...
Run Code Online (Sandbox Code Playgroud)

顺便说一句,你应该避免if对相互排斥的条件使用单独的语句.对于平台检查if..then..elseif

$platform = Get-Platform
if ($platform -eq "x64") {
  ...
} elseif ($platform -eq "x86") {
  ...
}
Run Code Online (Sandbox Code Playgroud)

switch声明

Switch (Get-Platform) {
  "x86" { ... }
  "x64" { ... }
}
Run Code Online (Sandbox Code Playgroud)

会更合适.

我也避免在函数内部回应.只需返回值并执行返回值可能需要的任何回显.函数内部回显的任何内容也将返回给调用者.

最后一点:个人而言,我宁愿不依赖于特定文件夹或环境变量的存在来确定操作系统架构.使用WMI执行此任务可以让我更加可靠:

function Get-Platform {
  return (gwmi Win32_OperatingSystem).OSArchitecture
}
Run Code Online (Sandbox Code Playgroud)

此函数将返回一个字符串"32-Bit""64-Bit",具体取决于操作系统体系结构.


fla*_*ayn 5

我认为您是在比较函数而不是函数结果。不知何故,回声在函数中无法按预期工作。我通常使用写主机。

这是我对您的问题的解决方案:

function Get-Platform()
{
    # Determine current Windows architecture (32/64 bit)
    if ([System.Environment]::GetEnvironmentVariable("ProgramFiles(x86)") -ne $null)
    {
        Write-Host("x64")
        return "x64"
    }
    else
    {
        Write-Host("x86")
        return "x86"
    }
}

$platform = Get-Platform

if ($platform -eq 'x64')
{
    echo "64 bit platform"
}

if ($platform -eq 'x86')
{
    echo "32 bit platform"
}
Run Code Online (Sandbox Code Playgroud)