0
votes

In cmd I can write a batch file like so, which will provide an alias for an executable.

SuperUtil.bat

call Mine.Library.SuperUtil.exe %*

So I can call

SuperUtil -t SomeParam

This is my attempt of a PowerShell equivalent

Start-Process Mine.Library.SuperUtil.exe -NoNewWindow -ArgumentList $args

However when I call it with no parameters I get an error.

Start-Process : Cannot validate argument on parameter 'ArgumentList'. The argument is null, empty, or an element of the argument collection contains a null value. Supply a collection that does not contain any null values and then try the command again.

I've tried the following but doesn't pass the arguments, plus it's quite verbose:

if ($args -ne $Null)
{
    Start-Process Mine.Library.SuperUtil.exe -NoNewWindow -ArgumentList $args -Wait
}
else
{
    Start-Process Mine.Library.SuperUtil.exe -NoNewWindow -Wait
}

So I want to optionally pass the arguments or not, in order to explore the command line options.

2

2 Answers

3
votes

Use splatting if you want to provide optional parameter arguments:

$params = @{}
if($args){
    $params['ArgumentList'] = $args
}
Start-Process Mine.Library.SuperUtil.exe -NoNewWindow -Wait @params

If the $params hashtable is empty by the time Start-Process is invoked, it'll simply be ignored.

You can also squash the other parameter arguments into the hashtable if you want:

$params = @{
    FilePath    = 'Mine.Library.SuperUtil.exe'
    NoNewWindow = $true
    Wait        = $true
}
if($args){
    $params['ArgumentList'] = $args
}
Start-Process @params

Makes maintenance of the script easy (but obviously still quite verbose compared to the batch file alternative)

1
votes

Read About Automatic Variables:

$ARGS
Contains an array of the undeclared parameters and/or parameter values that are passed to a function, script, or script block.

Therefore, check if ($args.Count -ne 0) rather than if ($args -ne $Null) as the automatic variable $args is always an array (and never $Null).