How do skip my for loop while WMI query delay response against remote server

PRAKASH MANOHARAN 0 Reputation points
2024-03-01T16:45:47.8166667+00:00

$stask = Get-ScheduledTask -CimSession $input1

$staskfinal = $stask | Select-Object TaskPath, TaskName, @{ Name = "Username"; Expression = { $.Principal.UserID } }, @{ Name = "LogonType"; Expression = { $.Principal.LogonType } } | Where {$_.username -like 'domain\serviceaccount*'}

$staskfinal |Export-Csv -Append .\schtaks.csv -nti

Windows for business Windows Server User experience PowerShell
{count} votes

1 answer

Sort by: Most helpful
  1. MotoX80 36,291 Reputation points
    2024-03-01T17:51:07.8366667+00:00

    If the server is not accessible, you can test the session like I did here.

    cls
    $computer = "xxxxxxxxxxxxxxx"   
    $User = ".\admin"
    $pswd = "admin"
    $PWord = ConvertTo-SecureString -String $pswd -AsPlainText -Force
    $Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
    $sess = New-CimSession  -ComputerName $computer  -Credential $Credential
    if ($sess) {
        $stask = Get-ScheduledTask -CimSession $sess
        $staskfinal = $stask | Select-Object TaskPath, TaskName, @{ Name = "Username"; 
            Expression = { $_.Principal.UserID } }, @{ Name = "LogonType";
            Expression = { $_.Principal.LogonType } }   | Where {$_.username -like 'admin*'}  # note user
        $staskfinal     # append to csv here
    } else {
        "Server is not accessible."
    }
    
    
    

    Or you could add a try/catch block.

    cls
    $computer = "xxxxxxxxxxxxxxx"   
    $User = ".\admin"
    $pswd = "admin"
    $PWord = ConvertTo-SecureString -String $pswd -AsPlainText -Force
    $Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
    $ErrorActionPreference = 'Stop'    # if we get an error, stop processing
    try {
        $sess = New-CimSession  -ComputerName $computer  -Credential $Credential
        $stask = Get-ScheduledTask -CimSession $sess
        $staskfinal = $stask | Select-Object TaskPath, TaskName, @{ Name = "Username"; 
            Expression = { $_.Principal.UserID } }, @{ Name = "LogonType";
            Expression = { $_.Principal.LogonType } }   | Where {$_.username -like 'admin*'}  # note user
        $staskfinal     # append to csv here
    } catch {
        "Server is not accessible."
    }
    

    Beyond that you will need to provide more details about this "WMI query delay".

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.