Reputation: 1
I am attempting to write a short script that will get a list of all of the computers in the domain and then run Get-Printer on them to obtain a list of all of the installed printers on each machine.
To obtain the list of computers in the domain I would like to use "net view" so I tried
net view | ForEach-Object {Get-Printer -ComputerName $_}
But that does not work. Instead I just get a line of "spooler service is not reachable" for each PC in net view.
Manually entering the pc names into "Get-Printer" works perfectly and I actually wrote a working script that outputs the results of net view to a .txt file after searching for PC names in the text, then it reads each line from the text file and inputs them sequentially into "Get-Printer". But I would like to be able to expand upon this code to centrally manage the printers so I need to get this working from one line which I think is possible.
Can anyone explain what I am missing here? How does ForEach actually work in Powershell 4?
The following is my working code that writes to a file and then reads from it:
$PCs = net view /all | Select-String "\\"
$a = ForEach ($Line in $PCs)
{ $Line -Replace(" ","")
}
$a | Out-file -FilePath C:\Users\esmith\Desktop\test.txt -Encoding ascii
Get-content C:\Users\esmith\Desktop\test.txt | ForEach-Object {Get-Printer -cn $_} | Out-file -FilePath C:\Users\esmith\Desktop\output.txt
Upvotes: 0
Views: 1013
Reputation: 7625
net view
is a DOS command line, which returns text output. The PowerShell pipeline works on objects instead of text, so that does not combine well in this case. (Technically: strings are objects as well, but not the kind of objects that you expect here).
You can use the native PowerShell cmdlet Get-AdComputer
to obtain a list of the domain joined computers as PowerShell objects, which you can then feed into the pipeline.
Something like this should work:
Get-AdComputer -Filter * | ForEach-Object { Get-Printer -ComputerName $_.Name }
The Get-Printer
cmdlet does except pipeline input directly, so this should work as well (without the need for an explicit ForEach-Object):
Get-AdComputer -Filter * | Get-Printer
Upvotes: 1