Web Developer has created an API where if I can generate a JSON file, we can automatically keep an accurate record of printers on EACH of our Print servers.
His requirements are as follows:
“Make an array of servers in json with a property of “printer”, and have an array with all of the printers in the server in that array”
So I will have an array of Servers and from that array, I need to create a property for each element in the array. That is the part I am stuck on.
I can get create a list of Print server and iterate through each to get a list of the printers installed on each.
$PrintServers = ‘P1’,‘P2’, ‘P3’, ‘P4’, ‘P5’,‘P6’, ‘P9’
foreach ($Server in $PrintServers)
{
$Printers = Invoke-Command -ComputerName $Server -ScriptBlock { get-printer }
-Credential $Credential | Select-Object Name
}
I am stuck as to how to add a property to each element in the array and have it as a single property that is an array of printers.
I think I have it. If there are alternatives, I would be interested in knowing what they are.
$PrintServers = 'P1','P2', 'P3', 'P4', 'P5','P6', 'P9'
$HostedPrinters = @()
foreach ($Server in $PrintServers)
{
$Printers = Invoke-Command -ComputerName $Server -ScriptBlock{Get-Printer} -Credential $Credential | Select-Object Name
$prop = @{
Server = $Server
Printers = $Printers
}
$obj = New-Object -TypeName psobject -Property $prop
$HostedPrinters += $obj
#Write-Output $obj
}
$HostedPrinters | ConvertTo-Json
Hey Brian,
You could simplify your code a bit, and you’ll want to do the Get-Printer
property filtering on the remote computers - currently, the results from Get-Printer
on each remote computer includes the default property set, most of which you don’t need.
Instead, just run Invoke-Command
against the entire array of $PrinterServers
(rather than using foreach
loop), filter for only the printer Name, then pipe the final output to ConvertTo-Json
:
$PrintServers = 'P1','P2', 'P3', 'P4', 'P5','P6', 'P9'
$results = Invoke-Command -ComputerName $PrintServers -Credential $Credential -ScriptBlock {
[pscustomobject]@{
Server = $env:COMPUTERNAME
Printers = Get-Printer |
Select-Object -Property PortName, @{
Name = 'Printer'
Expression = { $_.Name }
}, DriverName
}
} | Select-Object -Property Server, Printers -ExcludeProperty PSComputerName, RunspaceId
$results | ConvertTo-Json
How would I accomplish including the DriverName and Portname in my JSON file?
What we need is a Json file that has two Headers “Server” and “Printers”. With the “Printers” Header, the value is an array of JSON objects.
Example:
[
{
“Server”: "P1,
“Printers”: [
{“Port”:"10.60.40.34,“Printer”:“Ahasn-BackOffice”,“Driver”;"HP Universal Printing PCL 5(v5.7.0)},
{…},
]
Running Get-Printer | Get-Member
shows the properties PortName
and DriverName
which can be included in the Get-Printer | Select-Object
pipeline with manipulating the Name
property to show as Printer
as per your sample. The code has been revised to reflect this.