设为首页 收藏本站
查看: 782|回复: 0

如何使用PowerShell从VHD创建虚拟机

[复制链接]

尚未签到

发表于 2018-9-1 11:04:43 | 显示全部楼层 |阅读模式
param  
(
  [parameter(Mandatory = $false)][switch]$AzureMoonCake,
  [parameter(Mandatory = $false)][switch]$DoNotLogin,
  [Parameter(Mandatory = $true)][string]$LocationName,
  [Parameter(Mandatory = $true)][string]$ResourceGroupName,
  [parameter(Mandatory = $true)][string]$VMName,
  [parameter(Mandatory = $true)][string]$VhdUri,
  [parameter(Mandatory = $true)][string]$VnetName,
  [parameter(Mandatory = $true)][string]$SubnetName,
  [parameter(Mandatory = $false)][switch]$HybridBenefit,
  [parameter(Mandatory = $false)][string]$VMSizeName = "Standard_D2",
  [parameter(Mandatory = $false)][string]$AvailabilitySetName,
  [parameter(Mandatory = $false)][ValidateSet("Windows", "Linux")][string]$OS = 'Windows',
  [parameter(Mandatory = $false)][string]$VnetPrefix = "10.140.0.0/16",
  [parameter(Mandatory = $false)][string]$SubnetPrefix = "10.140.0.0/24",
  [parameter(Mandatory = $false)][ValidateSet("Static", "Dynamic")][string]$PublicIPAllocationMethod = "Dynamic"
  
)
  

  

  

  
#检查Location是否存在,并返回结果
  
function Check-AzureRmLocation()
  
{
  param
  (
  [string]$LocationName = $(throw "Parameter missing: -LocationName LocationName")
  )
  Write-Host "$(Get-Date) * Checking location $LocationName" -ForegroundColor Green
  $Location = Get-AzureRmLocation | Where-Object { $_.Location -eq $LocationName }
  If (-not ($Location))
  {
  Write-Host "$(Get-Date) * The location" $LocationName "does not exist." -ForegroundColor Red
  return $false
  }
  Else
  {
  Write-Host "$(Get-Date) * Location $LocationName exists" -ForegroundColor Green
  return $true
  }
  
}
  

  
#检查RG是否存在,不存在则创建新的RG
  
function Check-AzureRmResourceGroup()
  
{
  param
  (
  [string]$ResourceGroupName = $(throw "Parameter missing: -ResourceGroupName ResourceGroupName"),
  [string]$LocationName = $(throw "Parameter missing: -LocationName LocationName")
  )
  Write-Host "$(Get-Date) * Checking resource group $ResourceGroupName, if not, created it." -ForegroundColor Green
  Try
  {
  $ResourceGroup = Get-AzureRmResourceGroup -Name $ResourceGroupName -Location $LocationName -ErrorAction SilentlyContinue
  If (-not ($ResourceGroup))
  {
  Write-Host "$(Get-Date) * Creating resource group" $ResourceGroupName "..." -ForegroundColor Green
  New-AzureRmResourceGroup -Name $ResourceGroupName -Location $LocationName -ErrorAction Stop
  return $true
  }
  Else
  {
  Write-Host "$(Get-Date) * Resource group $ResourceGroupName exists" -ForegroundColor Green
  return $true
  }
  }
  Catch
  {
  Write-Host -ForegroundColor Red "$(Get-Date) * Create resource group" $LocationName "failed." $_.Exception.Message
  return $false
  }
  
}
  

  

  
#随机生成新的NIC
  
function AutoGenerate-AzureRmNetworkInterface()
  
