Alright, this is driving me nuts because my regex is working on Rubular, but PowerShell is not working as I expect.
- I did a Get-ChildItem on a network directory and then directed the output into a txt file.
- I went to remove the directory info from the text file that appears like the following:

- When I use PowerShell to try and write a regex to remove the Directory info, I run into some problems.
When I use:
$var = Get-Contnet "file path"
$var -match "Directory.*"
PowerShell grabs the text I am looking for, BUT it doesn’t grab the text that starts on a new line, I get:
Directory: \\Drive\Unit\Proposals\Names\Location\crazy folder path\even crazier folder path\unbelievable folder path\
So… when I use:
$var -match "Directory.*\n.*"
I get nothing…
When I try this on Rublar it works fine, what am I missing here? Any help would be great, thanks!
Filburt’s answer is a good one, and it doesn’t look like regular expressions are the best tool to use here. However, you bumped into an issue that may cause confusion again down the road. The issue here is that the variable you populated with
Get-Contentis not a multi-line string. It is an array of strings:When you run a regex match against
$var, it matches against each object in the array (each line in the file) individually. It can’t match past the end of a line because the next line is a new object.One workaround here is to flatten that array of strings down into a single string like this:
In Powershell it can sometimes be tricky to tell when you’re dealing with a single String object versus an array of Strings. If you output them to the console they appear identical. In those cases,
GetType()andOut-Stringcan be useful tools.Edit: As of Powershell 3.0, the
Filesystemprovider includes a-Rawswitch forGet-Content. That switch instructsGet-Contentto read the file all at once without splitting it into chunks. It is significantly quicker than using theOut-Stringworkaround, because it doesn’t waste time pulling pieces apart only to put them back together again.