Var shared between functions, is it the way to do it, or?

Welcome Forums General PowerShell Q&A Var shared between functions, is it the way to do it, or?

This topic contains 2 replies, has 3 voices, and was last updated by

 
Participant
2 weeks, 2 days ago.

  • Author
    Posts
  • #127476

    Participant
    Points: 43
    Rank: Member
    I got this psydo code
    switch ([System.Environment]::OSVersion.Platform) {
    'Unix' {
        $BaseUrl='http://:8282/masking/api/'
        $RulesXMLFile='E:/Delphix/Masking/Rules.xml'
        $UserName=
        $Password=
      } default {
        $BaseUrl='http://:8282/masking/api'
        $RulesXMLFile='//Volumes/home/PowerShell/Delphix/Masking/Rules.xml'
        $UserName=
        $Password=
      }
    }
    
    $Header = @{
      "Accept"="application/json"
      "connectapitoken"="97fe6ab5b1a640909551e36a071ce9ed"
      "Content-Type"="application/json"
    }
    
    Function New-Login {
      $Authorization=Invoke-WebRequest-Uri "$($BaseURL)/login"-Method POST -Headers $Header-Body $Jason
      $Header.Add("Authorization", ($Authorization|Select-Object-ExpandProperty Content |ConvertFrom-Json).Authorization)
      Write-Output ($Authorization|Select-Object-ExpandProperty Content |ConvertFrom-Json).Authorization
    }
    
    Function Get-Environments {
    Param (
      [parameter(Mandatory = $False,
        ValueFromPipeline=$true,
        ValueFromPipelineBypropertyName=$true)]
        [String]$EnvironmentID
    )
    
    Begin {}
    
    process {
      $url="$($BaseURL)/environments"
      $res=Invoke-RestMethod-Uri $url-Method GET -Headers $header
      Write-Output$res
    }
    
    End {}
    
    }
    
    Function Get-FileRuleSet {
    Param(
      [parameter(Mandatory = $True,
      ValueFromPipeline=$true,
      ValueFromPipelineBypropertyName=$true)]
      [Int]$EnvironmentID
    )
    
    Begin {}
    
    Process {
      $url="$($Script:BaseURL)/file-rulesets?environment_id=$($EnvironmentID)"
      Invoke-RestMethod-Uri $url-Method GET -Headers $Header|ForEach-Object {
      $_.responseList | ForEach-Object {
        $properties=@{
          FileRulesetId= $_.fileRulesetId
          rulesetName= $_.rulesetName
          fileConnectorId= $_.fileConnectorId
        }
        $Obj=New-Object-TypeName PSObject -Property $properties
        Write-Output$obj
        }
      }
    }
    
    End {}
    
    }
    
    if (New-Login) {
      Get-Environments|Get-FileRuleSet
    }
    
    --------------------------------------------------
    I have some var there is shared between the functions (and the next 15-20 functions), 
    is there a smarter or more beautiful way to do it?
    Or do I do it the right and only way?
    You can say, that normally a function has some input, and some output (an object), 
    nothing comes into the function from the sides, but you can say, in this case it does (its not defined as input parameter)
    If i save this as a module, then i will have a module with some functions, and some global variables, 
    would you do it the same way?
    
    

     

  • #127488

    Participant
    Points: 321
    Helping Hand
    Rank: Contributor

    Variable scope is a fully documented and heavily discussed topic, for example:

    Get-help -Name about_Scopes -Examples
    Get-help -Name about_Scopes -Full
    Get-help -Name about_Scopes -Online
    

    Controlling the Scope of Variables

    First rule of PowerShell scoping rules…

    When you create a variable, it is available in that scope and any child scopes.

    The example below shows how you can define a variable in one scope and access it in a child scope (by calling a function t1) and how it is available in all child scopes (by calling a function t2 which then calls a t1):

    function t1 {“X = $x”}
    t1
    X =
    $x=”test”
    $x
    test
    t1
    X = test
    function t2 { t1 }
    t2
    X = test
    
  • #127491

    Participant
    Points: 324
    Helping Hand
    Rank: Contributor

    If you are making this a Module, which I would highly recommend, you can also setup private module variables. In your .PSD1 file, you can setup

    ...
    PrivateData = @{
        DelphixAuthorizationToken = $null;
        DelphixHrmHostName = $null;
        
        PSData = @{
            ....
        }
    }
    

    Then you can set this private variable:

    $MyInvocation.MyCommand.Module.PrivateData['DelphixAuthorizationToken'] = $authRequest.Envelope.Body.row.id
    

    I normally have a wrapper script for Invoke-RestMethod where I set global headers, allow self-signed certs, force TLS 1.2, etc. that all of my functions call. Additionally, I build the URL here and just pass the relative URL (i.e. /file-rulesets?environment_id=123) to this function. I set the AuthToken as a Parameter like so:

               [Parameter(Mandatory = $False,
                           ValueFromPipelineByPropertyName = $True,
                           HelpMessage = 'Authorization Token for session returned from Invoke-DelphixRestMethod')]
                [string]$AuthorizationToken = $MyInvocation.MyCommand.Module.PrivateData['DelphixAuthorizationToken'],
    

You must be logged in to reply to this topic.