Powershell connect with remote computer

With Powershell you are able to connect to remote computers and execute statements. For example this allows you to start and stop IIS on a remote webserver, install/uninstall Windows Services when deploying new software and more.

Snippet: connect to a remote computer

# Server to connect to
$TargetServerName = "server.lanedirt.local"  

# Username and password of account which has local admin and local logon rights to the server above
$RemoteUsername = "administrator"
$RemotePassword = "[password here]"

# Convert password to a secure string
$SecurePassword = ConvertTo-SecureString $RemoteUsername -AsPlainText -Force
# Create credential object with username and secure password
$SecureCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $RemoteUsername,$SecurePassword
# Create remote connection with the just created credential object
$RemoteConn = New-PSSession -ComputerName $TargetServerName -Credential $SecureCredential

# ================ Execute code on remote server ================
Invoke-Command -Session $RemoteConn -ScriptBlock {
		# Enter code to execute on remote computer here
		# ....
} -argumentlist $Argument0,$Argument1
# Tip: you can optionally pass on arguments via the argumentList. These arguments will then be available within the ScriptBlock via $args[0], $args[1] etc.

Remote execute examples

Below you will find a few examples of things to run on a remote computer via Powershell.

a) Copy files from local to remote server

Note: the code below does 2 things:

  • Delete all files on remote server, except files matching a filter (in this case, appsettings.json files are NOT deleted) — this is done on the remote server, so it uses a RemoteConn ScriptBlock.
  • Copy all files from local server to remote server (this is initiated from the local server, so this statement needs te be outside of the ScriptBlock.
$CopySource = "C:\Solution\MyService\bin\Release\net5.0\*"
$CopyDest = "C:\Services\MyService"
Invoke-Command -Session $RemoteConn -ScriptBlock { 
        # Remove all files on remote server except appsettings.json files.
        Get-ChildItem -Path  $args[0] -Recurse -exclude "appsettings.*.json", "appsettings.json" | Remove-Item -Recurse -force 
	} -argumentlist $CopyDest
Copy-Item $CopySource -Recurse -Force -Destination $CopyDest -ToSession $RemoteConn -Container

b) Install a Windows Service

The code below should be inserted between the parentheses in the RemoteConn ScriptBlock.

# Install Windows Service
Write-Host "  -- Starting installation of Windows Service 'MyWindowsService'"        
Invoke-Expression "cmd.exe /c 'sc.exe create MyWindowsService binpath=C:\Services\MyWindowsService\MyWindowsService.exe'"
# Optional: configure Windows Service to run as a certain user. You will need to pass on the username/passwords via the ArgumentList option!
Invoke-Expression ("cmd.exe /c 'sc.exe config MyWindowsService obj= """ + $args[0] + """ password= """ + $args[1] + """'")
# Set service to auto-start
Invoke-Expression "cmd.exe /c 'sc config MyWindowsService start= auto'"
# Start service immediately
Invoke-Expression "cmd.exe /c 'sc start MyWindowsService '"
Write-Host "  --   Finished installation of Windows Service 'MyWindowsService'"

c) Uninstall a Windows Service

The code below should be inserted between the parentheses in the RemoteConn ScriptBlock.

# Uninstall Windows Service
Write-Host "  -- Starting uninstall of Windows Service 'MyWindowsService'"
Invoke-Expression "cmd.exe /c 'sc.exe stop MyWindowsService'"
Invoke-Expression "cmd.exe /c 'sc.exe delete MyWindowsService'"
Write-Host "  --   Finished uninstallation of Windows Service 'MyWindowsService'"

d) Stop and start IIS

The code below should be inserted between the parentheses in the RemoteConn ScriptBlock.

# Stop IIS
Invoke-Expression "iisreset /STOP"

# Start IIS
Invoke-Expression "iisreset /START"

e) Create EventViewer EventSources

The code below should be inserted between the parentheses in the RemoteConn ScriptBlock.

$eventSources = @("MyApp1","MyApp2")
foreach ($source in $eventSources) {
    if ([System.Diagnostics.EventLog]::SourceExists($source) -eq $false) {
        [System.Diagnostics.EventLog]::CreateEventSource($source, "Application")
    }
}
Published
Categorized as Powershell

By Leendert de Borst

Freelance software architect with 10+ years of experience. Expert in translating complex technical problems into creative & simple solutions.

Leave a comment

Your email address will not be published. Required fields are marked *