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