Powershell - 在 CSV 文件中添加名为 RoleUserA* 的额外列

Powershell - add extra column called RoleUserA* inside CSV file

我想向 CSV 文件添加一个名为 RoleUserA* 的额外空列,如下所示。 RoleUserA* 不是 AD 属性。

Get-ADUser -Filter {Enabled -eq $true} -Properties * | 
  Select givenName, sn, displayname, samaccountname, RoleUserA*, title |
    Export-Csv -Path "c:\tmp\users.csv" -NoTypeInformation -Encoding UTF8

期望的输出:

givenName,sn,displayname,samaccountname,RoleUserA*,title
user01,sn1,User01 SN,user01,,specialist
user02,sn2,User02 SN,user02,,specialist

但是,RoleUserA* 未添加为列。

Select-Object cmdlet (whose built-in alias is select) interprets its arguments as wildcard expressions 的(隐含位置)-Property 参数。

因此,RoleUserA* 在名称 RoleUserA 开头的输入对象上查找 现有属性 -如果没有现有的 属性 匹配,只需将 none 添加到输出对象;一个简单的例子:

# Because 'bar*' matches no existing properties, it is *ignored*.
PS> [pscustomobject] @{ foo = 1 } | Select-Object foo, bar*

foo
---
  1

虽然 转义 *`* ('RoleUserA`*') 以便按字面意思使用 ,作为(non-existent,在这种情况下)属性 名称,应该 是可能的,不幸的是,从 PowerShell 7.2.2 开始,[1] 正如 Mathias R. Jessen 指出的那样,他还指出 确实 有效的解决方案:

使用 calculated property,其 Name 条目(在下面缩写为 n)始终按字面意思处理 ;使用 { $null } 作为 Expression (e) 入口脚本块创建 属性 值 $null:[1]

Get-ADUser -Filter 'Enabled -eq $true' -Properties * | 
  Select givenName, sn, displayname, samaccountname, @{n='RoleUserA*';e={ $null }}, title |
    Export-Csv -Path "c:\tmp\users.csv" -NoTypeInformation -Encoding UTF8

注意:在使用long-term的脚本中,最好将计算出的属性的输入键全拼出来,即:

@{ Name = 'RoleUserA*'; Expression = { $null } }

[1] 这应该被认为是一个错误,或者至少需要记录 - 参见 GitHub issue #17068

[2] 仅使用 { } - 即 empty script block, almost works the same, but it actually creates an "Automation Null" value (the System.Management.Automation.Internal.AutomationNull.Value singleton), which in expressions behaves the same as $null, but acts differently in a pipeline - see 以获取更多信息。 也就是说,在转换为 CSV 的上下文中,这种差异无关紧要。