NB: @AnsgarWiechersの回答が推奨される回答です。
すなわち
function RunOtherScript($_oneParameter, $twoParameter) {
$cmd = "python -u otherScript.py --oneParameter $_oneParameter"
if ($twoParameter) { $cmd += " --twoParameter $twoParameter" }
ExecuteSSHCommand $cmd
}
以下は、純粋に学術的関心のために投稿されています。
これが解決策です。しかし、それは数字に対してのみ機能します/良いまたは推奨される解決策ではなく、実際には興味があるだけです:
oneParameter
(私は以下のように扱いtwoParameter
ます;oneParameter
そこにない場合、pythonの呼び出しはまだそれを指定しています(値が渡されていないだけです);twoParameter
そのパラメーターはpython呼び出しに表示されませんが、欠落している場合)。
cls
function RunOtherScript($_oneParameter, $twoParameter)
{
("python -u otherScript.py --oneParameter {0} {1:--twoParameter 0}" -f $_oneParameter, $twoParameter)
}
RunOtherScript
RunOtherScript "a"
RunOtherScript "a" 10
RunOtherScript "a" "10" # this doesn't work the way you'd want it to
出力
python -u otherScript.py --oneParameter
python -u otherScript.py --oneParameter a
python -u otherScript.py --oneParameter a --twoParameter 10
python -u otherScript.py --oneParameter a 10
別の代替:
これはハックではありませんが、より多くのコードが必要です。したがって、多くのパラメーターがある場合にのみ価値があります。
clear-host
function RunOtherScript{
[CmdletBinding()]
Param(
[parameter(Mandatory = $true)]
[string]$_oneParameter
,
[parameter(ValueFromRemainingArguments = $true)]
[String] $args
)
process {
[string]$cmd = "python -u otherScript.py"
$cmd = $cmd + " --oneParameter $_oneParameter"
$args | ?{$_ -ne ""} | %{ $cmd = $cmd + " --twoParameter $_" }
write-output $cmd #to show what we'd be executing
#ExecuteSSHCommand $cmd
}
}
RunOtherScript "one" "two" "three"
RunOtherScript "one" "two"
RunOtherScript "one"
出力:
python -u otherScript.py --oneParameter one --twoParameter two three
python -u otherScript.py --oneParameter one --twoParameter two
python -u otherScript.py --oneParameter one
または多くのパラメーターの場合:
clear-host
function RunOtherScript{
[CmdletBinding()]
Param(
[parameter(Mandatory = $true)]
[string]$_oneParameter
,
[parameter(ValueFromRemainingArguments = $true)]
[string[]]$arguments
)
begin {
[string[]]$optionalParams = 'twoParameter','threeParameter','fourParameter'
}
process {
[string]$cmd = "python -u otherScript.py"
$cmd = $cmd + " --oneParameter $_oneParameter"
[int]$i = -1
$arguments | ?{($_) -and (++$i -lt $optionalParams.Count)} | %{ $cmd = $cmd + " --" + $optionalParams[$i] + " " + $arguments[$i] }
write-output $cmd
#ExecuteSSHCommand $cmd
}
}
RunOtherScript "one" "two" "three" "four" "five"
RunOtherScript "one" "two" "three" "four"
RunOtherScript "one" "two" "three"
RunOtherScript "one" "two"
RunOtherScript "one"
出力:
python -u otherScript.py --oneParameter one --twoParameter two --threeParameter three --fourParameter four
python -u otherScript.py --oneParameter one --twoParameter two --threeParameter three --fourParameter four
python -u otherScript.py --oneParameter one --twoParameter two --threeParameter three
python -u otherScript.py --oneParameter one --twoParameter two
python -u otherScript.py --oneParameter one