I want to add an extra, empty column called RoleUserA*
to a CSV file, as attempted below. RoleUserA*
is not an AD Attribute.
Get-ADUser -Filter {Enabled -eq $true} -Properties * |
Select givenName, sn, displayname, samaccountname, RoleUserA*, title |
Export-Csv -Path "c:\tmp\users.csv" -NoTypeInformation -Encoding UTF8
Desired output:
givenName,sn,displayname,samaccountname,RoleUserA*,title
user01,sn1,User01 SN,user01,,specialist
user02,sn2,User02 SN,user02,,specialist
However, RoleUserA*
isn't being added as a column.
CodePudding user response:
The (positionally implied) -Property
parameter of the Select-Object
cmdlet (whose built-in alias is select
) interprets its arguments as wildcard expressions.
Therefore, RoleUserA*
looks for existing properties on the input objects whose name starts with RoleUserA
- and simply adds none to the output objects if no existing property matches; a simple example:
# Because 'bar*' matches no existing properties, it is *ignored*.
PS> [pscustomobject] @{ foo = 1 } | Select-Object foo, bar*
foo
---
1
While escaping *
as `*
('RoleUserA`*'
) so that it is used literally, as a (non-existent, in this case) property name, should be possible, it unfortunately isn't as of PowerShell 7.2.2,[1] as Mathias R. Jessen points out, and he also points to the solution that does work:
Use a calculated property, whose Name
entry (shortened to n
below) is always treated literally; using { $null }
as the Expression
(e
) entry script block creates the property with value $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
Note: In scripts used long-term, it's better to spell out the entry keys of the calculated property in full, i.e.:
@{ Name = 'RoleUserA*'; Expression = { $null } }
[1] This should be considered a bug, or at least needs documenting - see GitHub issue #17068
[2] Using just { }
- i.e. an 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 this answer for more information.
That said, in the context of converting to CSV this difference won't matter.