Afternoon on a friday, I am playing around with calling a powershell script from the cmd (similar to how Nuke does their call for "build") but I can't get an array parameter to correctly pass through and populate.
Here is the setup: I have 1 text file that is "masterswitch.cmd" and it is a one-liner that just calls the powershell script "masterswitch.ps1", all in the same directory.
powershell -ExecutionPolicy ByPass -NoProfile -File "%~dp0masterswitch.ps1" %*
The content of the "masterswitch.ps1" file is below.
[CmdletBinding()]
Param(
[Alias("n")]
[string]$meal,
[Alias("e")]
[array]$foods,
[Alias("h")]
[switch]$help
)
if ($Help){
powershell -command "get-help $PSCommandPath -Detailed"
exit
}
if ($meal.length -eq 0){
Write-Output "`n No meal to eat"
exit}
if ($foods.length -eq 0){
Write-Output "`n No foods where provided"
exit}
$i = 0
foreach ( $line in $foods) {
write "[$i] $line"
$i
}
open up a cmd window and cd to the directory where those 2 files exist. Then run masterswitch -h
works just fine. So does masterswitch -n lunch
with the expected notification that -foods is missing.
But when I run masterswitch -n dinner -e burritos,nachos
I get the output of [0] burritos,nachos
.
What I should get, and what I get when I run it from the powershell ide, is:
[0] burritos
[1] nachos
So what in my setup of the one-liner "masterswitch.cmd" file is blocking the ability for powershell to properly parse my passed array? (yes, I realize I can turn it into a string and parse myself)
Update
Clarity to the answer below. All that had to happen was change that one liner from -File
to -Command
. So the new one liner is
powershell -ExecutionPolicy ByPass -NoProfile -Command "%~dp0masterswitch.ps1" %*
CodePudding user response:
Does this code produce the results you are seeking?
PS C:\src\t> type .\foods.ps1
[CmdletBinding()]
Param(
[Alias("n")]
[string]$meal,
[Alias("e")]
[string[]]$foods,
[Alias("h")]
[switch]$help
)
if ($Help){
powershell -command "get-help $PSCommandPath -Detailed"
exit
}
if ($meal.length -eq 0){
Write-Output "`n No meal to eat"
exit}
if ($foods.length -eq 0){
Write-Output "`n No foods where provided"
exit}
$i = 0
foreach ( $line in $foods) {
write "[$i] $line"
$i
}
PS C:\src\t> .\foods.ps1 -n lunch -e apple,orange
[0] apple
[1] orange
Update:
16:00:45.10 C:\src\t
C:>powershell -NoLogo -NoProfile -Command ".\foods.ps1 -n lunch -e apple,orange"
[0] apple
[1] orange
Update 2:
16:01:17.45 C:\src\t
C:>powershell -NoLogo -NoProfile -Command "C:\src\t\foods.ps1 -n lunch -e apple,orange"
[0] apple
[1] orange