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 }
.
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.
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");
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.
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')
)
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With