Monday, December 3, 2012

A defect for 'get-random'

In PS 3.0, 'Get-random' doesn't return an error value for a $null variable without the use of  '-inputobject'.  I came across this writing a  function so my third grader could pick up her arithmetic skills. The function has '$Mixed' as such:

[array]$Mixed= % {
0..($questions_per_worksheet - 1) | % {write "2 $operator1 $(get-random -max $random_max -min $random_min) = "} 
0..($questions_per_worksheet - 1) | % {write "4 $operator2 $(get-random -max $random_max -min $random_min) = "} 
0..($questions_per_worksheet - 1) | % {write "5 $operator3 $(get-random -max $random_max -min $random_min) = "} 
0..($questions_per_worksheet - 1) | % {write "10 $operator4 $(get-random -max $random_max -min $random_min) = "} 



Outside the scope of my variable definitions in my function (far below), '$Mixed' simply executes a default 'get-random' return:


PS C:\> $Mixed
2  2067565188 =
2  2004162216 =
4  1444965532 =
4  1339255453 =
5  800716612 =
5  1734093788 =
10  1172049319 =
10  1506713684 =

Given variable definitions, all proceeds as expected:



Function global:Create-MathSheet
{
 [CmdletBinding()]
 Param(
[int]$question_count=80,
[int]$questions_per_worksheet=20,
[int]$random_max=10,
[int]$random_min=1,
[string]$operator1="+",
[string]$operator2="-",
[string]$operator3="*",
[string]$operator4="/"
)
# defines questions
[array]$Mixed= % {
0..($questions_per_worksheet - 1) | % {write "2 $operator1 $(get-random -max $random_max -min $random_min) = "} 
0..($questions_per_worksheet - 1) | % {write "4 $operator2 $(get-random -max $random_max -min $random_min) = "} 
0..($questions_per_worksheet - 1) | % {write "5 $operator3 $(get-random -max $random_max -min $random_min) = "} 
0..($questions_per_worksheet - 1) | % {write "10 $operator4 $(get-random -max $random_max -min $random_min) = "} 
}

# randomizes order of questions
foreach ($i in (0.. $($question_count - 1))) `
{get-random -min 0 -max $($question_count - 1) | % {$Mixed[$PSItem]}}
}




PS C:\> Create-MathSheet
5 * 2 =
4 - 2 =
10 / 9 =
5 * 2 =
2 + 4 =
4 - 4 =
4 - 6 =
4 - 9 =
4 - 4 =
2 + 4 =
5 * 8 =
10 / 7 =
10 / 8 =
2 + 2 =
5 * 6 =
5 * 7 =
4 - 6 =
4 - 7 =
10 / 8 =
2 + 1 =
10 / 2 =

...

You can work around this problem for a simple $null variable in one of several ways:


get-random -inputobject $a
Get-Random : Cannot validate argument on parameter 'InputObject'. The argument is null or empty. Supply an argument that is not null or empty and then try the comma
again.
At line:1 char:25
+ get-random -inputobject $a
+ ~~
+ CategoryInfo : InvalidData: (:) [Get-Random], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetRandomCommand
or some validation homespun:
If (!$defined_variable) {} else {get-random $defined_variable}





No comments: