powershellscriptblock

Variable in ScriptBlock - Powershell


I have a GUI for my powershell script. If the folder "Temp" in C: does not exist - create folder and the logging entry "Path C:\Temp does not exist - create folder".

This is an extract of my code:

$infofolder=$global:dText.AppendText("Path C:\Temp does not exist - create folder`n")

###create C:\Temp if does not exist
       Invoke-Command -Session $session -ScriptBlock {
         $temp= "C:\Temp"
         if (!(Test-Path $temp)) {
                $Using:infofolder
                New-Item -Path $temp -ItemType Directory}
        }

I have to use a variable that is defined outside of the ScriptBlock, so I use "$Using". But the variable $infofolder should only be executed in the Scriptblock. Unfortunately it gets already executed before and that does not make sense, as the logging entry is also created when the folder exists.

And I cannot use $using:global:dText.AppendText("Path C:\Temp does not exist - create folder`n").

THANK YOU!!


Solution

  • You can't share "live objects" across remote sessions - meaning you can't invoke methods (like AppendText()) across a session boundary like you're trying to do.

    Instead, use the pipeline to consume the output from Invoke-Command and call AddText() in the calling session:

    Invoke-Command -Session $session -ScriptBlock {
      $temp= "C:\Temp"
      if (!(Test-Path $temp)) {
        Write-Output "Path '$temp' does not exist - create folder"
        New-Item -Path $temp -ItemType Directory |Out-Null
      }
      # ... more code, presumably
    } |ForEach-Object {
      # append output to textbox/stringbuilder as it starts rolling in
      $global:dText.AppendText("$_`n")
    }