PowerShell WinRM with un-trusted certificate

This is perfect for connecting to a remote server using PowerShell WinRM and you don’t need to worry about any client certificates. No longer need to worry about using the correct CN.

Perfect for spinning up Azure virtual machines e.g. Nano Server and connecting to and managing Azure hosted Windows Nano server using PowerShell.


#region Connect to Remote PowerShell WinRM HTTPS port 5986 with untrusted certificate – single connection
### Variables
$ServerName = "ServerName / or / IP Address"
$adminname = 'UserName'
$adminpassword = 'Password'
$password = ConvertTo-SecureString $adminpassword -AsPlainText -Force
$cred= New-Object System.Management.Automation.PSCredential (".\$adminname", $password)
### Enter session
$SessionOptions = New-PSSessionOption –SkipCACheck –SkipCNCheck –SkipRevocationCheck
Enter-PSSession -ComputerName $ServerName -Port 5986 -UseSSL -Credential $cred -SessionOption $SessionOptions
##########################################################################################
#################################### Do Stuff #####################################
##########################################################################################
### Get Service
Get-Service | ? {$_.Status -match 'runn'}
### Create Directory
New-Item -Path c:\ -Name MyDirectory -Type Directory -Force
### Check Direcroty Listing
Get-ChildItem -Path c:\ | ? {$_.Attributes -match 'Directory'}
##########################################################################################
Exit-PSSession
#endregion
#region Connect to Remote PowerShell WinRM HTTPS port 5986 with untrusted certificate – multiple connections
$adminname = 'UserName'
$adminpassword = 'password'
$password = ConvertTo-SecureString $adminpassword -AsPlainText -Force
$cred= New-Object System.Management.Automation.PSCredential (".\$adminname", $password)
$SessionOptions = New-PSSessionOption –SkipCACheck –SkipCNCheck –SkipRevocationCheck
$Computers = "123.221.252.23", "123.221.58.233", "ComputerName03"
$Params = @{
ComputerName = $Computers
Port = 5986
Credential = $cred
}
New-PSSession @params -UseSSL -OutVariable ps -SessionOption $SessionOptions
Invoke-Command -Session $ps -ScriptBlock {
# Do Stuff on all computers at the same time
$process = "cmd.exe"
$arguments = '/bla /bla etc'
start-process $process -ArgumentList $arguments -Wait
}
#endregion

Leave a comment