Run PSExec From PowerShell

PowerShell remoting help in a lot of areas, but there are times when you need to use PSExec. For those instances, I’ve created a function that you can use to run a command on a remote machine using PSExec.

Function ExecutePsExec($computer, $command){
    $ping = Test-Connection $computer -Count 1 -Quiet
    if($ping){
        $StdOutput = (Join-path $env:temp "$($computer).txt")
        Start-Process -FilePath $psexec -ArgumentList "-s \\$computer $command" -Wait -RedirectStandardOutput $StdOutput -WindowStyle Hidden
        $Results = Get-Content $StdOutput -raw
        Remove-Item $StdOutput -Force
    } else {
        $Results = "Not online"
    }
    [pscustomobject]@{
        Computer = $computer
        Results = $Results
    }
}
# path to PsExec on your local machine
$script:psexec = "C:\Tools\PsExec.exe"

# the command to run
$command = 'cmd /c "powershell.exe -ExecutionPolicy ByPass \\SHARE01\Scripts\Demo.ps1"'

# execute the command on the remote computer
ExecutePsExec -computer 'MYPC01' -command $command