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?
Your splitting is working as expected, the issue is that
$Param1is constrained to be astringand arrays when coerced to string get joined by$OFS(a space by default).Basically:
If you want to re-use that variable name then you would need to constrain it again to be a
string[]: