Invoke-Command Error Handling

Welcome Forums General PowerShell Q&A Invoke-Command Error Handling

Viewing 2 reply threads
  • Author
    Posts
    • #33859
      Participant
      Topics: 1
      Replies: 0
      Points: 0
      Rank: Member

      I am trying to run a script to query the folders inside “C:\Users” against Active Directory, this in order to delete any folder of a user who is not found in AD. Since I will be running this on ALL servers, I need to run Invoke-Command against a DC in order to query those users, but I am unable to CATCH error messages from within the Scriptblock, into a local file in the computer, this is the code I have so far (I DO get an output when running, I just dont know how to pass that output which is comming from the remote computer, to a text file in the local server where I am running the script):

      $RunLocation = "C:\Users"
      $ContLocation = Get-ChildItem -Path $RunLocation
      $ScriptLocation = "C:\Scripts\C_Drive"
      $BaseFile = New-Item (Join-Path $ScriptLocation "Base.txt") -ItemType file -Force
      $SetContent = Set-Content -Path (Join-Path $ScriptLocation "Base.txt") -Value $ContLocation
      $LogFile = New-Item (Join-Path $ScriptLocation "NotFound.txt") -ItemType file -Force
      $Users = gc $BaseFile
      $ScriptBlockCont = {
                      Param($RemoteUsers=$Users)
                      try 
                      {
                          Import-Module activedirectory
                          $NoOut = Get-ADUser $RemoteUsers | Select-Object Name,Samaccountname,Enabled,distinguishedname
                      }
                      catch
                      {
                          $ErrorOut = Write-Host "$RemoteUsers"
                       }
      }
      
      $l = 0
      Get-Content $BaseFile | ForEach {
                  Invoke-Command -ComputerName LAB-DC-01.LAB.COM -ScriptBlock $ScriptBlockCont -ArgumentList @($Users[$l])
                  $l = $l + 1
      }
      
      

      Please help me

    • #33884
      Participant
      Topics: 4
      Replies: 262
      Points: 61
      Rank: Member

      Hey Juan,

      If you prefix the Invoke-Command with a variable assignment, and make sure the script within the scriptblock produces output, you can do this.

      e.g.

      $x = Invoke-Command -ComputerName comp1 -ScriptBlock {
      1+1
      }
      

      Would set $x to 2.

    • #33914
      Participant
      Topics: 47
      Replies: 156
      Points: 42
      Rank: Member

      great explanation above, it took me an age to find any sort of ledgable answer to this elsewhere

Viewing 2 reply threads
  • The topic ‘Invoke-Command Error Handling’ is closed to new replies.