Powershell - 即使不满足条件,函数中的if语句也只使用第一个if语句

时间:2015-02-03 14:35:04

标签: function powershell if-statement credentials

我有以下功能,但无论我指定什么$ Server,即使不符合条件,也始终使用第一个if语句。这会导致使用错误的凭据。我尝试了很多次重写""在不同的地方,有和没有通配符,但我总是有同样的问题。它可能是一个简单的疏忽,但我无法发现它(powershell新手)。

$CredsFile = "C:\cred.txt"

Function DriveSpace {

$Server= "Myserver"

if ($Server -contains "application" -or "web") {
    $password = get-content $CredsFile | convertto-securestring
    $Cred = New-Object System.Management.Automation.PsCredential $Server"\username",$password
    $Output = Get-WmiObject win32_logicaldisk -computername $Server -Credential $cred| 
        Where-Object { $_.DriveType -eq 3 } | 
        Select SystemName,DeviceID,VolumeName,@{Name="Size(GB)";Expression={"{0:N2}" -f($_.size/1gb)}},@{Name="FreeSpace(GB)";Expression={"{0:N2}" -f($_.freespace/1gb)}} |Out-String
}
Else {      
    $Output = Get-WmiObject win32_logicaldisk -computername $Server| 
    Where-Object { $_.DriveType -eq 3 } | 
    Select SystemName,DeviceID,VolumeName,@{Name="Size(GB)";Expression={"{0:N2}" -f($_.size/1gb)}},@{Name="FreeSpace(GB)";Expression={"{0:N2}" -f($_.freespace/1gb)}} |Out-String
} 
$Output

}

任何建议都非常感谢

3 个答案:

答案 0 :(得分:2)

复合If语句将每个子句视为离散测试。

if ($Server -contains "application" -or "web")

将分别评估$Server -contains "application""web",然后将每个的结果转换为[bool]。 “Web”是一个非空字符串,在转换为[bool]时总是会返回$ true。

你需要让第二个子句成为一个完整的测试表达式,它将独立存在:

if ($Server -contains "application" -or $Server -contains "web")

答案 1 :(得分:1)

此声明的工作方式与您认为的不同。

$Server -contains "application" -or "web"

使用括号显示如何解释它。此声明与您的声明相同。

($Server -contains "application") -or ("web")

应该是

$Server -contains "application" -or $Server -contains "web"

正在发生的事情是这被视为两个陈述。

$Server -contains "application"

"web"

非null非空字符串将解析为True。这就是为什么你的原始陈述被解雇,因为"Web"本身就是一个真实的条件。如果它有助于考虑以下将返回"True"的语句。

If("web"){"True"}

答案 2 :(得分:1)

声明"web"总是如此。将您的陈述更改为if ($Server -contains "application" -or $Server -contains "web")