2

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!!

2
  • What is $dText? A stringbuilder? Commented Feb 22, 2022 at 12:56
  • Recommended reading: about_Remote_Output Commented Feb 22, 2022 at 13:06

1 Answer 1

5

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")
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.