{
  param
  (
  [string]$ResourceGroupName = $(throw "Parameter missing: -ResourceGroupName ResourceGroupName"),
  [string]$LocationName = $(throw "Parameter missing: -LocationName LocationName"),
  [string]$VMName = $(throw "Parameter missing: -VMName VMName"),
  [string]$SubnetName,
  [string]$VnetName,
  [string]$SubnetPrefix = "10.140.0.0/24",
  [string]$VnetPrefix = "10.140.0.0/16",
  [switch]$Create,
  [string]$PublicIPAllocationMethod = "Dynamic"
  )
  Try
  {
  $RandomNum = Get-Random -minimum 100 -maximum 9999
  $IpName = $VMName + "-ip" + $RandomNum
  $NicName = $VMName + "-ni" + $RandomNum
  Write-Host "$(Get-Date) * Auto generate network interface $NicName" -ForegroundColor Green
  $Pip = New-AzureRmPublicIpAddress -Name $IpName -ResourceGroupName $ResourceGroupName -Location $LocationName -AllocationMethod $PublicIPAllocationMethod -ErrorAction Stop
  if ($Create)
  {
  #Vnet does not exist
  $Subnet = New-AzureRmVirtualNetworkSubnetConfig -Name $SubnetName -AddressPrefix $SubnetPrefix -ErrorAction Stop
  $Vnet = New-AzureRmVirtualNetwork -Name $VnetName -ResourceGroupName $ResourceGroupName -Location $LocationName -AddressPrefix $VnetPrefix -Subnet $Subnet -ErrorAction Stop
  $Nic = New-AzureRmNetworkInterface -Name $NicName -ResourceGroupName $ResourceGroupName -Location $LocationName -SubnetId $Vnet.Subnets[0].Id -PublicIpAddressId $Pip.Id -ErrorAction Stop
  }
  else
  {
  #Vnet exist
  $Vnet = Get-AzureRmVirtualNetwork -ResourceGroupName $ResourceGroupName -Name $VnetName -ErrorAction stop
  $subnet = Get-AzureRmVirtualNetworkSubnetConfig -VirtualNetwork $Vnet -Name $SubnetName -ErrorAction SilentlyContinue
  if ($subnet -eq $null)
  {
  #subnet does not exist
  Write-Host "$(Get-Date) * Subnet $SubnetName does not exist,create it,subnet prefix $SubnetPrefix" -ForegroundColor Green
  $Subnet = New-AzureRmVirtualNetworkSubnetConfig -Name $SubnetName -AddressPrefix $SubnetPrefix -ErrorAction Stop
  $vnet.subnets += $Subnet
  #update Vnet
  Set-AzureRmVirtualNetwork -VirtualNetwork $Vnet -ErrorAction Stop
  #get vnet again
  $Vnet = Get-AzureRmVirtualNetwork -ResourceGroupName $ResourceGroupName -Name $VnetName -ErrorAction stop
  $Subnet = Get-AzureRmVirtualNetworkSubnetConfig -Name $SubnetName -VirtualNetwork $Vnet -ErrorAction stop
  $Nic = New-AzureRmNetworkInterface -Name $NicName -ResourceGroupName $ResourceGroupName -Location $LocationName -SubnetId $Subnet.Id -PublicIpAddressId $Pip.Id -ErrorAction Stop
  }
  else
  {
  #subnet exist
  Write-Host "$(Get-Date) * Subnet $SubnetName exist" -ForegroundColor Green
  $Nic = New-AzureRmNetworkInterface -Name $NicName -ResourceGroupName $ResourceGroupName -Location $LocationName -SubnetId $Subnet.Id -PublicIpAddressId $Pip.Id -ErrorAction Stop
  }
  }
  return $Nic.Id
  }
  Catch
  {
  Write-Host -ForegroundColor Red "$(Get-Date) * Auto generate network interface" $_.Exception.Message
  return $false
  }
  
}
  

  

  

  

  

  

  

  
#Login Azure with ARM mode
  
Import-Module AzureRM.Profile
  
$Error.Clear()
  

  
if (!$DoNotLogin)
  
{
  if ($AzureMoonCake)
  {
  Write-Warning "$(Get-Date) * Current environment is Azure China(Mooncake)"
  Login-AzureRmAccount -EnvironmentName AzureChinaCloud
  }
  else
  {
  Write-Warning "$(Get-Date) * Current environment is Azure Global"
  Login-AzureRmAccount
  }
  if ($? -eq $true)
  {
  Write-Host "$(Get-Date) * Login succeeded!" -ForegroundColor Green
  }
  else
  {
  Write-Host $Error[0].Exception.Message -ForegroundColor Red
  break
  }
  
}
  
else
  
{
  $CurrentSubscription = Get-AzureRmSubscription
  if ($CurrentSubscription -eq $null)
  {
  Write-Warning "$(Get-Date) * Didn't find any subscription for now! Please login"
  break
  }
  
}
  

  

  
try
  
