I need to SET a script scope variable value within a function but it appears that the ARS scheduled task environment command shell does not have these available. Here's a simple script to demonstrate the issue ( if you run this in a powershell or even the ARS command shell it works as expected but as a scheduled task the script scope variable is not updated.
Returning the value from the function is not an option as the actual task is dynamic, so I don't know until run time what the variable name is and I'm using invoke-expression to actually set the value which is where I thought the original issue lay, but invoke-expression does work, I've tested it and the issue is 100% with the variable not being available. I just added proof of that in the test function below - the output inside the function shows blank values for the script scope variables when run in an ARS scheduled task.
Function Set-MyVariableValues {
"Variable 1 in function : '$script:myvariable1'" | Out-file c:\temp\MyVariableValueFunction.txt -append
"Variable 2 in function : '$script:myvariable2'" | Out-file c:\temp\MyVariableValueFunction.txt -append
$script:Myvariable1 = 2
Invoke-Expression '$script:Myvariable2 = 3'
}
$myvariable1 = 1
$Myvariable2 = 2
"Variable 1 value was : '$myvariable1'" | Out-file c:\temp\MyVariableValue.txt
"Variable 2 value is now : '$myvariable2'" | Out-file c:\temp\MyVariableValue.txt -Append
Set-MyVariableValues
"Variable 1 value was : '$myvariable1'" | Out-file c:\temp\MyVariableValue.txt -Append
"Variable 2 value is now : '$myvariable2'" | Out-file c:\temp\MyVariableValue.txt -Append
<#
when run in a powershell session you get the correct output
Variable 1 value was : 1
Variable 2 value is now : 2
Variable 1 in function : '1'
Variable 2 in function : '2'
Variable 1 value was : 2
Variable 2 value is now : 3
when run as an ARS scheduled task you get unchanged values
Variable 1 value was : 1
Variable 2 value is now : 2
Variable 1 in function : ''
Variable 2 in function : ''
Variable 1 value was : 1
Variable 2 value is now : 2
#>