如何移除PowerShell数组拼接结果末尾的逗号?
解决PowerShell拼接结果末尾多逗号的问题
给你三种实用的修改方式,按需选择:
方法1:用数组收集后拼接(最推荐)
PowerShell处理这类元素拼接时,最省心的方式是先把所有要拼接的内容存到数组里,最后用-join ', '统一连接,自动避免末尾多余逗号:
clear $excludeList = 'choco*','kb*','dotnet*','netfx*','*.install*','*.portable*','vcredist*','packages*','lessmsi*' $appsInstalled = Get-ChildItem -Exclude $excludeList -Recurse -Path "C:\ProgramData\chocolatey\lib\*.nuspec" # 初始化数组存储每个应用的信息 $appList = @() Foreach ($app in $appsInstalled) { [xml]$XmlDocument = Get-Content $app.Fullname $appInfo = "$($XmlDocument.package.metadata.Title) v$($XmlDocument.package.metadata.Version)" $appList += $appInfo } # 用逗号加空格连接数组元素 $dataOut = $appList -join ', ' $dataOut
方法2:直接移除末尾的逗号和空格
如果不想改动循环逻辑,直接在最后对$dataOut做修剪,去掉末尾的, 即可:
clear $dataOut = '' $excludeList = 'choco*','kb*','dotnet*','netfx*','*.install*','*.portable*','vcredist*','packages*','lessmsi*' $appsInstalled = Get-ChildItem -Exclude $excludeList -Recurse -Path "C:\ProgramData\chocolatey\lib\*.nuspec" Foreach ($app in $appsInstalled) { [xml]$XmlDocument = Get-Content $app.Fullname $appsInstalled = $XmlDocument.package.metadata.Title + " v" +$XmlDocument.package.metadata.Version + ", " $dataOut = $dataOut + $appsInstalled } # 移除末尾的逗号和空格 $dataOut = $dataOut.TrimEnd(', ') $dataOut
方法3:循环内判断是否为最后一个元素
通过判断当前元素是不是集合里的最后一个,仅在非最后一个元素后添加逗号:
clear $dataOut = '' $excludeList = 'choco*','kb*','dotnet*','netfx*','*.install*','*.portable*','vcredist*','packages*','lessmsi*' $appsInstalled = Get-ChildItem -Exclude $excludeList -Recurse -Path "C:\ProgramData\chocolatey\lib\*.nuspec" $totalCount = $appsInstalled.Count $currentIndex = 0 Foreach ($app in $appsInstalled) { $currentIndex++ [xml]$XmlDocument = Get-Content $app.Fullname $appInfo = "$($XmlDocument.package.metadata.Title) v$($XmlDocument.package.metadata.Version)" # 仅非最后一个元素后添加逗号 if ($currentIndex -lt $totalCount) { $appInfo += ', ' } $dataOut += $appInfo } $dataOut
内容的提问来源于stack exchange,提问作者Darren
相关产品推荐
相关产品推荐

