I ran into such a problem, I don't know how best to solve it. We have this script, determining the load on the CPU.
$pc = 'cmd'
try {$Connection = Test-Connection -ComputerName $pc -Count 2 -EA Stop}
catch {Write-Host "NO network connection to $PC" -fo Red; break}
try
{
$option = New-CimSessionOption -Protocol Dcom
$session = New-CimSession -ComputerName $pc -SessionOption $option -EA Stop
}
catch
{
try
{
$option = New-CimSessionOption -Protocol Wsman
$session = New-CimSession -ComputerName $pc -SessionOption $option -EA Stop
}
Catch {Write-Host "NOT connect to CimSession on $PC" -fo Red; break}
}
$ComputerSystem = Get-CimInstance -ClassName Win32_ComputerSystem -CimSession $session
$CpuCores = $ComputerSystem.NumberOfLogicalProcessors
Write-Host 'Please wait for CPU Usage data to be collect...' -fo Yellow
if (Get-Counter -ListSet * -ComputerName $pc | ? Paths -Match "\\Процесс\(\*\)"){$CounterPath = "\Процесс(*)\% загруженности процессора"}
else {$CounterPath = "\Process(*)\% Processor Time"}
$CPU_Usage_Counter = (Get-Counter -Counter $CounterPath -SampleInterval 1 -MaxSamples 5 -ComputerName $pc -EA SilentlyContinue).CounterSamples | ? CookedValue -ne 0 | group InstanceName
$CPU_Usage_Data = $CPU_Usage_Counter | select Name,@{N='CPU_Usage_%';E={[math]::Round(($_.Group | %{$_.CookedValue} | measure -Average).Average/$CpuCores,2)}}
$CPU_Usage_Data | ? Name -ne '_total' | sort 'CPU_Usage_%' -Des | ft -a
Write-Host "NumberOfLogicalProcessors: $CpuCores"
$check = Write-Host "CpuUsageProcess" ( [math]::Round((100 - (($CPU_Usage_Data | ? Name -eq 'idle').'CPU_Usage_%')),2) ) -fo Yellow
#####---------------------------------------------------------------------------------------------------------------------------------------------------
$status = (($check).CpuUsageProcess -gt 5)
if($status)
{
#Break
Write-Host -ForegroundColor Green 'if!'
}
else
{
Write-Host -ForegroundColor Red 'else!'
}
After execution, you need to extract the result of the "CpuUsageProcess" value and use it in the if / else condition

Write-Hostdoes not emit anything for you to capture with$check = Write-Host. Its purpose is to output text to the display. Your variable$checkwill therefore be$nulland thus you enter theelse {..}part.