$Credential = Get-Credential
Invoke-Command -ComputerName $Computer -ScriptBlock {Stop-Service -Name Bits}
Use to run a single command or script on a remote machine.
$Credential = Get-Credential
Invoke-Command -ComputerName $Computer -ScriptBlock {Stop-Service -Name Bits}
$Credential = Get-Credential
Invoke-Command -ComputerName $Computer -ScriptBlock {Stop-Service -Name Bits} -Credential $Credential
# Create a persistent connection to remote machine
$Session = New-PSSession -ComputerName $Computer -Credential $Credential
# Runs on remote machine
Invoke-Command -Session $Session -ScriptBlock {Stop-Service -Name Bits}
# Run on local machine
Get-Service
# Runs on remote machine again
Invoke-Command -Session $Session -ScriptBlock {Start-Service -Name Bits}
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