PS - PowerShell Connect to Azure & VMs


Install AzureRM PowerShell Module

First of all you need to ensure you have the correct PowerShell modules installed, let's set the execution policy level to Bypass just for this one process and install the AzureRM module.

Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process

Install-Module -Name AzureRM -Verbose -Force

Next, update the local help files:

Update-Help -Force -ErrorAction SilentlyContinue


WinRM Client Security

In many cases, you will be able to work with remote computers in other domains. However, if the remote computer is not in a trusted domain, the remote computer might not be able to authenticate your credentials. 

Now we add a wildcard to the trusted hosts for WSMan, Onlydo this for test/dev environments, on production environments specif the domain, IP address, etc.

Check the hosts already trusted :

Get-Item -Path WSMan:\localhost\Client\TrustedHosts

To add all the computers of a doimain the list of TrustedHosts

Set-Item -Path WSMan:\localhost\Client\TrustedHosts -Value *


Connect to Azure

Type Login-AzureRmAccount. You will get dialog box asking for your Azure credentials.

Ideally you would Azure service principal and logon as this, see Create an Azure service principal with Azure PowerShell. To log in with the service principal:

Login-AzureRmAccount -ServicePrincipal -ApplicationId  "http://my-app" -Credential $pscredential -TenantId $tenantid

To get your TenantId, log in interactively and then get the TenantId from your subscription:

Get-AzureRmSubscription

To enter a PSSession directly to a VM

You can now execute Powershell commands remotely on the server after entering a new PSSession:

Enter-PSSession -ComputerName xxxxxxxx -Credential Get-Credential

Or

$cred1 = Get-Credential -UserName 'Neil' -Message 'Enter VM admin credentials'
$vm = New-PSSession -ComputerName 1.2.3.4 -Credential $cred1 -Name 'vm'

$vm | Enter-PSSession

Exit-PSSession

Things to check on the remote server

You can verify the availability of WinRM and configure a PowerShell for remoting by following these steps: 

1. Start Windows PowerShell as an administrator by right-clicking the Windows PowerShell shortcut and selecting Run As Administrator. 

2. The WinRM service is confi gured for manual startup by default. You must change the startup type to Automatic and start the service on each computer you want to work with. At the PowerShell prompt, you can verify that the WinRM service is running using the following command: 

Get-Service winrm

The value of the Status property in the output should be “Running”.

3. To configure Windows PowerShell for remoting, type the following command: 

Enable-PSRemoting –force

Comments