PowerShell ISE how to automate the creation of new tabs with closing ScriptBlock?

I am trying to automate the creation of a group of tabs in PowerShell ISE

I started with a feature like

function Start-NewTab($name, [ScriptBlock]$scriptBlock) { $tab = $psISE.PowerShellTabs.Add() $tab.DisplayName = $name sleep 2 $tab.Invoke($scriptBlock) } 

however, when I run it like that

 $v = "hello world" Start-NewTab "Test" { $v } 

hello world not displayed, unlike the following fragmentation

 function Test-ScriptBlock([ScriptBlock]$sb) { & $sb } Test-ScriptBlock { $v } 

What is going on here and how to fix it?

+7
source share
3 answers

The Tab container is equated to a space (or powershell runtime ) in ISE. Since you are creating a new tab (i.e. powershell runtime), the variable v is undefined in this runtime. The script block is evaluated in the new runtime and displays the value v (nothing).

It is easy to see how permission variables differ in the case of Test-Scriptblock from the case of Start-NewTab, if you try to get the variable in the script block by explicitly indicating the area in which the variable should be found.

 PS>Test-ScriptBlock { get-variable v -scope 0} Get-Variable : Cannot find a variable with name 'v'. PS>Test-ScriptBlock { get-variable v -scope 1} Get-Variable : Cannot find a variable with name 'v'. PS>Test-ScriptBlock { get-variable v -scope 2} # Variable found in grandparent scope (global in the same execution environment) Name Value ---- ----- v hello world PS>Start-NewTab "Test" { get-variable v -scope 0 } # global scope of new execution environment Get-Variable : Cannot find a variable with name 'v'. PS>Start-NewTab "Test" { get-variable v -scope 1 } # proof that scope 0 = global scope Get-Variable : The scope number '1' exceeds the number of active scopes. 

One way to solve your problem is to define your variable in the script block:

 Start-NewTab "Test" { $v = "hello world";$v } 

Edit: Another one, your name mentions "closing." Powershell scriptblocks are not closures, however you can create closures from a script block. This will not help you with the problem you are describing.

Edit2: Another workaround:

 $v = "hello world" Invoke-Expression "`$script = { '$v' }" Start-NewTab "test" $script 
+1
source

Or just create the script block first.

 $v={"Hello world"} start-newtab "test" $v 

But you must remember this.

0
source

I know this is an old question, however I recently found a new problem for this problem. It may be helpful to someone.

Use environment variable:

 function Start-NewTab($name, [ScriptBlock]$scriptBlock) { $tab = $psISE.PowerShellTabs.Add() $tab.DisplayName = $name sleep 2 $tab.Invoke($scriptBlock) } $env:v = "hello world" Start-NewTab "Test" { $env:v } 
0
source

All Articles