powershellstart-process

Using start-process in a loop, where some programs will have arguments and some don't; Way to not have if $Arguments -ne $null


I have the below code line, in a script that iterates through things to install from a repository. Some things have arguments, some don't. Have come across one that doesn't, and trying to avoid having the same command more or less duplicated (along with all the error checking, etc) in a for...else command. Is there anyway to have start-process work with a $null/empty variable specified after -argumentlist that I am not thinking about?

for($i=0; $i -lt $Installs.count; $i++)
{
  $Arguments = $($Installs[$i].path)

  start-process -filepath $Path -argumentlist $Arguments -wait
}

Solution

  • However, the splatting technique described in Santiago's answer alone is not enough for a robust solution:

    Therefore, use the following:

    for ($i = 0; $i -lt $Installs.count; $i++)
    {
      # Create a hashtable for splatting that originally just contains
      # a value for the -FilePath and -Wait parameters.
      $splat = @{
        FilePath = $Path
        Wait = $true
      }
      # Only add an 'ArgumentList' entry if an install path was given.
      if ($installPath = $Installs[$i].Path) {
        # Enclose the install path in "..." if it contains spaces.
        $splat.ArgumentList = 
          ($installPath, "`"$installPath`"")[$installPath -match ' ']
      }
      # Note the use of @ instead of $ in order to achieve splatting.
      Start-Process @splat
    }
    

    Note: