3

Here is a barebones code of what I am trying to achieve..

$destinationDir = "subdir1"   

#creating tab     
$newTab = $psise.PowerShellTabs.Add()
Do 
   {sleep -m 100}
While (!$newTab.CanInvoke)


#running required script in tab 
$newTab.Invoke({ cd $destinationDir})

Since $destinationDir is initialized in the parent tab, its scope is limited to it and I get the following error in the child tab

cd : Cannot process argument because the value of argument "path" is null. Change the value of argument "path" to a non-null value.

How do I overcome this and use the value in the child tab?

Jan Chrbolka
  • 4,184
  • 2
  • 29
  • 38
SatheeshJM
  • 3,575
  • 8
  • 37
  • 60

1 Answers1

2

Short answer: You can't. Each tab in PowerShell ISE is created with a new runspace. There is no method provided, for injecting variables into this runspace.

Long answer: There are always workarounds. Here are two.

1. Use the invoke script-block to transfer the variable to the new runspace:

$destinationDir = "subdir1"
#creating tab     
$newTab = $psise.PowerShellTabs.Add()
Do 
   {sleep -m 100}
While (!$newTab.CanInvoke)

$scriptblock = "`$destinationDir = `"$($destinationDir)`" 
cd `$destinationDir"

#running required script in tab 
$newTab.Invoke($scriptblock)

2. Use en environmental variable:

$env:destinationDir = "subdir1"   

#creating tab
$newTab = $psise.PowerShellTabs.Add()
Do 
   {sleep -m 100}
While (!$newTab.CanInvoke)

#running required script in tab 
$newTab.Invoke({ cd $env:destinationDir})
Jan Chrbolka
  • 4,184
  • 2
  • 29
  • 38
  • Thanks! Exactly what I needed. Can you please explain why `$($destinationDir)` is used? – SatheeshJM Mar 27 '15 at 09:52
  • 1
    @SatheeshJM Enclosing an expression in brackets preceded by a dollar sign "$(....)" is a PowerShell way to ensure that the enclosed expression gets evaluated. Sometimes, in strings, variables don't get evaluated properly. Especial when the string contains special characters. It's a PowerShell thing... – Jan Chrbolka Mar 29 '15 at 23:13