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
You're assigning the result of
Add-Member
to a variable, not adding it to a property collection within$obj
.Instead of
Try this:
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:Here's a slightly modified version of your script:
However, since in your case you don't really need to save the output object in a new variable, you could also simply say:
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 theInputObject
parameter. Finally, return the object back to the pipeline by specifying thePassThru
switch on the lastAdd-Member
call:Alternatively, you could simplify the process with
New-Object's
-Property
parameter:Or by using
Select-Object
:As indicated by Enrico, Shay and Christian, you should specify the object on which
Add-Member
operates, either by piping the object toAdd-Member
or by explicitly specifying the object on theInputObject
parameter. When adding multiple members usingAdd-Member
I usually add thePassThru
switch to avoid repeating the InputObject and to provide a visual cue.Try like this: