Getting to Know Export-PSSession — A Powerful PowerShell Cmdlet
Welcome back to Wahmans PowerShell Blog! Today, we’re taking a close look at a handy cmdlet that can really power up your remote PowerShell workflow: Export-PSSession.
According to Microsoft, Export-PSSession “exports commands from another session and saves them in a PowerShell module.” This is useful when you want to pull remote commands (especially from another computer or exchange server) and use them locally as if they were installed modules.
Why Use Export-PSSession?
Export-PSSession is particularly helpful in environments where you’re regularly managing remote machines or services and you want to avoid repeatedly establishing sessions just to run the same commands.
Let’s Dive into Some Examples
1. Beginner: Exporting Cmdlets from a Remote Session
This is the most basic way to use Export-PSSession. We establish a remote session, export commands to a local folder, and then import them using Import-Module.
$session = New-PSSession -ComputerName Server01
Export-PSSession -Session $session -OutputModule RemoteCommands -Force
Import-Module ./RemoteCommands
This allows you to access remote cmdlets from ‘Server01’ just like they were installed locally.
2. Intermediate: Export Only Specific Cmdlets
Want a module with only the cmdlets you need? Use the -CommandName parameter to be selective.
$session = New-PSSession -ComputerName Server01
Export-PSSession -Session $session -CommandName Get-Service, Start-Service -OutputModule SelectedServices -Force
Import-Module ./SelectedServices
This avoids clutter and loads only the commands you care about.
3. Advanced: Export Commands from Exchange Server
A real-world scenario: connecting to an Exchange server and exporting administrative cmdlets for later use.
$cred = Get-Credential
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://ExchangeServer/PowerShell/ -Authentication Kerberos -Credential $cred
Export-PSSession -Session $session -OutputModule ExchangeCmdlets -Force
Import-Module ./ExchangeCmdlets
This is useful for Exchange admins who need frequent access to remote commands without waiting for session creation every time.
4. Advanced Pro: Using Exported Module in Other Scripts
Once you’ve exported remote commands to a module, you can reuse them in any script without needing to reconnect to the original session.
# Assuming the ExchangeCmdlets module was previously created
Import-Module ./ExchangeCmdlets
# Now use the cmdlets as if they were local
Get-Mailbox -Identity "JohnDoe"
This is great for automation scripts that shouldn’t rely on session availability.
Conclusion
If you’re managing remote servers, Export-PSSession can save you time and streamline your workflows by letting you access your frequently-used remote cmdlets as if they were local.
Happy scripting, and I will see you in the next post!
Leave a Reply