简体   繁体   English

为什么 PowerShell -Replace 在每行前面添加一个额外的空白?

[英]Why PowerShell -Replace is adding an extra white space in front of each line?

I have a strange issue with -Replace in PowerShell.我对 PowerShell 中的-Replace有一个奇怪的问题。 This command output a list, filtered:这个命令 output 一个列表,过滤:

PS C:\> dism /image:pro /Get-ProvisionedAppxPackages | Select-String -Pattern 'Nome'

Nome visualizzato: Microsoft.BingWeather
Nome visualizzato: Microsoft.DesktopAppInstaller
Nome visualizzato: Microsoft.GetHelp
Nome visualizzato: Microsoft.Getstarted
Nome visualizzato: Microsoft.HEIFImageExtension
Nome visualizzato: Microsoft.Messaging
Nome visualizzato: Microsoft.Microsoft3DViewer
Nome visualizzato: Microsoft.MicrosoftOfficeHub
Nome visualizzato: Microsoft.MicrosoftSolitaireCollection
Nome visualizzato: Microsoft.MicrosoftStickyNotes
Nome visualizzato: Microsoft.MixedReality.Portal
Nome visualizzato: Microsoft.MSPaint

Output is quite clean (some empty lines, not show here). Output 很干净(一些空行,这里不显示)。

When i try to add | % {$_ -Replace '[^:]+:',''}当我尝试添加| % {$_ -Replace '[^:]+:',''} | % {$_ -Replace '[^:]+:',''} for replacing all following the : character, an extra space is added to the list, at the beginning of each line : | % {$_ -Replace '[^:]+:',''}用于替换所有后面的:字符,在每行的开头添加一个额外的空格到列表中

PS C:\> dism /image:pro /Get-ProvisionedAppxPackages | Select-String -Pattern 'Nome' | % {$_ -Replace '[^:]+:',''}
 Microsoft.BingWeather
 Microsoft.DesktopAppInstaller
 Microsoft.GetHelp
 Microsoft.Getstarted
 Microsoft.HEIFImageExtension
 Microsoft.Messaging
 Microsoft.Microsoft3DViewer
 Microsoft.MicrosoftOfficeHub
 Microsoft.MicrosoftSolitaireCollection
 Microsoft.MicrosoftStickyNotes
 Microsoft.MixedReality.Portal
 Microsoft.MSPaint

Why?为什么? I can easly fix with an extra | % {$_ -Replace '\s+',''}我可以很容易地用一个额外的修复| % {$_ -Replace '\s+',''} | % {$_ -Replace '\s+',''} , but I'd like to understand why it's happening. | % {$_ -Replace '\s+',''} ,但我想了解为什么会这样。

My comment as answer:我的评论作为答案:

The extra space you see is the space character directly behind the colon.您看到的额外空格是冒号后面的空格字符。 Your regex is not filtering that space out, so it remains as the first character in the output.您的正则表达式没有过滤掉那个空间,所以它仍然是 output 中的第一个字符。

Instead of | % {$_ -Replace '[^:]+:',''}而不是| % {$_ -Replace '[^:]+:',''} | % {$_ -Replace '[^:]+:',''} , use | % {$_ -replace '^.+:\s*'} | % {$_ -Replace '[^:]+:',''} ,使用| % {$_ -replace '^.+:\s*'} | % {$_ -replace '^.+:\s*'} to remove everything from the start up to and including the colon AND all possible extra space characters that folow that. | % {$_ -replace '^.+:\s*'}删除从开始到包括冒号在内的所有内容以及所有可能的额外空格字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM