For later powershell versions I can use the following with no issue:
$contents = Get-Content $path -raw
if ($contents -match $regex) {
$result = $matches[0]
}
But in powershell version 2, there's no -raw switch for Get-Content, but then without the -raw switch, the regex matching step always fails; $matches appear to be $null.
I am not sure of the inner workings of this "raw" parameter does, because Microsoft has provided a rather pathetic description of it on the respective documentation page, so I am not sure how to work around it.
Get-Content -Raw ignores newline characters and reads the contents of the file as one string.
Here are two methods that simulate the PowerShell 3.0+ -Raw functionality in PowerShell 2.0:
$contents = [System.IO.File]::ReadAllText($path)
if ($contents -match $regex) {
$result = $matches[0]
}
Or:
$contents = Get-Content -Path $path | Out-String
if ($contents -match $regex) {
$result = $matches[0]
}
As an alternative to @HAL9256, you can just join the strings together:
[string]$contents = @(Get-Content -Path $path) -join [Environment]::NewLine
Otherwise Get-Content returns an array of strings.
if ($contents -match $regex)
{
$result = $matches[0]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With