PSSession management helps you connect to and control other computers remotely using PowerShell. It makes running commands on other machines easy and organized.
0
0
PSSession management in PowerShell
Introduction
You want to run commands on a remote computer without logging in physically.
You need to manage multiple remote computers at once.
You want to keep a connection open to a remote machine to run several commands.
You want to automate tasks across different servers from your local computer.
Syntax
PowerShell
New-PSSession -ComputerName <RemoteComputerName>
Enter-PSSession -Session <PSSessionObject>
Invoke-Command -Session <PSSessionObject> -ScriptBlock { <commands> }
Remove-PSSession -Session <PSSessionObject>Use New-PSSession to create a new remote session.
Enter-PSSession lets you interact directly with the remote session.
Examples
Creates a new session to a computer named Server01.
PowerShell
New-PSSession -ComputerName Server01
Runs the
Get-Process command on Server01 using the session stored in $session.PowerShell
$session = New-PSSession -ComputerName Server01
Invoke-Command -Session $session -ScriptBlock { Get-Process }Starts an interactive session with Server01 so you can type commands directly.
PowerShell
$session = New-PSSession -ComputerName Server01 Enter-PSSession -Session $session
Closes the session stored in
$session to free resources.PowerShell
Remove-PSSession -Session $session
Sample Program
This script creates a session to your own computer (localhost), runs the Get-Date command remotely to get the current date and time, then closes the session.
PowerShell
$session = New-PSSession -ComputerName localhost
Invoke-Command -Session $session -ScriptBlock { Get-Date }
Remove-PSSession -Session $sessionOutputSuccess
Important Notes
Replace localhost with the name of the remote computer you want to connect to.
Make sure remote PowerShell is enabled on the target machine.
Always remove sessions when done to avoid using unnecessary resources.
Summary
PSSession lets you connect and run commands on remote computers.
Use New-PSSession to create, Invoke-Command to run commands, and Remove-PSSession to close.
It helps automate and manage tasks across multiple machines easily.