chocolatey-packages icon indicating copy to clipboard operation
chocolatey-packages copied to clipboard

Pass arguments via splatting rather than backticks

Open dtgm opened this issue 8 years ago • 2 comments

Same issue here as on chocolatey.org; command is not broken.

Install-ChocolateyPackage -PackageName "$packageName" -FileType "$installerType" -SilentArgs "$silentArgs" -Url "$url" -Url64bit "$url64" -ValidExitCodes $validExitCodes -Checksum "$checksum" -ChecksumType "$checksumType" -Checksum64 "$checksum64" -ChecksumType64 "$checksumType64"

Even if the command is broken, it's not pretty.

Install-ChocolateyPackage -PackageName "$packageName" -FileType "$installerType" 
-SilentArgs "$silentArgs" -Url "$url" -Url64bit "$url64" -ValidExitCodes $validExitCodes 
-Checksum "$checksum" -ChecksumType "$checksumType" -Checksum64 "$checksum64" 
-ChecksumType64 "$checksumType64"

Solution 1: break command with the line continuation character backtick `

Requires newline follow backtick

Install-ChocolateyPackage -PackageName "$packageName" `
                          -FileType "$installerType" `
                          -SilentArgs "$silentArgs" `
                          -Url "$url" `
                          -Url64bit "$url64" `
                          -ValidExitCodes $validExitCodes `
                          -Checksum "$checksum" `
                          -ChecksumType "$checksumType" `
                          -Checksum64 "$checksum64" `
                          -ChecksumType64 "$checksumType64"

Solution 2: use splatting man about_Splatting
Requires building a hashtable or array whereas Solution 1 is just a simple string.

$InstallChocolateyPackageParams = @{
    PackageName = "$packageName"
    FileType = "$installerType"
    SilentArgs = "$silentArgs"
    Url = "$url"
    Url64bit = "$url64"
    ValidExitCodes = $validExitCodes
    Checksum = "$checksum"
    ChecksumType = "$checksumType"
    Checksum64 = "$checksum64"
    ChecksumType64 = "$checksumType64"
}
Install-ChocolateyPackage @InstallChocolateyPackageParams

Possible issue: $validExitCodes is an array...problem?

^^ does not seem to be

$array = @("explorer", "svchost")
$params = @{Name = $array}
Get-Process @params

dtgm avatar Mar 14 '16 06:03 dtgm

Nevermind.

"SPLATTING COMMAND PARAMETERS [...] This feature is introduced in Windows PowerShell 3.0."

dtgm avatar Mar 14 '16 06:03 dtgm

Nevermind nevermind.

Tested in version 2 seems to work:

powershell.exe -Version 2
$array = @("explorer", "svchost")
$params = @{Name = $array}
Get-Process @params

dtgm avatar Mar 14 '16 06:03 dtgm

Splatting is the recommended way forward.

gep13 avatar Sep 12 '23 13:09 gep13