Using PowerShell's Add-Member results in an error Using PowerShell's Add-Member results in an error powershell powershell

Using PowerShell's Add-Member results in an error


You need to move the PSObject creation into the loop. Otherwise, you'll get errors that the properties already exist on the object.

Secondly, you need to tell Add-Member on which object to operate. You do it either by piping the object to the cmdlet or by specifying it on the InputObject parameter. Finally, return the object back to the pipeline by specifying the PassThru switch on the last Add-Member call:

ForEach ($objItem in $colItems){    $obj = New-Object -TypeName PSobject    Add-Member -InputObject $obj -MemberType NoteProperty -Name ComputerName -Value $ComputerName    Add-Member -InputObject $obj -MemberType NoteProperty -Name MacAddress -Value $objItem.MacAddress    Add-Member -InputObject $obj -MemberType NoteProperty -Name IPAddress -Value $objitem.IpAddress -PassThru}

Alternatively, you could simplify the process with New-Object's -Property parameter:

Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $ComputerName -Filter "IpEnabled=TRUE" | Foreach-Object {    New-Object -TypeName PSobject -Property @{        ComputerName=$ComputerName        MacAddress=$_.MacAddress        IPAddress=$_.IpAddress    }}

Or by using Select-Object:

Get-WmiObject ... | Select-Object @{n='ComputerName';e={$_.__SERVER}},MacAddress,IpAddress


First you need to specify the input object to which the property should be added by piping it to the Add-Member cmdlet.
Then, if you want the cmdlet to return the modified object, you should invoke it with the -PassThru argument:

When you use the PassThru parameter, Add-Member returns the newly-extended object. Otherwise, this cmdlet does not generate any output.

Here's a slightly modified version of your script:

$obj = $objItem | Add-Member -MemberType NoteProperty -Name ComputerName -Value $ComputerName -PassThru

However, since in your case you don't really need to save the output object in a new variable, you could also simply say:

$obj | Add-Member -MemberType NoteProperty -Name ComputerName -Value $ComputerName


Try like this:

$objcol = @()ForEach ($objItem in $colItems){    $obj = New-Object System.Object    $obj | Add-Member -MemberType NoteProperty -Name ComputerName -Value $ComputerName    $obj | Add-Member -MemberType NoteProperty -Name MacAddress -Value $objItem.MacAddress    $obj | Add-Member -MemberType NoteProperty -Name IPAdress -Value $objitem.IpAddress    $objcol += $obj}Write-Output $objcol