PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 25, 2022

[FIXED] How 'local' are function parameters in a PowerShell module

 November 25, 2022     module, parameters, powershell, scope     No comments   

Issue

I have found a behavior in PowerShell that surprises me and for which I am looking for an explanation. Please consider the following PowerShell module named testParameter:

testParameter.psd1:

@{
   RootModule         = 'testParameter.psm1'
   ModuleVersion      = '0.1'

   FunctionsToExport  = @(
      'get-embeddedString'
   )
}

testParameter.psm1:

set-strictMode -version 3

function embed-string {

   param (
      [string] $pre,
      [string] $post
   )

  "$($pre)$text$($post)"
}


function get-embeddedString {

   param (
      [string] $text
   )

   return embed-string '>>> ' ' <<<'
}

When I call get-embeddedString foo, the function returns (or the console prints):

>>> foo <<<

I am surprised because this string is rendered in the function embed-string which does not declare a local variable named $text, does not have a parameter with that name and does not assign a value to it before it is used and I have expected the function to throw a The variable '$text' cannot be retrieved because it has not been set. error.

Apparently, embed-string chooses to use the value that $text has in get-embeddedString which I assume is in a different and unrelated scope.

I don't understand what's going on here and where the relevant documentation for this behavior is found.


Solution

Nested/Child functions have access to all the parent function's variables. You can even modify them in the child scope and they are returned to the original value in the parent.

function embed-string {
   param (
      [string] $pre,
      [string] $post
   )
    Write-Host $MyInvocation.BoundParameters
    Write-Host $MyInvocation.UnboundArguments

    Write-Host $text
    $text = "bar"

    "$($pre)$text$($post)"
}

function get-embeddedString {

    param (
       [string] $text
    )
    
    embed-string '>>> ' ' <<<'

    Write-Host $text
}

Output

[pre, >>> ] [post,  <<<]

foo
>>> bar <<<
foo

If you want to persist a change to a variable in the child function, you can use Set-Variable -Name text -Option AllScope.

Link about Nested Functions, applies to Child Functions too



Answered By - Ash
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing