在 Powershell 中构建和执行命令字符串

Mic*_*rgl 4 bash powershell scripting parameter-passing

再会!

前几天我偶然发现了一个小“问题”......

我通过 linux-shell 学习了脚本编写。在那里,人们可以通过字符串构造命令并按原样执行它们。

例如:

#!bin/bash
LS_ARGS='-lad'  
LS_CMD='ls'

CMD="$LS_CMD $LS_ARGS /home"    
$CMD
Run Code Online (Sandbox Code Playgroud)

但现在我不得不切换到Windows powershell:

If ( $BackgroundColor ) {
    Write-Host -BackgroundColor $BackgroundColor
}
If ( $ForegroundColor ) {
    Write-Host -ForegroundColor $ForegroundColor
}
If ( $ForegroundColor -AND $BackgroundColor ) {
    Write-Host -ForegroundColor $ForegroundColor
               -BackgroundColor $BackgroundColor
}

If ( $NoNewline ) {
    If ( $BackgroundColor ) { ... }
    ElseIf ( $ForegroundColor ) { ... }
    ElseIf ( $ForegroundColor -AND $BackgroundColor ) { ... }
    Else { ... }
}
Run Code Online (Sandbox Code Playgroud)

我想你知道我的意思;)有谁知道一种减少这种情况的方法,例如:

[string] $LS_CMD  = 'Write-Host'
[string] $LS_ARGS = '-BackgroundColor Green -NoNewLine'
[string] $CMD     = "$LS_CMD C:\temp $LS_ARGS"
Run Code Online (Sandbox Code Playgroud)

也许我正在尝试改变一些由于与其他语言的愚蠢比较而不应该改变的东西。我想这样做的主要原因是因为我试图减少脚本中所有不必要的条件和段落。试图让它们更清晰......如果有人可以帮助我,那就太好了。

迈克尔

And*_*ndi 6

您可以构建一个字符串并使用以下命令执行Invoke-Expression

Invoke-Expression "$cmd $cmd_args"
Run Code Online (Sandbox Code Playgroud)