Powershell 计算与某个值匹配的数组元素

Powershell 计算与某个值匹配的数组元素

我有一个脚本,它根据 DOS 命令的输出构建具有属性的 PSCustomObject。数组构建正确,我可以通过将其转储到屏幕输出来检查它。但是,当我尝试按属性名称获取元素列表时,它给出零输出。以下示例:

$computers = @("computer1","computer2","computer3")
ForEach ($computer in $computers) {
    quser /server:$computer | Select-Object -Skip 1 | ForEach-Object {
    $CurrentLine = $_.Trim() -Replace '\s+',' ' -Split '\s'
    $HashProps = @{
        UserName = $CurrentLine[0]
        ComputerName = $computer
        timestamp = $timestamp
    }
$tempUserList = @(New-Object -TypeName PSCustomObject -Property $HashProps | Select-Object -Property UserName,Id,State,IdleTime,LogonTime,ComputerName | % { $_ -replace '","', ','} | % { $_ -replace "^`"",''} | % { $_ -replace "`"$",''})
$userList += $tempUserList
}
$serverCount = $userList | % { $_.UserName | where ($_.ComputerName -eq $computer) }
Write-Host "Server $computer has" $serverCount.Count "Users Logged On."

}

该代码的输出为:

Server computer1 has 0 Users Logged On.
Server computer2 has 0 Users Logged On.
Server computer3 has 0 Users Logged On.

如果我在循环完成后向脚本添加 $userList,我会得到以下输出:

@{UserName=user1; Id=2; State=Active; IdleTime=0; LogonTime=7/28/2016 7:43 AM; ComputerName=computer1}
@{UserName=user2; Id=3; State=Active; IdleTime=1:13; LogonTime=7/28/2016 11:31 AM; ComputerName=computer2}
@{UserName=user3; Id=4; State=Active; IdleTime=24692+13:29; LogonTime=7/28/2016 11:15 AM; ComputerName=computer3}

如何让脚本识别 ComputerName 属性并给出正确的登录次数?

答案1

我会更像这样去做(假设我正确理解了你的逻辑):

foreach ($computer in $computers) {
  $list = @()
  $quser = quser /server:$computer | Select-Object -Skip 1
  foreach ($q in $quser) {

    $item = New-Object -TypeName PSObject
    $item | Add-Member -MemberType NoteProperty -Name ComputerName -Value $computer
    $item | Add-Member -MemberType NoteProperty -Name UserName -Value $q.Trim().Replace('\s+',' ').Split(' ')[0]
    $item | Add-Member -MemberType NoteProperty -Name TimeStamp -Value (Get-Date)

    $list += $item
  }
  $count = ($list | Where-Object -FilterScript { $_.ComputerName -eq $computer }).Count
  Write-Output "Server $computer has $count users logged on"
}

相关内容