值为 "False" 的 Powershell WebAdministration IF 语句未按预期工作

Powershell WebAdministration IF Statement with value "False" not working as expected

我不确定我错过了什么。这个 powershell 的工作方式似乎与我的预期相反。有人知道为什么吗?

$loadUserProfileValue = Get-ItemProperty "IIS:\AppPools\.net v4.5" -Name processModel.loadUserProfile.Value
    Write-Host "Value: $loadUserProfileValue"
    IF ($loadUserProfileValue -eq "False") {
            Write-Host "Since Load User Profile is False, we will now set it to True"}

这是加载用户配置文件为真时我的输出

Value: True
Since Load User Profile is False, we will now set it to True

这是加载用户配置文件为 False 时的输出

Value: False

值被正确拾取。 变量 $loadUserProfileValue 是正确的。 IF 语句与我的预期相反。

我可以将它换成 -ne "True",它似乎有效...但为什么 -eq "False" 无效?

当 属性 可能 return 是布尔值时,您正在测试字符串值 false。 PowerShell 的 type-converter 可能是导致此问题不引发错误的原因。

更改您的测试以使用 $false 而不是 'false' 并查看是否可以解决问题。这是一篇很棒的文章:

https://devblogs.microsoft.com/powershell/boolean-values-and-operators/

编辑:您可以(并且应该)始终检查 return 对象的数据类型,您可以使用所有对象的继承方法 .gettype() 来执行此操作。对于您的代码,它将是:$loadUserProfileValue.gettype() 它会告诉您 returned 对象是否被转换为布尔值、字符串等

在 PowerShell 中,您可以像这样使用布尔数据类型:True = $trueFalse = $false.

在您的情况下,您必须将 False 更改为 $false

$loadUserProfileValue = Get-ItemProperty "IIS:\AppPools\.net v4.5" -Name processModel.loadUserProfile.Value
Write-Host "Value: $loadUserProfileValue"
IF ($loadUserProfileValue -eq $false) {
        Write-Host "Since Load User Profile is False, we will now set it to True"}

Stack Overflow 上已经有关于该主题的问题:Question