当我导出到 csv 文件时,我在同一单元格中的两个不同值之间需要的管道两侧都有空格。但是,在将其导入系统之前,我需要删除这些空间。
$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
结果如下所示: 名字,"姓氏","用户登录名","职务","部门","公司","经理","电子邮件","公司 | 部门","帐户状态"
那么有什么想法如何消除管道前后的空间吗?
您可以删除字符周围的一个或多个空格
|
,如下所示:
PS> $str -replace " *\| *", "|"
这意味着:将与正则表达式
" *\| *"
匹配的模式替换为 "|"
。
$_.company, $Pipeline, $_.department
创建一个 array,当该数组被 Export-Csv
隐式stringified 时,其(字符串化)元素由 space 作为分隔符连接。[1]
例如,
[string] ('a', '|', 'c')
(以及"$('a', '|', 'c')"
)变成'a | c'
要获得所需的表示(例如,
'a|b'
),您必须自己执行字符串化,有两个基本选项:
正如Olaf所指出的,您可以将字符串连接与
+
(即加法/字符串连接运算符:)一起使用
# NOTE:
# The [string] cast is only needed if $_.company isn't already a string.
[string] $_.company + $Pipeline + $_.department
特别是如果要连接三个或更多元素,请使用
-join
,字符串连接运算符:
# NOTE:
# No [string] cast needed - all elements are implicitly stringified as needed.
$_.company, $_.department -join $Pipeline
[1] 空格是默认分隔符;虽然很少使用(最好避免),但您可以通过
$OFS
首选项变量指定不同的分隔符。