Reputation: 17
I'm new to PowerShell and I'm attempting to write a script that will query AD for machine names, check which ones are responding and write the output into a file. So far I have this:
$computers = Get-ADComputer -filter {(Name -like "PC*")} | Select-Object -Property Name
foreach ($computer in $computers) {
if((Test-Connection -Cn $computer -BufferSize 16 -Count 1 -Ea 0 -Quiet)) {
"Machine $computer connected." | Out-File "out.txt" -Append
} else {
"Machine $computer not connected." | Out-File "out.txt" -Append
} #end if
} #end foreach
What I get in the output text file looks like the following:
...
Machine @{Name=PC-0649} not connected.
Machine @{Name=PC-1541} not connected.
Machine @{Name=PC-1574} not connected.
...
I think my problem lies with the Select-Object -Property Name
part of the first line. Running the debugger, it looks like PowerShell is formatting each iteration of $computer
to include the header line.
[DBG]: PS Y:\>> $computer
Name
----
PC-0649
What's the best way for me to strip out everything except the PC-#### part in this situation?
Upvotes: 0
Views: 5318
Reputation: 32697
I think your problem is that you still have a list of (truncated) computer objects in $computers
. Verify this by doing $computers[0].GetType()
. If you don't see String, it's not a string. :) Try this instead:
$computers = Get-ADComputer -filter {(Name -like "PC*")} |
Select-Object -ExpandProperty Name
Upvotes: 1