Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the default argument to an array

I'm trying to get my script to set an array as a default value for a script if the value is not given as an argument to my script and seem to be having some issues getting Powershell to understand that it's an array.

I've set params as so:

param (
    [string]$games = @('Subnautica', 'Gearcity')
)

The problem seems to be that $games now gets the value of a string "Subnautica Gearcity". At least that's the output of the variable. The comma seems to disappear and thus so does the array when trying to traverse it using foreach ( $game in $games ) { random jabber }.

like image 359
SkyRaider Avatar asked Jun 25 '17 20:06

SkyRaider


People also ask

How do I set a default array?

Using default values in initialization of arrayType[] arr = new Type[capacity]; For example, the following code creates a primitive integer array of size 5 . The array will be auto-initialized with a default value of 0 . We can use the Arrays.

How do you assign a default value to an argument in Java?

There are several ways to simulate default parameters in Java: Method overloading. void foo(String a, Integer b) { //... } void foo(String a) { foo(a, 0); // here, 0 is a default value for b } foo("a", 2); foo("a");

How do you declare a default argument in C?

A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.


2 Answers

The reason this happens is that you have specified that your Parameter $games is a string, what you want is an array of strings: string[] so your code becomes:

param (
    [string[]]$games = @('Subnautica', 'Gearcity')
)
like image 115
Zerqent Avatar answered Oct 04 '22 22:10

Zerqent


This bit: [string]$games forces your variable to be a string. To make it an array of strings you need to add[] to variable type declaration.

[string[]]$games = @('Subnautica', 'Gearcity')
like image 40
NikolaiDante Avatar answered Oct 04 '22 21:10

NikolaiDante