Invoke-Command Error Handling

This topic contains 2 replies, has 3 voices, and was last updated by Profile photo of Mark Prior Mark Prior 11 months ago.

  • Author
    Posts
  • #33859

    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
    Profile photo of Tim Pringle
    Tim Pringle
    Participant

    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
    Profile photo of Mark Prior
    Mark Prior
    Participant

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

You must be logged in to reply to this topic.