Powershell从数据表更改输出对象名称
我正在将数据表中的几个对象输出到 .csv 文件,并希望更改对象名称。
这工作正常:
$dataset.tables[0] | select-object System.ItemName, System.ItemPathDisplay | Export-Csv -Path D:\SEARCH_RESULT.csv -NoTypeInformation
但是我想将 System.ItemName 更改为 SKU 并尝试了以下操作:
$dataset.tables[0] | select-object @{N='SKU';E={$_.System.ItemName}}, System.ItemPathDisplay | Export-Csv -Path D:\SEARCH_RESULT.csv -NoTypeInformation
这给出了正确的列标题但空白行。所以尝试了这个,它给出了行,但它们都说 SYSTEM.ITEMNAME:
$dataset.tables[0] | select-object @{N='SKU';E={$dataset.tables[0].Columns['SYSTEM.ITEMNAME']}}, System.ItemPathDisplay | Export-Csv -Path D:\SEARCH_RESULT.csv -NoTypeInformation
显然我没有正确引用该对象。非常感谢任何帮助。
I'm outputting a couple of objects from a data table to a .csv file and wanted to change the object names.
This works fine:
$dataset.tables[0] | select-object System.ItemName, System.ItemPathDisplay | Export-Csv -Path D:\SEARCH_RESULT.csv -NoTypeInformation
However I'd like to change System.ItemName to SKU and have tried the following:
$dataset.tables[0] | select-object @{N='SKU';E={$_.System.ItemName}}, System.ItemPathDisplay | Export-Csv -Path D:\SEARCH_RESULT.csv -NoTypeInformation
This gives the right column heading but blank rows. So tried this which give rows but they all say SYSTEM.ITEMNAME:
$dataset.tables[0] | select-object @{N='SKU';E={$dataset.tables[0].Columns['SYSTEM.ITEMNAME']}}, System.ItemPathDisplay | Export-Csv -Path D:\SEARCH_RESULT.csv -NoTypeInformation
Clearly I'm not referencing the object correctly. Any help greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将
$_.System.ItemName
更改为$_.'System.ItemName'
您的属性名称是
System.ItemName
,并且如果属性名称本身包含.
,必须引用 - 否则,PowerShell 将其解释为嵌套 属性访问也就是说,
$_.System.ItemName
首先在名为System
的对象$_
上查找属性,然后查找ItemName
属性第一个财产的价值;访问不存在的属性时,PowerShell 默认为$null
。将此与使用
System.ItemName
作为传递给Select-Object
cmdlet,其中参数是始终解释为单个属性名称(无论您是否引用它)。换句话说:
Select-Object
不直接支持嵌套属性访问,但您可以通过计算属性,如您的方法所示。Change
$_.System.ItemName
to$_.'System.ItemName'
Your property name is
System.ItemName
, and if a property name itself contains.
, it must be quoted - otherwise, PowerShell interprets it as a nested property accessThat is,
$_.System.ItemName
looks for a property on object$_
namedSystem
first, and then for anItemName
property on the first property's value; PowerShell defaults to$null
when accessing non-existent properties.Contrast this with the use of
System.ItemName
as an argument passed to the (positionally implied)-Property
parameter of theSelect-Object
cmdlet, where the argument is always interpreted as a single property name (whether you quote it or not).In other words:
Select-Object
doesn't directly support nested property access, but you can do it via a calculated property, as in your approach.