First of all thank you for reading. I am new to Powershell so please forgive my ignorance. Also, this is my first time posting here.
Before I had this and it was working, however, it was crazy slow. Here is the initial script:
$RemoteComputers = (Get-ADComputer -Filter {OperatingSystem -Like 'Windows*'} -Property * -SearchBase "OU=Computers,OU=Domain".Name
ForEach ($Computer in $RemoteComputers)
{
$result = Invoke-Command -ErrorAction SilentlyContinue -ComputerName $Computer -ScriptBlock {Test-NetConnection -Port 135 server.domain.local}
[pscustomobject]@{
Target = $Computer
RemoteAddress = $result.RemoteAddress
SourceAddress = (Resolve-Dnsname $Computer -ErrorAction SilentlyContinue).IPAddress
Port = $result.RemotePort
Status = $result.tcpTestSucceeded
}
}
then ran it by doing this
.\ports.ps1 | Tee-Object -Variable result | Export-Csv ports-all.csv -NoTypeInformation
So below I have removed -Property * and cleaned it up. However no content in the CSV file. Can anyone tell me why when I run this there is no content in the csv file?
$RemoteComputers = (Get-ADComputer -Filter {OperatingSystem -Like 'Windows*'} -SearchBase "OU=Computers,OU=Domain").Name
$results = try {
Invoke-Command -ErrorAction Stop -ComputerName $RemoteComputers -ScriptBlock {
$Test = Test-NetConnection -Port 135 "server.domain.local"
[pscustomobject]@{
Target = $Env:COMPUTERNAME
RemoteAddress = $Test.RemoteAddress
SourceAddress = (Resolve-Dnsname $Env:COMPUTERNAME -ErrorAction SilentlyContinue).IPAddress
Port = $Test.RemotePort
Status = $Test.tcpTestSucceeded
}
}
}
catch {
Write-Output ([pscustomobject]@{
Target = $_.TargetObject
RemoteAddress = $null
SourceAddress = $null
Port = $null
Status = "Failed to connect"
})
}
$results | select target, remoteaddress, sourceaddress, port, status | export-csv file.csv
So this last script does not output anything to CSV. Why?