Doug Doug - 2 months ago 6x
PowerShell Question

Append Member/Column to PSObject

I'm looking for a way to add an extra member to an object in PowerShell without creating a new object and looping.

Typically when I run a script it will be again a list of servers and I want to append some extra information against the data I'm returning but I can't find a way to do it without creating a new PSObject and looping through the existing object and adding the extra member row by row (simplified example below)

$FileList = get-childitem | Select-Object Name, DirectoryName
$FileListOBJ = @()

foreach ($item in $FileList)
$Temp = New-Object PSObject
$Temp | Add-Member NoteProperty ServerName "XServerName"
$Temp | Add-Member NoteProperty FileName $item.Name
$Temp | Add-Member NoteProperty Directory $item.DirectoryName

$FileListOBJ += $Temp


Is there a way to do it along these lines ...

get-childitem | Select-Object "ServerName", Name, DirectoryName

The above code creates the extra Member but I haven't been able to find a way to fill the additional member with the details I'm after.


Sure, you can use a calculated property (more about them here):

get-childitem | Select-Object @{l="ServerName"; e={"XServerName"}}, Name, DirectoryName