Search code examples
objectpowershellwmipipeline

Using PowerShell's Add-Member results in an error


Why does the script below come up with the following error?

"Add-Member : Cannot process command because of one or more missing
mandatory parameters: InputObject.
+ $obj = Add-Member <<<< -MemberType NoteProperty -Name ComputerName -Value $ComputerName
+ CategoryInfo : InvalidArgument: (:) [Add-Member], ParameterBindingException
+ FullyQualifiedErrorId : MissingMandatoryParameter,Microsoft.PowerShell.Commands.AddMemberCommand"

Script

# Receives the computer name and stores the required results in $obj.
Function WorkerNetworkAdaptMacAddress {
    Param($ComputerName)

    $colItems = GWMI -cl "Win32_NetworkAdapterConfiguration" -name "root\CimV2" -comp $ComputerName -filter "IpEnabled = TRUE"
    $obj = New-Object -TypeName PSobject
    ForEach ($objItem in $colItems)
    {
        $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
    }
    Write-Output $obj
}

# Receives the computer name and passes it to WorkerNetworkAdaptMacAddress.

Function Get-NetworkAdaptMacAddress {
    begin {}
    process{
        WorkerNetworkAdaptMacAddress -computername $_
    }
    end {}
}

# Passes a computer name to get-networkAdaptMacAddress
'tbh00363' | Get-NetworkAdaptMacAddress

Solution

  • 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