🎓 A1Learner
🔍
0 of 46 lessons completed

PowerShell Remoting Sessions

A PSSession is a lasting connection to another computer. It lets you run many commands there without reconnecting each time.

Opening a session can fail on Linux

New-PSSession needs a helper library called WSMan. This machine does not have it, so opening a session fails with a real message.

try {
  $session = New-PSSession -ErrorAction Stop
  "Session opened"
} catch {
  "Caught: " + $_.Exception.Message
}

Invoke-Command runs a block of code

Invoke-Command runs a script block. On this machine the block runs here, because no remote session exists.

Invoke-Command -ScriptBlock { Get-Date -Date "2026-10-28" -Format "yyyy-MM-dd" }

The result comes back as a value

A remote command returns its result to you. You can store that result in a variable and print it.

$result = Invoke-Command -ScriptBlock { 3 + 4 }
$result

Example

try {
  $session = New-PSSession -ErrorAction Stop
  "Session opened"
} catch {
  "No session: " + $_.Exception.Message
}
$result = Invoke-Command -ScriptBlock { 6 * 7 }
"Local result: $result"

Key points

  • PSSession: a lasting connection to another computer.
  • New-PSSession: the command that opens a session.
  • Invoke-Command: the command that runs a block of code.
  • ScriptBlock: a block of code in braces that can be sent and run.
  • Session work: commands run on the other computer and results come back to yours.
  • Closed sessions: a session ends when you close it, so it does not stay open forever.

In this example, the script first tries to open a session. The try and catch print the real failure message. The script then runs a block locally with Invoke-Command and prints its result.

Note

On this Linux machine, New-PSSession cannot open a session because the WSMan client library is missing. The lessons below show the real failure and run the same blocks locally instead.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does New-PSSession do?