Invoke-Command with Error Action and Error Variable

Welcome Forums General PowerShell Q&A Invoke-Command with Error Action and Error Variable

This topic contains 7 replies, has 3 voices, and was last updated by

 
Participant
1 week ago.

  • Author
    Posts
  • #176083

    Participant
    Topics: 1
    Replies: 3
    Points: 0
    Rank: Member

    Hi All,

    I'm relatively new to Powershell and i'm having some trouble with the below script I have put together with some help from a tutorial video.

    What I'm trying to create is a script that captures the TPM chip details of the computers I feed in to the $computers variable . With the details i would like it to Output the successful results into a csv and any computers that fail to connect or has issues it writes to .txt file.

    The successful entries seemed to be caught in the csv, however no errors are being created, yet i can see lots in the shell for computers that are offline etc...

    $Computers = Get-ADComputer -Filter * -SearchBase "OU=Laptops,OU=COMPUTERS,OU=COMPANY,DC=COMPANY,DC=local" | Select-Object -ExpandProperty name
    try {
        Invoke-Command -ComputerName $Computers {Get-tpm | Select-Object TpmPresent, TpmReady, ManufacturerVersionFull20 -ErrorAction Stop -ErrorVariable errors } | export-csv c:\tmp\success.csv -Append
    } catch {
        $computers | Out-File c:\tmp\errors.txt -Append
        Write-Warning "Error $computers : $errors"
    }

    Thank you in advance for any support and advice 🙂

    Thanks
    Anthony

  • #176122

    Participant
    Topics: 37
    Replies: 155
    Points: 479
    Helping Hand
    Rank: Contributor

    This worked for me....

    
    try {
    Invoke-Command -ComputerName (Get-ADComputer -Filter * -SearchBase "OU=Laptops,OU=COMPUTERS,OU=COMPANY,DC=COMPANY,DC=local" | `
    Select-Object -ExpandProperty name) -ScriptBlock {
    Get-tpm | Select-Object TpmPresent, TpmReady, ManufacturerVersionFull20 -ErrorAction Stop
    } -ErrorVariable errors | export-csv c:\temp\success.csv -NoTypeInformation -Append ; $errors | Out-File c:\temp\errors.txt
    } catch {
    Write-Warning "Error $_ "
    }
    
    
  • #176155

    Senior Moderator
    Topics: 8
    Replies: 1041
    Points: 3,438
    Helping Hand
    Rank: Community Hero

    well, I would do it this way, leaving the error handling for each node expecting a tabular output as result

    $Computers = Get-ADComputer -Filter * -SearchBase "OU=Laptops,OU=COMPUTERS,OU=COMPANY,DC=COMPANY,DC=local" | Select-Object -ExpandProperty name
    
        $Result = Invoke-Command -ComputerName $Computers {
                    Try{
                        Get-tpm | Select-Object TpmPresent, TpmReady, ManufacturerVersionFull20,@{E={'Ok'};L='Status'} -ErrorAction Stop
                    }
                    catch{
                        [PSCustomObject]@{
                            TpmPresent = $Null
                            TpmReady = $Null
                            ManufacturerVersionFull20 = $Null
                            Status = "Error: $_"
                        }
                    }
                    
                }
    
    
    $Result | Export-CSV C:\tmp\success.csv -NoTypeInformation
    
  • #176188

    Participant
    Topics: 1
    Replies: 3
    Points: 0
    Rank: Member

    Thank you both for your replies, i really appreciate it and its good to see two different methods to get the desired outcome.

    @Kvprasoon, i get an error for the script at line 17 of the script you kindly provided saying it is missing a catch or finally block. Do you know where this is best placed as i can see there are two try's, but only one catch, so i can see the outcome of the script 🙂

    Thank you again
    Anthony

    • #176197

      Senior Moderator
      Topics: 8
      Replies: 1041
      Points: 3,438
      Helping Hand
      Rank: Community Hero

      oops, that was an editing issue. outer most try block is not required, removed now.

    • #176203

      Participant
      Topics: 1
      Replies: 3
      Points: 0
      Rank: Member

      That's ok 🙂

      I have run the command and it is successfully exporting the TPM details of the machines it can connect to into the success.csv, however the failed/error ones appear to be vanishing into thin air? It shows the error in the shell saying it can't connect to the machine, but doesnt seem to put the detail into the csv? Is there any further information I can provide which might help?

      Thanks
      Anthony

  • #176212

    Senior Moderator
    Topics: 8
    Replies: 1041
    Points: 3,438
    Helping Hand
    Rank: Community Hero

    my bad, I didnt read the question properly. Above code will not handle the connectivity error messages.

    try this (untested from my end)

    $Success = Invoke-Command -ErrorAction SilentlyContinue -ErroVariable FailedNodeList -ComputerName $Computers -ScriptBlock {
                   Get-tpm | Select-Object @{E={$_env:ComputerName};L='Computer'},TpmPresent, TpmReady, ManufacturerVersionFull20,@{E={'Ok'};L='Status'} -ErrorAction Stop        
                }
    
    $Failed = $FailedNodeList | Select-Object -Property @{E={$_.TargetObject};L='Computer'},TpmPresent,TpmReady,ManufacturerVersionFull20  @{E={"Error: $_"};L='Status'}
    $Success,$Failed | Export-CSV C:\tmp\success.csv -NoTypeInformation
    
    • #176383

      Participant
      Topics: 1
      Replies: 3
      Points: 0
      Rank: Member

      I corrected the spelling for ErrorAction, but i get the below error when i run this.

      PS C:\Windows\system32> $computers = Get-ADComputer -Filter * -SearchBase "OU=Laptops,OU=COMPUTERS,OU=COMPANY,DC=COMPANY,DC=local" | Select-Object -ExpandProperty name
      $Success = Invoke-Command -ErrorAction SilentlyContinue -ErrorVariable FailedNodeList -ComputerName $Computers -ScriptBlock {
      Get-tpm | Select-Object @{E={$_env:ComputerName};L='Computer'},TpmPresent, TpmReady, ManufacturerVersionFull20,@{E={'Ok'};L='Status'} -ErrorAction Stop 
      }
      
      $Failed = $FailedNodeList | Select-Object -Property @{E={$_.TargetObject};L='Computer'},TpmPresent,TpmReady,ManufacturerVersionFull20 @{E={"Error: $_"};L='Status'}
      $Success,$Failed | Export-CSV C:\tmp\success.csv -NoTypeInformation
      
      ERROR BELOW
      Select-Object : A positional parameter cannot be found that accepts argument 'System.Collections.Hashtable'.
      At line:6 char:29
      + ... dNodeList | Select-Object -Property @{E={$_.TargetObject};L='Computer ...
      + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo : InvalidArgument: (:) [Select-Object], ParameterBindingException
      + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.SelectObjectCommand
      
      Export-Csv : Cannot bind argument to parameter 'InputObject' because it is null.
      At line:7 char:20
      + $Success,$Failed | Export-CSV C:\tmp\success.csv -NoTypeInformation
      + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo : InvalidData: (:) [Export-Csv], ParameterBindingValidationException
      + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ExportCsvCommand
      
      
      PS C:\Windows\system32>

      Thanks
      Anthony

You must be logged in to reply to this topic.