Forum Discussion

Mathieu Desjardins's avatar
Mathieu Desjardins
Copper Contributor
Mar 18, 2020
Solved

Function in a function not running

HI, I am still experimenting with function and I have a question regarding a strange behavior. Let's say that I have the following code: function GetDatastore { $Datastore = Get-Datastore $Datas...
  • Erick A. Moreno R.'s avatar
    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

Resources