When i export to a csv file, i get spaces on either side of a pipline that i need between two to diffrent values in the same cell. However i need to get rid of the spcaces before i import it to a system.
$DNs = @(
"OU=Personal,OU=Administration,OU=ccc,DC=aaa,DC=bbb,DC=se"
)
# Create empty array
$System_Users = @()
$Pipeline = "|";
# Loop through every DN
foreach ($DN in $DNs) {
$Users = Get-ADUser -SearchBase $DN -Filter * -Properties *
# Add users to array
$System_Users += $Users
}
# Create list
$System_Users | Select-Object `
@{Label = "First name"; Expression = { $_.givenName } },
@{Label = "Last name"; Expression = { $_.sn } },
@{Label = "User logon name"; Expression = { $_.sAMAccountName } },
@{Label = "Job Title"; Expression = { $_.Title } },
@{Label = "Department"; Expression = { $_.department } },
@{Label = "Company"; Expression = { $_.company } },
@{Label = "Manager"; Expression = { % { (Get-AdUser $_.Manager -Properties cn).cn } } },
@{Label = "E-mail"; Expression = { $_.Mail } },
@{Label = "Groups"; Expression = {$_.company, $Pipeline, $_.department } },
@{Label = "Account status"; Expression = { if (($_.Enabled -eq 'TRUE') ) { 'Enabled' } Else
{'Disabled'} } } |
# Export report to CSV file
#Export-Csv -Encoding UTF8 -path $Csvfile -NoTypeInformation -Delimiter ","
Export-Csv C:\Support\Script\System_Users\System_users_group.csv -NoTypeInformation -Delimiter "," - Encoding UTF8
The result looks like this (note the space on either side of the |
symbol in the field corresponding to the Groups
property):
"First name","Last name",...,"E-mail","Company | Department","Account status"
So any ideas how to remove the space before and after the pipeline?
$_.company, $Pipeline, $_.department
creates an array (via ,
, the comma operator), and when that array is implicitly stringified by Export-Csv
, its (stringified) elements are joined by a space as the separator.[1]
E.g., [string] ('a', '|', 'c')
(as well as "$('a', '|', 'c')"
) becomes 'a | c'
To get the desired representation (e.g, 'a|b'
), you must perform the stringification yourself, and there are two basic options:
As Olaf notes, you can use string concatenation with +
, the addition / string concatenation operator:
# NOTE:
# The [string] cast is only needed if $_.company isn't already a string.
[string] $_.company + $Pipeline + $_.department
Especially if there are three or more elements to join, use -join
, the string joining operator:
# NOTE:
# No [string] cast needed - all elements are implicitly stringified as needed.
$_.company, $_.department -join $Pipeline
[1] A space is the default separator; though it is rarely used (and best avoided), you can specify a different separator via the $OFS
preference variable.