简体   繁体   中英

convert powershell Psobject to New-object

I have made a function that returns a custom psobject , but when I am trying to use the " . " to get the properties of the object noting happens, also the pipe isnt working in this type of object.

There is a way to convert this object to the one that is created with the cmdlet New-object?

Why the new psobject have missing features?

$ObjectProperties = @{                   
    Users     = "admin"
    Computer  = "localhost"
    Error     = $false
}
$Objects += New-Object psobject -Property $ObjectProperties

# I am trying to use select this object like $objects.computer but doesnt work
$Objects.

$objectTest = New-Object Object
$objectTest | Add-Member NoteProperty error $false
$objectTest | Add-Member NoteProperty Computadores "localhost"
$objectTest | Add-Member NoteProperty Usuarios "admin"

#I need an object like this that can be easy managed 
$objectTest

I have tried converting it in this way but doesn't work

$objectCompu = $objects |select computer|Out-String
$objectError = $Objects |select error|Out-String
$objectUsers = $Objects |select users |Out-String

$objectTest = New-Object Object
$objectTest | Add-Member NoteProperty error $objectError
$objectTest | Add-Member NoteProperty Computadores $objectCompu
$objectTest | Add-Member NoteProperty Usuarios $objectUsers
$objectTest

(My comment as an answer)

$Object += __ is short for $Objects = $Objects + __ ;

So this line:

$Objects += New-Object psobject -Property $ObjectProperties

is expecting $Objects to be a list, and then add an item to the list. You haven't said whether it should be a list or not, so I guess you just want to make one object, and should use = instead of += :

$Objects = New-Object psobject -Property $ObjectProperties

Then you can do:

$Objects.Computer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM