Invoke-Command Error Handling

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 = {
                    Import-Module activedirectory
                    $NoOut = Get-ADUser $RemoteUsers | Select-Object Name,Samaccountname,Enabled,distinguishedname
                    $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

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.


$x = Invoke-Command -ComputerName comp1 -ScriptBlock {

Would set $x to 2.

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