new-object PSObject导致空值表达式错误

时间:2016-11-14 17:45:29

标签: powershell null expression

我的PowerShell脚本:

Param([string]$Computers) #Must supply a comma seperated list of servers
$Threshold = 20 #Only show CPU over this number
$NoP = 20 #Number of processes to list
$NoRS = 4 #Number of result sets
If (! $Computers) { 
    Write-Host "Connection to server failed - please specify a server name." -ForegroundColor Red
    Break
} Else {
    $ComputerList = $Computers -Split " "#,[StringSplitOptions]'RemoveEmptyEntries')
}
$Credential = $host.ui.PromptForCredential("Need credentials", "Please enter your user name and password.", "", "NetBiosUserName")
If (! $Credential) { 
    Write-Host "Authentication failed - please verify your username and password." -ForegroundColor Red
    Break
}
$UserName = $Credential.Username
$Password = $Credential.GetNetworkCredential().Password
$CurrentDomain = "LDAP://" + ([ADSI]"").distinguishedName
$Domain = New-Object System.DirectoryServices.DirectoryEntry($CurrentDomain,$UserName,$Password)
If ($Domain.Name -eq $null){
    Write-Host "Authentication failed - please verify your username and password." -ForegroundColor Red
    Break
}
ForEach ($ComputerName In $ComputerList) {
    $LoadPercentage = $Processors.LoadPercentage
    If (!$LoadPercentage) {$LoadPercentage = 0}
    Write-Host "Server: $ComputerName (CPU load $LoadPercentage%)" -NoNewline
    $Processors = Get-WmiObject win32_processor -ComputerName $ComputerName -Credential $Credential
    $i = 1
    $TopProcess = @()
    $PercentComplete = 0
    Do{
        $PercentComplete = [Math]::Floor($i/$NoRS*100)
        Write-Progress -Activity $ComputerName -Status "$PercentComplete% Complete:" -PercentComplete $PercentComplete
        $ProcessList = gwmi Win32_PerfFormattedData_PerfProc_Process -ComputerName $ComputerName -Credential $Credential | 
            Select IDProcess,Name,PercentProcessorTime | 
            Where {$_.Name -ne "_Total" -and $_.Name -ne "Idle"} | 
            Sort PercentProcessorTime -Descending | 
            Select -First $NoP
        ForEach ($Process In $ProcessList) {
            $row = New-Object PSObject -Property @{
                Id = $Process.IDProcess
                Name = $Process.Name
                User = (gwmi Win32_Process -ComputerName $ComputerName -Credential $Credential | Where {$_.ProcessId -eq $Process.IDProcess}).GetOwner().User
                CPU = $Process.PercentProcessorTime/$Processors.NumberOfLogicalProcessors -f {P}
                Description = (gwmi Win32_Process -ComputerName $ComputerName -Credential $Credential | Where {$_.ProcessId -eq $Process.IDProcess}).Description 
            }
            $TopProcess += $row
        }
        $i++
    } While ($i -lt $NoRS + 1)
    Write-Progress -Activity $ComputerName -Completed
    $Group = $TopProcess | Where {$_.CPU -gt $Threshold} | Group 'ID' | Where Count -eq $NoRS
    If (!$Group) {
        Write-Host " has no processes persistently above $Threshold percent CPU usage."
    } Else {
        $Processes = @()
        ForEach ($Groupee In $Group) {
            $Ungroup = $Groupee | Select -ExpandProperty Group
            $CPU = 0
            ForEach ($ugr in $Ungroup) {
                $CPU += $ugr.CPU
            } 
            $row = new-object PSObject -Property @{
                Id = $Ungroup.Id | Select -First 1
                Name = $Ungroup.Name | Select -First 1
                CPU = $CPU/$NoRS
                User = $Ungroup.User | Select -First 1
                Description = $Ungroup.Description | Select -First 1
            }
            $Processes += $row
        }
        $Processes | Format-Table @{Expression={$_.User};Label="User Name";width=25},@{Expression={$_.CPU};Label="CPU";width=5},@{Expression={$_.Id};Label="ID";width=8},@{Expression={$_.Description};Label="Description";width=48}
    }
}

间歇性地给出以下错误:

您无法在空值表达式上调用方法。在C:\ Users \ Jasons1 \ CPUusage.ps1:41 char:4

  • $ row = new-object PSObject -Property @ {

  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    • CategoryInfo:InvalidOperation:(:) [],RuntimeException
    • FullyQualifiedErrorId:InvokeMethodOnNull

我无法理解,因为它在一个循环中,应该工作或跳过,因为有一个null的测试。

1 个答案:

答案 0 :(得分:2)

非常确定您的问题源自此行:

User = (gwmi Win32_Process -ComputerName $ComputerName -Credential $Credential | Where {$_.ProcessId -eq $Process.IDProcess}).GetOwner().User

具体来自.GetOwner()。您的where子句在循环中不能为该项找到匹配的进程。我意识到没有太多时间过去,但WMI查询不是那里最快的事情。

正在发生的事情很可能是先前在$ProcessList = gwmi Win32_PerfFormattedData_PerfProc_Process中查询过程的结果,然后是当您使用gwmi Win32_Process进程更改过程时查询的结果。你也需要考虑到这一点。时间已经过去,线程永远不会存在。

$queryResult = gwmi Win32_Process -ComputerName $ComputerName -Credential $Credential | Where {$_.ProcessId -eq $Process.IDProcess}
$owner = if($queryResult){$queryResult.GetOwner().User}else{"Process DNE"}
#...

User = $owner

不是很漂亮,但考虑到wmi查询返回null的可能性。