I'm looking to enter a persistent PSSession but want it to open in a new PowerShell window. The goal is to keep my original session free so I can continue working while watching the new session. I've tried creating a PSSession object to use but when I run Enter-PSSession -Session $TestObject.Session, it works in the local session, but I want it to spawn a new process. I attempted to use Start-Process with some parameters to launch a new pwsh.exe window, but I get an error that the remote session isn't available in that scope. I'm curious if there's a way to import my variables into the new session or if there's another way to make this work effectively.
4 Answers
You could try using `"-Command `"Enter-PSSession -Id $($using:TestObject.Session.Id)`""` with the `using:` scope modifier. If you’re looking to create the session in the new pwsh instance anyway, just run the `Enter-PSSession` command there directly. It avoids some of the issues you're facing with variable scopes.
Since the session is tied to the original process, you'll need to create a new session in the new PowerShell instance. Consider starting a new PowerShell session and connecting to the remote session directly from there, just using the `-ComputerName` parameter in `Enter-PSSession`. That way, you're starting fresh.
And just to clarify, even when starting a new PowerShell window, you're connecting to a PS5 endpoint, which might not give you much of a benefit over `Invoke-Command`. It might be worth checking out if the workload justifies opening new sessions.
If your goal is to batch process commands on remote machines, consider using `Invoke-Command` with a script block instead of `Enter-PSSession`. This lets you run your commands across multiple endpoints without locking up your main session. You can also use Jobs or ThreadJobs for this and keep your main console responsive.

Just a tip: `Invoke-Command` has an `-AsJob` parameter, so you might not need to bother with ThreadJobs at all.