在PowerShell中创建自定义对象时出错

时间:2015-02-11 01:37:34

标签: windows powershell

尝试创建自定义对象并收到此错误。有没有人有关于如何处理这个问题的想法?谢谢

$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 个答案:

答案 0 :(得分:3)

如果字符串中有空格,请将它们放在引号中(单引号或双引号):

$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 ""

<强>更新

Per @ wannabeprogrammer的评论如下,实现上述目标的简便方法是:

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

...或者完全相同(即两个方法中的compare-object显示正在创建的对象之间没有差异。)

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

通过运行上面的代码片段查看我的意思,然后是以下内容:

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