英文:
powershell where-object changes type of psobject to pscustomobject - how to workaround?
问题
以下是翻译好的代码部分:
$test=@()
$new = New-Object PSObject
$new | Add-Member -type NoteProperty -name name -Value 'test'
$new | Add-Member -type NoteProperty -name nummer -Value "17580-10"
$new | Add-Member -type NoteProperty -name datum -Value "10.08.23"
$test += $new
$test
$test_filtered=@()
$test_filtered=$test | Where-Object {($_.nummer -match '175')}
输出部分:
PS C:\Users\cm> $test.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS C:\Users\cm> $test_filtered.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False PSCustomObject System.Object
希望这对你有所帮助。
英文:
Example Code:
$test=@()
$new = New-Object PSObject
$new | Add-Member -type NoteProperty -name name -Value 'test'
$new | Add-Member -type NoteProperty -name nummer -Value "17580-10"
$new | Add-Member -type NoteProperty -name datum -Value "10.08.23"
$test += $new
$test
$test_filtered=@()
$test_filtered=$test | Where-Object {($_.nummer -match '175')}
Output:
PS C:\Users\cm> $test.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS C:\Users\cm> $test_filtered.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False PSCustomObject System.Object
As you can see, the type get's changed. I need to keep the Object as it is (before). How to workaround that?
Thanks for any idea.
答案1
得分: 2
你正在用一个 psobject 覆盖了 Array 对象(Where-Object
返回一个单独的项目),如果你想保持 Array 类型,请将筛选后的数据结果添加到数组中。所以将这行代码改成:
$test_filtered += ($test | Where-Object {($_.nummer -match '175')})
PS C:\> $test.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS C:\> $test_filtered.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
英文:
You're overwriting the Array object with a psobject (the Where-Object
return a single item), if you want to keep the Array type, Add the filtered data results into the array. so change this line:
$test_filtered = $test | Where-Object {($_.nummer -match '175')}
to:
$test_filtered += ($test | Where-Object {($_.nummer -match '175')})
PS C:\> $test.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS C:\> $test_filtered.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论