PS – remote execution of scripts

In this post i want to show you some ways how to execute remote execution of scripts.

First the complicated way:

connect – set execution policy – copy script, execute, delete – roll back execution policy

#"Start Session"
$s = New-PSSession -ComputerName $Computername
#"Enable Script Execution on remote System..."
Invoke-Command -Session $s -scriptblock { Set-executionpolicy unrestricted }
#Copy Script
Copy-Item H:\Skript.ps1 \\$Computername\c$\temp\Skript.ps1
#"Start Script..."
Invoke-Command -Session $s -scriptblock { c:\temp\Skript.ps1 }
#Delete Script
Remove-Item \\$Computername\c$\Skript.ps1
#Disable Script Execution on remote System...
Invoke-Command -Session $s -scriptblock { Set-executionpolicy default }
#End Session
Remove-PSSession $s

Next we use Invoke-Command – the scriptfile is copied and executed within the command itself:

Invoke-Command -computer Computername -FilePath C:\Skript.ps1

Next code connects to a computer NOT using Kerberos. This can become necessary if you want to connect to computers outside your domain:


#Not using Kerberos:
cd WSMan:\localhost\Client
Set-Item trustedhosts $Computername -force
Restart-Service winrm
Invoke-Command Computername { #Skript in here#} -authentication negotiate -credential Get-Credential

Have fun with it.