lapingultah
lapingultah

Reputation: 316

PowerShell Functions and varying parameters

Early on in my script I have check to define whether a parameter "-Silent" was used when running the script. The idea is to have zero output from the script if it was and it will be checked on every Write-Host entry I have later. It seems a bit heavy to make if-else statements on every single Write-Host I have, so I decided to go with a function - something like this:

Function Silent-Write ([string]$arg1)
    {
        if ($silent -eq $false) {
            if ($args -ieq "-nonewline") {
                Write-Host "$arg1" -NoNewLine
            }
        elseif ($args -ieq "-foregroundcolor") {
            Write-Host "$arg1" -ForegroundColor $args
            }
        else {
            Write-Host "$arg1"
        }
    }
}

Silent-Write -ForegroundColor red "hello"

This is not working, but you get the idea; besides passing the text I want to output, Silent-Write function should also take other Write-Host arguments into consideration. Quite simple issue I believe, but something I cannot figure out with the knowledge of functions I have.

Upvotes: 0

Views: 116

Answers (1)

user4003407
user4003407

Reputation: 22122

In PowerShell V3 you can use splatting:

Function Silent-Write
{
    if (!$silent) {
        Write-Host @args
    }
}

Silent-Write -ForegroundColor red "hello"

Upvotes: 2

Related Questions