Passing multi-line string to PowerShell function parameter

43 Views Asked by At

I have the following code:

function Main{

    $param1 = @"
aaa
bbb
ccc
"@
    Test -Param1 $param1
}

function Test {
    param (
        [Parameter(Mandatory)][string]$Param1
    )

    Write-Host $Param1
    Write-Host $Param1.GetType()
    Write-Host $Param1[0]

    Write-Host '---------------------'
    $Param1 = [regex]::split($Param1.trim(), "\r?\n");
    $Param1 = @(foreach($line in $Param1) {
        if($line -match '^\s*$') {
            continue
        }
        $line
    })

    Write-Host $Param1
    Write-Host $Param1.GetType()
    Write-Host $Param1[0]
}

Main

Basically, I hope the function Test can accept a string parameter. If it's a multi-line string, then I'll split it by newline and make it an array. However, when I run it, I got this output:

aaa
bbb
ccc
System.String
a
---------------------
aaa bbb ccc
System.String
a

As you can see, it seems that the split function doesn't work as expected. The multi-line heredoc string for sure contains newline. But the split function are not able to split it by these newline characters. Where is the problem?

1

There are 1 best solutions below

0
Santiago Squarzon On

Your splitting is working as expected, the issue is that $Param1 is constrained to be a string and arrays when coerced to string get joined by $OFS (a space by default).

Basically:

[string] @(@'
aaa
bbb
ccc
'@ -split '\r?\n') # => aaa bbb ccc

If you want to re-use that variable name then you would need to constrain it again to be a string[]:

[string[]] $Param1 = @(foreach($line in $Param1) {