Error when creating custom objects in PowerShell

4.7k Views Asked by At

I'm trying to create a custom object but receive error. Does anyone have ideas on how to deal with this issue?

$tempObject = New-Object System.Object
Add-Member -inputobject $tempObject -type NoteProperty -name Name -value ""
Add-Member -inputobject $tempObject -type NoteProperty -name account   status -value ""
Add-Member -inputobject $tempObject -type NoteProperty -name OU -value ""
Add-Member -inputobject $tempObject -type NoteProperty -name Last Logon -value ""

Add-Member : The SecondValue parameter is not necessary for a member of type "NoteProperty", and should not be specified. Do not specify the SecondValue parameter when you add members of this type.

1

There are 1 best solutions below

1
On

Where you have spaces in your strings, put them in quotes (single or double):

$tempObject = New-Object System.Object
Add-Member -inputobject $tempObject -type NoteProperty -name Name -value ""
Add-Member -inputobject $tempObject -type NoteProperty -name 'account   status' -value ""
Add-Member -inputobject $tempObject -type NoteProperty -name OU -value ""
Add-Member -inputobject $tempObject -type NoteProperty -name 'Last Logon' -value ""

Update

Per @wannabeprogrammer's comment below, a shorthand way of achieving the above would be:

$tempObject2 = [PSCustomObject]@{ 
    Name = "" ; 
    'Account Status' = "" ; 
    OU = "" ; 
    'Last Logon' = "" 
}

...or to get exactly the same (i.e. so a compare-object of the two methods shows no difference between the objects being created).

$tempObject3 = New-Object -TypeName PSObject -Property @{ 
    Name = "" ; 
    'Account Status' = "" ; 
    OU = "" ; 
    'Last Logon' = "" 
}

See what I mean by running the above snippets, then the below:

compare-object $tempObject $tempObject2
compare-object $tempObject $tempObject3
compare-object $tempObject2 $tempObject3