Building and executing Command-String in Powershell

bash, parameter-passing, powershell, scripting

Solution

The simplest way to build up a set of arguments for a cmdlet is to use a hashtable and splatting:

$arguments = @{}
if( $BackgroundColor ) { $arguments.BackgroundColor = $BackgroundColor }
if( $ForegroundColor ) { $arguments.ForegroundColor = $ForegroundColor }
if( $NoNewline ) { $arguments.NoNewline = $NoNewline }
...

Write-Host text @arguments

The `@` in `Write-Host text @arguments` causes the values in `$arguments` to be applied to the parameters of the `Write-Host` cmdlet.

Problem

Good day! I stumbled across a small "problem" the other day... I have learned scripting through the linux-shell. There, one can construct commands through strings and exceute them as is. For Example: ``` #!bin/bash LS_ARGS='-lad' LS_CMD='ls' CMD="$LS_CMD $LS_ARGS /home" $CMD ``` But now I had to switch to 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 { ... } } ``` I think you know what I mean ;) Does anyone know a way of cutting this down like: ``` [string] $LS_CMD = 'Write-Host' [string] $LS_ARGS = '-BackgroundColor Green -NoNewLine' [string] $CMD = "$LS_CMD C:\temp $LS_ARGS" ``` Maybe I am trying to change something that should not be changed due to these stupid comparisons with other languages. The main reason I want to do this is because I am trying to reduce all the unnecessary conditions and passages from my scripts. Trying to make them more legible... Would be nice if someone could help me out here. Michael

Original source