2013-04-10 85 views
6

这种语言的东西真的很奇怪。我试图执行一个函数并使用它的结果值作为条件。这是我的代码:在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" 
} 

预期输出是这样的:

x64 
64 bit platform 

但实际产量是这样的:

64 bit platform 
32 bit platform 

这是怎么回事?这怎么解决?我无法在网络上找到使用if条件中的函数的任何示例。在Powershell中可能吗?我在Windows 7上没有特别的设置,所以我拥有PS版本。

回答

16

如果你想一个函数的返回值进行比较的条件,你必须组函数调用(即把它放在括号)或(如建议使用@FlorianGerhardt)将函数的返回值赋给变量,并在条件中使用该变量。否则,比较运算符和另一个操作数将作为参数传递给函数(在这种情况下,它们将被无声地丢弃)。然后函数返回的结果既不是""也不是0也不是$null,因此它的计算结果为$true,导致显示这两个消息。

这应该做你想要什么:

... 
if ((Get-Platform) -eq 'x64') { 
    echo "64 bit platform" 
} 
... 

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

$platform = Get-Platform 
if ($platform -eq "x64") { 
    ... 
} elseif ($platform -eq "x86") { 
    ... 
} 

switch声明

Switch (Get-Platform) { 
    "x86" { ... } 
    "x64" { ... } 
} 

会更合适。

我也避免在函数内部回显。只需返回值并执行返回值中可能需要的任何回显。任何在函数内部回显的东西也会返回给调用者。

最后一点:个人而言,我宁愿不依赖特定文件夹或环境变量的存在来确定操作系统体系结构。使用WMI此任务认为我有很多更可靠:

function Get-Platform { 
    return (gwmi Win32_OperatingSystem).OSArchitecture 
} 

这个函数会返回一个字符串"32-Bit""64-Bit",这取决于操作系统的架构。

+0

谢谢您的完整解释。在函数名称周围使用圆括号确实可以调用函数,所以这看起来像是解决这些问题的通用方法。比使用其他变量名称更简单。 函数中的回显(由Write-Host替代为功能)仅用于跟踪目的。这是一个测试用例脚本。虽然我现在看到以下输出:“x64”,“64位平台”,“x64”。 WMI调用似乎返回一个本地化的字符串,对我来说它是“64位”。其他支票在其他地方看起来很广泛。 – ygoe 2013-04-11 07:38:21

+0

根据操作系统架构的不同,OSArchitecture会返回一个字符串“32位”或“64位”,因此您必须调整条件。 – 2013-04-11 11:19:49

3

我想你是在比较一个函数而不是函数的结果。另外某种方式回声不能按预期在函数中工作。我通常使用写主机。

这里是我的解决问题的方法:

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" 
}