Forum Discussion
Function in a function not running
- Mar 18, 2020
Mathieu Desjardins Hello, I would think about these 2 options.
Let me know if you have further questions.
#Option 1: Using a global scope$global:DatastoreName = $null # declared at top and used anywhere in your script
function GetDatastore{
$Datastore = Get-Datastore
$global:DatastoreName = $Datastore.name
}
Option 2: return the value of the desired variable outside the function to use it as needed
function GetDatastore
{
$Datastore = Get-Datastore
$DatastoreName = $Datastore.name
return $DatastoreName #required data
}
function RunAllFunction
{
$Test1 = "sometext"
$test2 = "sometext"
$test3 = GetDatastore #So now the output will be saved to $test3 variable and your outoutfile should be good.
$Output = Write-Output -InputObject ($test1,$test2,$test3)
$Output | Out-File C:\Temp\File.txt
ClearVariable
}
Regards
Erick Moreno
The Global variable worked like a charm!
But this answer trigger another question for my understanding:
How is a normal variable is not working vs a global one?
Thank you!
Mathieu Desjardins cause the "normal one" is inside a function so each time you run a function everything inside will be destroyed after the run unless it is explicitly saved.
You can test this initializing a var at the beginning on the script and then using the same var name inside the function and writing the value at the end of the script (outside the function) and see how the initialized value is the result no matter what you did inside the function so everything inside a function is like a different workspace. I hope that explains why you are getting that behavior.
Regards
Erick Moreno