Get-Random and empty array

I am working on a script in which a number of arrays exist, these arrays contain a set of characters. But one or more of these arrays can also be empty, depending of the circumstances. At the end I need to join the content of these arrays together and then get a random character from this array.

As long as all arrays contain at least 1 character, all is fine, but if there is an empty array the Get-Random cmdlet throws the error:

Get-Random : Cannot validate argument on parameter 'InputObject'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.

So just to vizualize:

$array1 = "a","b","c"
$array2 = "d","e","f"
$array3 = "g","h"

$joinedarray = $array1 + $array2 + $array3

$joinedarray | Get-Random -Count 1

So in above example all goes fine. But if one of the arrays is empty, Get-Random throws the above quoted error. I suppose I could check if the array is empty before adding it to the $joinedarray, but not sure how to exactly translate that in my code.

Any suggestions?

Might not be the BEST way but it works

#works fine without nulls but fails with nulls
$array1 = "a","b","c"
$array2 = "d","e","f"
$array3 = "g","h"

$joinedarray = $array1 + $array2 + $array3

$joinedarray | Get-Random -Count 1

#quick, simple, maybe not the best way
$array1 = "a","b","c"
$array2 = "d","e","f"
$array3 = $null

$joinedarray = $array1 + $array2 + $array3

$joinedarray | where-object{$_}|Get-Random -Count 1

You dont tel powershell its an array. It wil make that up for you, if it can.
But $array="" could be anything.

This works:

$array1 = @(“a”,“b”,“c”)
$array2 = @(“d”,“e”,“f”)
$array3 = @()

$joinedarray = $array1 + $array2 + $array3

$joinedarray | Get-Random -Count 1

I like your’s better Chris - had a couple of mine between meetings - guess I need to try to stop thinking quickly.

Ignore mine - go with the code stuff Chris posted

Well guys, both methods work. But indeed, Chris’ comment that I didn’t explicitly declared it as an array dropped the ball :slight_smile:

Thanks!

Thanks!

I just played around a bit to see what happens.

PS C:\Users> $array3.GetType()

IsPublic IsSerial Name BaseType


True True String System.Object

PS C:\Users> $array2.GetType()

IsPublic IsSerial Name BaseType


True True Object[] System.Array

So that checks out, one new thing for me i came across.
Setting a variable to $null, makes a variable, but still has no variable property like string or array.

PS C:\Users> $var1=$null

PS C:\Users> $var1.gettype()
You cannot call a method on a null-valued expression.
At line:1 char:1

  • $var1.gettype()
  •   + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
      + FullyQualifiedErrorId : InvokeMethodOnNull
    
    
    

PS C:\Users> Get-Variable var1

Name Value


var1

65…90|foreach-object{ [char]$_ } | get-random