PowerShell: Assign Guest Virtual Machine to a Cloud in VMM

# assignVmsToCloud.ps1
# The following function assigns a guest VM into a 'cloud' in Virtual Machine Manager

$vmNames=@(
	'guest-vm1',
	'guest-vm2',
	'guest-vm3'
)
$cloudAssign='DEV'
$vmmServer=$env:computername
$roleName='Developers'

function assignVmsToCloud{
	param(
		$vmName='testVm',
		$cloudAssign='Test',
		$roleName='Administrators',
        $vmmServer='localhost'
	)
	$ErrorActionPreference='Stop'
	try{
        $null=import-module virtualmachinemanager
		$vm=Get-SCVirtualMachine -Name $vmName -VMMServer $vmmServer
		$cloud=Get-SCCloud -Name $cloudAssign -VMMServer $vmmServer
		$userRole=Get-SCUserRole -Name $roleName -VMMServer $vmmServer
		$jobGroup=[System.Guid]::NewGuid().Guid
        if(!$vm){
            write-warning "Unable to find VM named $vmName on VMM Server $vmmServer"
            return $false
        }elseif($vm.Cloud.Name -eq $cloudAssign){
			write-host "$vmName has already been assigned to Cloud $cloudAssign" -ForegroundColor Green
			return $true
		}else{	
			$null=Set-SCVirtualMachine -VM $vm -Cloud $cloud
			$null=Set-SCUserRoleQuota -Cloud $cloud -JobGroup $jobGroup
			$null=Set-SCUserRoleQuota -Cloud $cloud -JobGroup $jobGroup -QuotaPerUser
			$null=Add-SCUserRolePermission -Cloud $cloud -JobGroup $jobGroup -AllowLocalAdmin -Checkpoint -CheckpointRestoreOnly -DeployFromTemplateOnly -Deploy -DeployShielded -PauseAndResume -RemoteConnect -Remove -Save -Shutdown -Start -Stop -Store -ManageAzureProfiles
			$null=Grant-SCResource -Resource $vm -JobGroup $jobGroup
			$null=Set-SCUserRole -UserRole $userRole -JobGroup $jobGroup
			$vm=Get-SCVirtualMachine -VMMServer $vmmServer -Name $vmName
			if($vm.Cloud.Name -eq $cloudAssign){
				write-host "$vmName has been assigned to Cloud $cloudAssign successfully" -ForegroundColor Green
				return $true
			}else{
				write-host "$vmName has NOT been assigned to Cloud $cloudAssign" -ForegroundColor Red
				return $false
			}
		}
	}catch{
		write-warning $_
		return $false
	}
}

######## Set VM as defined ########
$results=[hashtable]@{}
foreach($vmname in $vmNames){
    $result=assignVmsToCloud $vmName $cloudAssign $roleName $vmmServer
	$results+=@{$vmName=$result}
}
######## Dynamically Gather VM by Keywords and assign to cloud ########
$keyword='stg'
$cloudAssign='STAGE'
$vms=.{$null=import-module virtualmachinemanager;get-vm}
$targetVms=$vms.Name|?{$_ -like "*$keyword*"}

$results=[hashtable]@{}
foreach($vmName in $targetVms){
    $result=assignVmsToCloud $vmName $cloudAssign $roleName $vmmServer
	$results+=@{$vmName=$result}
}

Leave a Reply

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