How can I add the device names that were not scanned (offline etc) by a PowerShell script

Viewed 35

Very very much a PowerShell newbie here I wanted a script to scan devices on the network and report on Local Admins. Found one out there and made some minor modifications to meet my needs - but I have one mod I cant work out how to do. Hoping someone out there will know a simple way to do it ?

The scrip below will read in a list of device names - scan them and output a dated report for all devices that are live and on-line. If the device is not accessible I get the following error on screen but nothing in the report.

I would like when it encounters an error that it writes to the report file - something along the lines of "$computor was not accessible!"

The code I am using is

$date = Get-Date -Format o | foreach {$_ -replace ":", "."}
ECHO "Starting scan"

$Result = @()

foreach($server in (gc .\servers.txt)){

$computer = [ADSI](”WinNT://” + $server + “,computer”)
$Group = $computer.psbase.children.find(”Administrators”)
$Filename = "c:\" + "LocalAdminAudit" + $date + ".txt"

function getAdmins
{
ECHO "SEARCHING FOR DEVICE"
$members = ($Group.psbase.invoke(”Members”) | %
{$_.GetType().InvokeMember(”Adspath”, ‘GetProperty’, $null, $_, $null)}) -
replace ('WinNT://DOMAIN/' + $server + '/'), '' -replace ('WinNT://DOMAIN/', 
'DOMAIN\') -replace ('WinNT://', '')
$members}
ECHO "READY TO WRITE OUTPUT"
$Result += Write-Output "SERVER: $server"
$Result += Write-Output ' '
$Result += ( getAdmins )
$Result += Write-Output '____________________________'
$Result += Write-Output ' '

ECHO "Record written"
}
# Added date run to report 
$result += Write-Output "Date Reported: $date"
$Result > $Filename
Invoke-Item $Filename

# replace "DOMAIN" with the domain name.



ECHO "Scan Complete"

And the on screen error when a machine is off line or otherwise doesn't respond is

Exception calling "Find" with "1" argument(s): "The network path was not found. " At \server\users\User.Name\Powershell Scripts\Get-Local-AdminsV3.ps1:1 0 char:40 + $Group = $computer.psbase.children.find <<<< (”Administrators”) + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : DotNetMethodException

I would like when it encounters an error that it writes to the report file - something along the lines of "$computor was not accessible!" - I am pretty sure there must be an easy way of doing this - but I cant work it out so any tips would be greatly appreciated

1 Answers
Related