{
  #check location
  $Error.clear()
  if (Check-AzureRmLocation -LocationName $LocationName)
  {
  #check RM resource group, if not exist, create one
  if (Check-AzureRmResourceGroup -ResourceGroupName $ResourceGroupName -LocationName $LocationName)
  {
  #Check VM Name
  If (Get-AzureRmVM -Name $VMName -ResourceGroupName $ResourceGroupName -ErrorAction Ignore)
  {
  Write-Host -ForegroundColor Red "$(Get-Date) * VM $VMName has already exist."
  }
  else
  {
  #Check VM Size
  Write-Host "$(Get-Date) * Checking VM Size $VMSizeName" -ForegroundColor Green
  If (Get-AzureRmVMSize -Location $LocationName | Where-Object { $_.Name -eq $VMSizeName })
  {
  Write-Host "$(Get-Date) * VM Size $VMSizeName exist" -ForegroundColor Green
  If ($VhdUri)
  {
  #Create a network interface
  $Vnet = Get-AzureRmVirtualNetwork -ResourceGroupName $ResourceGroupName -Name $VnetName -ErrorAction SilentlyContinue
  if ($Vnet -eq $null)
  {
  Write-Host "$(Get-Date) * Virtual network $VnetName does not exist,create it,vnet prefix $VnetPrefix" -ForegroundColor Green
  $Nid = AutoGenerate-AzureRmNetworkInterface -Location $LocationName -ResourceGroupName $ResourceGroupName -VMName $VMName -VnetName $VnetName -VnetPrefix $VnetPrefix -SubnetName $SubnetName -SubnetPrefix $SubnetPrefix -PublicIPAllocationMethod $PublicIPAllocationMethod -Create
  }
  else
  {
  Write-Host "$(Get-Date) * Virtual network $VnetName exist" -ForegroundColor Green
  $Nid = AutoGenerate-AzureRmNetworkInterface -Location $LocationName -ResourceGroupName $ResourceGroupName -VMName $VMName -VnetName $VnetName -VnetPrefix $VnetPrefix -SubnetName $SubnetName -SubnetPrefix $SubnetPrefix -PublicIPAllocationMethod $PublicIPAllocationMethod
  }
  If ($Nid)
  {
  Write-Host "$(Get-Date) * Creating VM $VMName ..." -ForegroundColor Green
  if ($AvailabilitySetName)
  {
  Write-Host "$(Get-Date) * Verify availability set" -ForegroundColor Green
  $AvailabilitySet = Get-AzureRmAvailabilitySet -ResourceGroupName $ResourceGroupName -Name $AvailabilitySetName -ErrorAction SilentlyContinue
  if (!$AvailabilitySet)
  {
  write-host "$(Get-Date) * AvailabilitySet $AvailabilitySetName does not exist, create a new one" -ForegroundColor Green
  $AvailabilitySet = New-AzureRmAvailabilitySet -ResourceGroupName $ResourceGroupName -Name $AvailabilitySetName -Location $LocationName -ErrorAction Stop
  $VM = New-AzureRmVMConfig -VMName $VMName -VMSize $VMSizeName -AvailabilitySetId $AvailabilitySet.Id -ErrorAction Stop
  }
  else
  {
  $VM = New-AzureRmVMConfig -VMName $VMName -VMSize $VMSizeName -AvailabilitySetId $AvailabilitySet.Id -ErrorAction Stop
  }
  }
  else
  {
  $VM = New-AzureRmVMConfig -VMName $VMName -VMSize $VMSizeName -ErrorAction Stop
  }
  }
  #Choose source image
  #$VM = Set-AzureRmVMSourceImage -VM $VM -PublisherName $PublisherName -Offer $OfferName -Skus $SkusName -Version "latest" -ErrorAction Stop
  #Add the network interface to the configuration.
  $VM = Add-AzureRmVMNetworkInterface -VM $VM -Id $Nid -ErrorAction Stop
  $DiskName = "vmosdisk"
  #$vmConfig = Set-AzureRmVMOSDisk -VM $vmConfig -Name $osDiskName -VhdUri $destinationVhd -CreateOption Attach -Linux
  #$VM = Set-AzureRmVMOSDisk -VM $VM -Name $DiskName -VhdUri $OSDiskUri -CreateOption fromImage -Caching $OSDiskCaching -ErrorAction Stop
  if ($OS -eq "Windows")
  {
  $VM = Set-AzureRmVMOSDisk -VM $VM -Name $DiskName -VhdUri $VhdUri -CreateOption attach -Caching None -Windows -ErrorAction Stop
  }
  else
  {
  $VM = Set-AzureRmVMOSDisk -VM $VM -Name $DiskName -VhdUri $VhdUri -CreateOption attach -Caching None -Linux -ErrorAction Stop
  }
  #Create a virtual machine
  if ($HybridBenefit)
  {
  Write-Host "$(Get-Date) * Hybrid Benefit enabled for VM $VMName !" -ForegroundColor Green
  New-AzureRmVM -ResourceGroupName $ResourceGroupName -Location $LocationName -VM $VM -ErrorAction Stop -LicenseType "Windows_Server" | Out-Null
  }
  else
  {
  New-AzureRmVM -ResourceGroupName $ResourceGroupName -Location $LocationName -VM $VM -ErrorAction Stop | Out-Null
  }
  Write-Host "$(Get-Date) * Create virtual machine $VMName successfully!" -ForegroundColor Green
  #Set private nic to static
  
  }
  }
  else
  {
  Write-Host -ForegroundColor Red "$(Get-Date) * VM Size $VMSizeName does not exist."
  }
  }
  }
  }
  
}
  
catch
  
{
  Write-Host -ForegroundColor Red "$(Get-Date) * Create a virtual machine $VMName failed" $_.Exception.Message
  
}



运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-561037-1-1.html 上篇帖子: 一次应对PowerShell+WMI挖矿***的记录 下篇帖子: PowerShell 运维菜鸟系列-02-批量取n台Windows KEY(2018年大年初一奉献)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表