-4

I have to change a bash script into a PowerShell script, but I dont really get the condition in the if-statement.

if [ $# -eq 0 ]
then
    name='plmapp-all'
else
    name="$1"

Does somebody know what's $# and how this statement would look like in PowerShell?

Manu
  • 1,685
  • 11
  • 27
Antonya
  • 13

1 Answers1

2

$# is an internal bash variable that holds the number of arguments passed to a script. Its PowerShell equivalent is $args.Count. $args is an automatic variable holding a list with the arguments passed to the script (like $@ in bash). Since PowerShell is working with objects you can obtain the argument count directly from the $args array without the need for an additional variable.

The whole expression would look like this in PowerShell:

if ($args.Count -gt 0) {
    $name = 'plmapp-all'
} else {
    $name = $args[0]
}

You could simplify that to

if ($args) {
    $name = 'plmapp-all'
} else {
    $name = $args[0]
}

because PowerShell interprets non-empty arrays as $true and empty arrays as $false in a boolean context.

An even more streamlined alternative would be:

$name = @($args + 'plmapp-all')[0]

Since $args is always an array the + operator appends the string to that array, then the index operator selects the first element from the result array.

[] + 'plmapp-all'              → [ 'plmapp-all' ]
[ 'something' ] + 'plmapp-all' → [ 'something', 'plmapp-all' ]
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328