提问人:user22694243 提问时间:10/6/2023 最后编辑:mklement0user22694243 更新时间:10/7/2023 访问量:61
Powershell,删除值之间的空格
Powershell, remove spaces between values
问:
当我导出到 csv 文件时,我在 pipline 的两侧获得空格,我需要在同一单元格中的两个到不同的值之间使用空格。但是,在将 spcaces 导入系统之前,我需要将其删除。
$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
结果如下所示(请注意与属性对应的字段中符号两侧的空间):|
Groups
"First name","Last name",...,"E-mail","Company | Department","Account status"
那么,有什么想法可以去除管道前后的空间呢?
答:
0赞
C. Aknesil
10/6/2023
#1
您可以删除字符周围的一个或多个空格,如下所示:|
PS> $str -replace " *\| *", "|"
这意味着:将与正则表达式匹配的模式替换为 。" *\| *"
"|"
评论
1赞
Olaf
10/6/2023
难道你不同意一开始就不要把不需要的空间放在那里比事后删除它们要好吗?😉
1赞
C. Aknesil
10/7/2023
@Olaf我同意。这是另一种方法。
1赞
mklement0
10/7/2023
#2
$_.company, $Pipeline, $_.department
创建一个数组(通过逗号运算符,
当该数组由 Export-Csv
隐式字符串化时,其(字符串化)元素由空格作为分隔符连接。[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
preference 变量指定不同的分隔符。
上一个:需要帮助将网格转换为字符串
评论
@{Label = "Groups"; Expression = { $_.company + '|' + $_.department } },
Groups
¯\_(ツ)_/¯