Antoine C.
Antoine C.

Reputation: 3962

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.

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?

Upvotes: 0

Views: 1664

Answers (1)

Matt
Matt

Reputation: 46730

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. 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. 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. On my ISE 3.0 that above code works.

Again... your code was working just fine for me in your question. I also don't think the Out-String is required. I still get positive output. With Out-String I get extra output that includes the entire matched line. 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. With Out-String $result is a System.String and without it you get 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. 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)

Upvotes: 1

Related Questions