Brad
Brad

Reputation: 2185

Powershell Pattern Matching Regular Expression

On our servers we have files similar to the following:

C:\Documents and Settings\username\Application Data\Sun\Java\jre1.6.0_01\
C:\Documents and Settings\username\Application Data\Sun\Java\jre1.6.0_02\
C:\Documents and Settings\username\Application Data\Sun\Java\jre1.6.0_03\
etc

We don't need these files any more so I am trying to write a powershell script to delete them. For now I am limiting myself to one particular server and I have the following script:

 $path = "\\server\c$\Documents and Settings\"
 Get-ChildItem $path -Recurse | Where {$_.PSIsContainer -and ($_ -match '^jre1.6.0_')} | Remove-Item -Recurse -WhatIf

The problem is that the pattern I am using doesn't seem to be calling a match and I'm not sure what I'm doing wrong. I've tried several permutations and none seem to work. Can any regex gurus out there shed some light on what I might be doing wrong?

Thanks Brad

Upvotes: 2

Views: 2371

Answers (2)

CB.
CB.

Reputation: 60910

Try like this:

Get-ChildItem $path -Recurse -Force | ....

-Force looks for hidden or system files/folders also.

The "Application Data" folder is Hidden!

Upvotes: 3

Paolo Tedesco
Paolo Tedesco

Reputation: 57182

The regex is ok, I think you should try

$_.Name -match '^jre1.6.0_'

and not just

$_ -match '^jre1.6.0_'

Upvotes: 1

Related Questions