Home > Blockchain >  Is there a better way to call this command with this optional argument?
Is there a better way to call this command with this optional argument?

Time:11-10

My PowerShell script takes an argument to indicate if the output should have a header so I currently do this:

if ($null -eq $noHeader) {
    Send-SQLDataToExcel -Connection $connection -mssqlserver -SQL $SQL -Path $output
} else {
    Send-SQLDataToExcel -Connection $connection -mssqlserver -SQL $SQL -Path $output -NoHeader
}

Is there a better way that doesn't repeat code?

Thank you.

CodePudding user response:

Yes, take a look at splatting to handle different parameter scenarios e.g.:

$splatHt = @{
    connection=$connection
    mssqlserver=$true
    sql=$sql
    path=$output
}
If ($noHeader){
    $splatHt.add('NoHeader',$true)
}

Send-SQLDataToExcel @splatHt

As the only difference currently is a SWITCH parameter you could also do this:

$header = $false
If ($noHeader){
    $header = $true
}
Send-SQLDataToExcel -Connection $connection -mssqlserver -SQL $SQL -Path $output -NoHeader:$header
  • Related