Changes between Version 3 and Version 4 of Programming/PowerShell/HowToPassCommandLineArgumentsBetweenScripts


Ignore:
Timestamp:
Feb 29, 2016, 4:57:24 AM (9 years ago)
Author:
Vijay Varadan
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • Programming/PowerShell/HowToPassCommandLineArgumentsBetweenScripts

    v3 v4  
    141141=== Solution ===
    142142
     143There are 2 solutions. The first uses !PowerShell splatting, available as of !PowerShell V2, but not easily found unless you use the term **`splatting`** in your search. The second involves manual expansion, which I prefer even though it involves more changes. The second method can also be used on the command line when piping the output of native programs. Program output raw strings rather than string arrays, since they don't care about the shell they're being invoked from.
     144
     145==== Solution 1: Using Splatting ====
     146Simply invoke the callees by prefixing the args array with an @ sign rather than the $ sign, like this (see comment marked as `CHANGE:`):
     147
     148**`push0.ps1`**
     149{{{#!powershell
     150# $args is the array of input arguments to any script
     151# Do some work here common to all projects
     152# like pushing code to the master repo for developer scripts, etc.
     153
     154# invoke project specific scripts here
     155# $Env:Project will be set to quake, doom or wolf
     156# call project specific push0 script if it exists
     157# and pass all arguments to it
     158$scriptName = $Env:Project + ".push0.ps1"
     159if (Test-Path $scriptName) {
     160    & $scriptName @args # CHANGE: use @args instead of $args
     161}
     162}}}
     163
     164**`quake.push0.ps1`** - no change
     165
     166**`doom.push0.ps1`** - no change
     167
     168**`wolf.push0.ps1`** - no change
     169
     170
     171==== Solution 2: Manual Expansion ====
    143172What we need to do in the callees, is check if the incoming $args has only 1 parameter and if it's an array. If so, then simply use `$args[0]` as the actual list of arguments and process it below.
    144173
     
    147176{{{#!powershell
    148177function UnwrapArguments($params) {
    149     $unwrapped = @()
    150     if ($params.Count -gt 0) {
    151         if ($params.Count -eq 1 -and $params[0].GetType().IsArray) {
    152             $unwrapped = $params[0]
    153         } else {
    154             $unwrapped = $params
    155         }
     178    $unwrapped = $params
     179    if ($params -and $params.Count -eq 1 -and $params[0].GetType().IsArray) {
     180        $unwrapped = $params[0]
    156181    }
    157182    return $unwrapped