Skip to content

Instantly share code, notes, and snippets.

@nohwnd
Created May 31, 2019 09:39
Show Gist options
  • Save nohwnd/aeb63b272c03ab084560083ebbc75d73 to your computer and use it in GitHub Desktop.
Save nohwnd/aeb63b272c03ab084560083ebbc75d73 to your computer and use it in GitHub Desktop.
Define variable in caller scope
# Sets variable $a = 1000 in the local scope from which it was called from, like $matches in regex
Get-Module m | Remove-Module
New-Module m {
function f {
[CmdletBinding()]
param()
$sb = [ScriptBlock]::Create('param($Value); $a = $Value')
$ExecutionContext.InvokeCommand.InvokeScript($PSCmdlet.SessionState, $sb, @(1000))
}
} | Import-MOdule
Get-Variable a -ErrorAction Ignore | Remove-Variable
f
"a: $a"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment