<<< Back to Search

Scripting ::: Remote PowerShell Execution with PSSession - returning remote information

This code allow you execute remotely PowerShell commands that not have parameters for remote execution: -computerName / -cimSession

  • If the command has those parameters available execute using them instead of PSSession.

Core Snippet & Sample

Copy text below into a power shell session and execute to see the code in action.

# Scripting - Remote PowerShell Execution with PSSession
# Core Snippet &amp; Sample
# www.PowerShellExamples.com

# Commands to run in a remote computer using PSSession
#     returning info from remote execution
#     in case of a non-controlled exception code will return error details

$s = New-PSSession -computerName "ComputerNameXXX" # To use Custom Credential pass it here: -credential $credObj.Credential
$invokeResult = Invoke-Command -Session $s -Scriptblock {

    try {
        # TODO Update this section with commands to execute remotely
        # On this sample a list of 2 services on remote machine named C* is returned
        $x = @()
        $x += get-service -name "*" | select-object -last 2
    catch {
        $x = $_.Exception
    return $x
Remove-PSSession $s

Write-Host "Returned info" -ForegroundColor Magenta
$invokeResult | out-string | Write-Host


PS C:\>

Returned info

Status   Name               DisplayName                            PSComputerName
------   ----               -----------                            --------------
Stopped  wuauserv           Windows Update                         xxxxxxxxxxxx
Stopped  wudfsvc            Windows Driver Foundation - User-mo... xxxxxxxxxxxx