Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powershell Get-Content -raw alternative for PS Version 2

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.

like image 227
Lost Crotchet Avatar asked Jun 06 '26 08:06

Lost Crotchet


2 Answers

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]
}
like image 82
HAL9256 Avatar answered Jun 08 '26 21:06

HAL9256


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]
}
like image 25
Maximilian Burszley Avatar answered Jun 08 '26 21:06

Maximilian Burszley