Enable IIS On Azure VM using Remote PowerShell

With Simple modification you can do anything you want.

 

# Define functions:
Function InstallWinRMCertificateForVM ($servicename, $svrname)
{
    Write-Host "Installing WinRM Certificate for remote access: $servicename $svrname"
    $WinRMCert = (Get-AzureVM -ServiceName $servicename -Name $svrname | select -ExpandProperty vm).DefaultWinRMCertificateThumbprint
	$AzureX509cert = Get-AzureCertificate -ServiceName $servicename -Thumbprint $WinRMCert -ThumbprintAlgorithm sha1

	$certTempFile = [IO.Path]::GetTempFileName()
	$AzureX509cert.Data | Out-File $certTempFile

	# Target The Cert That Needs To Be Imported
	$CertToImport = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $certTempFile

	$store = New-Object System.Security.Cryptography.X509Certificates.X509Store "Root", "LocalMachine"
	$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
	$store.Add($CertToImport)
	$store.Close()
	
	Remove-Item $certTempFile
}

$adminUsername  = '<username>'
$adminPassword = '<password>'

$vmname       = "HQServer1"
$cloudsvcName =  "HQServer1"

# Install the WinRM Certificate first to access the VM via Remote PS
InstallWinRMCertificateForVM $cloudsvcName $vmname

# Return back the correct URI for Remote PowerShell
$uri = Get-AzureWinRMUri -ServiceName $cloudsvcName -Name $vmname
$SecurePassword = $adminPassword | ConvertTo-SecureString -AsPlainText -Force
$credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $adminUsername,$SecurePassword

# Test Remote Script 
Invoke-Command -ConnectionUri $uri.ToString() -Credential $credential -ScriptBlock {
  Get-ChildItem c:\
}

# Install IIS
Invoke-Command -ConnectionUri $uri.ToString() -Credential $credential -ScriptBlock {
  Install-WindowsFeature -Name Web-Server -IncludeManagementTools -Source C:\Windows\WinSxS
}

# Disable Windows Firewall:
Invoke-Command -ConnectionUri $uri.ToString() -Credential $credential -ScriptBlock {
  Set-NetFirewallProfile -All -Enabled False 
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s