【问题标题】:If statement not working showing correct results in foreach array [duplicate]如果语句不起作用,则在 foreach 数组中显示正确的结果 [重复]
【发布时间】:2019-01-25 20:42:45
【问题描述】:

我创建了一个带有if..else 语句的foreach 循环,该语句应该检查变量是否为空/空。一切似乎都很好。然而,尽管有些变量是空的,有些不是,但返回的结果都有一个结果。

我尝试在if..else 语句中使用不同的位,例如

if ([string]::IsNullOrWhiteSpace($password))

if ($password -eq $null)

if ($password.length -gt 2)

但我一点运气都没有。

我开始着手解决这个问题,以便快速找出哪些计算机没有 LAPS 来调查原因。问题已解决,但这个脚本仍然困扰着我,因为我无法理解我做错了什么。

这是我的代码,尝试使用ms-mcs-admpwd属性和LAPS内置get-admpwd,没有区别。

$computers = Get-ADComputer -Filter * -SearchBase $OU -Properties * |
             Select-Object Name, ms-mcs-admpwd

foreach ($computer in $computers) {
    $password = Get-ADComputer $computer.Name -Properties * |
                Select ms-mcs-admpwd

    if ($password) {
        Write-Host "LAPS password on $computer present"
    } else {
        Write-Host "LAPS password on $computer not present"
    }

    Write-Host $password
    Write-Host " "
}

这是结果:

@{Name=Computer1; 上的 LAPS 密码; ms-mcs-admpwd=} 存在 @{ms-mcs-admpwd=} @{Name=Computer2; 上的 LAPS 密码; ms-mcs-admpwd=8CG1]8,q.j} 存在 @{ms-mcs-admpwd=8CG1]8,q.j} @{Name=Computer3; 上的 LAPS 密码; ms-mcs-admpwd=P2v94d+05q} 存在 @{ms-mcs-admpwd=P2v94d+05q} @{Name=Computer4; 上的 LAPS 密码; ms-mcs-admpwd=} 存在 @{ms-mcs-admpwd=}

如您所见,Computer1 和 Computer4 没有 ms-mcs-admpwd 属性,但结果与 Computer2 和 Computer3 相同。

【问题讨论】:

  • 变量$computer 中的对象已经具有ms-mcs-admpwd 属性,因此无需为每台计算机执行另一个 AD 查询。使用$password = $computer.'ms-mcs-admpwd'$password = $computer | Select-Object -Expand ms-mcs-admpwd 将该属性的值分配给变量。

标签: arrays powershell if-statement foreach


【解决方案1】:
Get-ADComputer $computer.name -Properties * | Select ms-mcs-admpwd

正在返回一个对象,而不是我认为您正在寻找的字符串。 你需要$password.'ms-mcs-admpwd'

If($password.'ms-mcs-admpwd')
    {write-host "LAPS password on $computer present"}

Else {Write-host "LAPS password on $computer not present"}

Write-host $password.'ms-mcs-admpwd'

【讨论】:

  • 有道理 - 感谢贾斯汀的解释!
  • 请注意,要使点访问起作用,如果属性名称包含连字符或其他特殊字符,则必须将其放在引号中:$password.'ms-mcs-admpwd'
【解决方案2】:

您的问题是 $password 变量不为空、空或假,因此它始终被评估为真。对于编写的代码,您需要将评估更改为:

If($password.'ms-mcs-admpwd')
{write-host "LAPS password on $computer present"}

此外,不需要运行两次Get-ADComputer,因为 $computers 变量已经包含您需要的信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-01
    • 2013-05-26
    • 1970-01-01
    • 2021-02-11
    • 2018-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多