简体   繁体   English

Powershell中的正则表达式无法按预期工作

[英]Regex in powershell does not work as expected

I store the output of a defragmentation analysis in a variable, then I try to match a pattern to retrieve a number. 我将碎片整理分析的输出存储在变量中,然后尝试匹配模式以检索数字。

In this following online regex tester , it works fine but in powershell, String -match $pattern returns false. 下面的此在线正则表达式测试器中 ,它工作正常,但在powershell中, String -match $pattern返回false。

My code: 我的代码:

$result = Defrag C: /A /V | Out-String
echo $result
$pattern = "fragmenté[^.0-9]*([0-9]+)%"
$result -match $pattern

What am I doing wrong? 我究竟做错了什么?

I actually had no issue with your code. 实际上,您的代码没有问题。 I just needed to change the match to support my English output. 我只需要更改比赛以支持我的英语输出即可。 It is possible that Wolfgang Kluge is onto something about the whitespace. 沃尔夫冈·克鲁格Wolfgang Kluge )可能在空白上。 However if your output actually matches what you have in the regex tester than i'm not sure what this issue you are having. 但是,如果您的输出实际上与您在正则表达式测试器中的输出匹配,则我不确定您遇到的问题是什么。

For fun I propose this update to your code. 为了好玩,我建议对您的代码进行此更新。 This uses ConvertFrom-StringData . 这使用ConvertFrom-StringData I explain the code more in this answer . 我将在此答案中解释更多代码。

$defrag = Defrag C: /A /V | out-string
$hash = (($defrag -split "`r`n" | Where-Object{$_ -match "="}) -join "`r`n" | ConvertFrom-StringData)
$result = New-Object -TypeName PSCustomObject -Property $hash

$result."Quantité totale d'espace fragmenté"

This is of course assuming that your PowerShell is perfectly OK with the accents in the words. 当然,这是假定您的PowerShell完全正确,并带有单词中的重音符号。 On my ISE 3.0 that above code works. 在我的ISE 3.0上,上述代码有效。

Again... your code was working just fine for me in your question. 再次...您的代码对我来说对您的问题很好。 I also don't think the Out-String is required . 我也不认为Out-String必需的 I still get positive output. 我仍然得到积极的输出。 With Out-String I get extra output that includes the entire matched line. 使用Out-String我得到了包括整个匹配行的额外输出。 Else I just get a boolean. 否则我会得到一个布尔值。 In both (using the following code) I still get a result. 在两种方法中(使用以下代码),我仍然得到结果。

$result = Defrag C: /A /V #| Out-String
$pattern = "fragmented space[^.0-9]*([0-9]+)%"
$result -match $pattern
$Matches[1]

-match works as an array operator which changes how $result is treated. -match用作数组运算符, -match $result的处理方式。 With Out-String $result is a System.String and without it you get System.Object 使用Out-String $result是一个System.String ,没有它,您将获得System.Object

False Theory 虚假理论

The only way I can get the match to be False is if I am not running PowerShell as an administrator. 我可以使匹配为False的唯一方法是,如果我没有以管理员身份运行PowerShell。 That is important because if not you will get a message 这很重要,因为如果没有,您将收到一条消息

The disk defragmenter cannot start because you have insufficient priveleges to perform this operation. 磁盘碎片整理程序无法启动,因为您没有足够的特权来执行此操作。 (0x89000024) (0x89000024)

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

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