Powershell: add an item to a collection

Is it possible to add an item to a collection in PowerShell (I'm not sure if I'm using the correct terms here).  Let me give an example:

I want to get a list of all the servers in our environment, and then add another server name to the list along with a tag on whether it's enabled or not.

So I run this command:
$AllServers = Get-ADComputer -Filter * -Properties "OperatingSystem" | Where-Object {$_.OperatingSystem -like "*Server*"} | Select Name, Enabled | Sort-Object Name

Then I want to add a server with a Name of "Server A" and an Enabled value of $false to the $AllServers variable.

How do I accomplish this?

Thanks!  Greg.
malcolm29Asked:
Who is Participating?
 
oBdACommented:
You can always add items to a Powershell array using the += operator:
$a = @()
$a += 'a'
$a += 'b'
$a

Open in new window

So you could use something like the following.
The @() around the first command will make sure that $AllServers will be an array, even if only one element is returned by Get-ADComputer.
The last line generates a custom object with the two properties and adds it to the array.
$AllServers = @(
	Get-ADComputer -Filter * -Properties "OperatingSystem" |
		Where-Object {$_.OperatingSystem -like "*Server*"} |
		Select-Object -Property Name, Enabled |
		Sort-Object Name
)
$AllServers += '' | Select-Object -Property @{n='Name'; e={'ServerA'}}, @{n='Enabled'; e={$false}}

Open in new window

Or if you want the added server not at the end of the array, but at its sorted position:
$AllServers = $(
	Get-ADComputer -Filter * -Properties "OperatingSystem" |
		Where-Object {$_.OperatingSystem -like "*Server*"} |
		Select-Object -Property Name, Enabled
	'' | Select-Object -Property @{n='Name'; e={'ServerA'}}, @{n='Enabled'; e={$false}}
) | Sort-Object Name

Open in new window

0
 
malcolm29Author Commented:
Thank you!  This worked GREAT!  And your thoughtfulness in providing two options allowed me to much better understand how PowerShell does this.  Thank you!  Greg.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.