Passing around command line $args in powershell , from function to function
# use the pipe, Luke!
file1.ps1
---------
$args | write-host
$args | .\file2.ps1
file2.ps1
---------
process { write-host $_ }
Related videos on Youtube
Admin
Updated on July 09, 2022Comments
-
Admin almost 2 years
This is a nasty issue I am facing. Wont be surprised if it has a simple solution, just that its eluding me.
I have 2 batch files which I have to convert to powershell scripts.
file1.bat --------- echo %1 echo %2 echo %3 file2.bat %* file2.bat -------- echo %1 echo %2 echo %3
On command line, I invoke this as C:> file1.bat one two three The output I see is as expected one two three one two three
(This is a crude code sample)
When I convert to Powershell, I have
file1.ps1 --------- Write-Host "args[0] " $args[0] Write-Host "args[1] " $args[1] Write-Host "args[2] " $args[2] . ./file2.ps1 $args file2.ps1 --------- Write-Host "args[0] " $args[0] Write-Host "args[1] " $args[1] Write-Host "args[2] " $args[2] When I invoke this on powershell command line, I get $> & file1.ps1 one two three args[0] one args[1] two args[2] three args[0] one two three args[1] args[2]
I understand this is because $args used in file1.ps is a System.Object[] instead of 3 strings.
I need a way to pass the $args received by file1.ps1 to file2.ps1, much the same way that is achieved by %* in .bat files.
I am afraid, the existing manner will break even if its a cross-function call, just the way its a cross-file call in my example.
Have tried a few combinations, but nothing works.
Kindly help. Would much appreciate it.