Creating a VM in Azure using Powershell - powershell

I am trying to create a VM in Azure using powershell. I am running this on my local PC. I have been able to setup websites and SQL Azure instances without any issues but None of the samples on the web work.
Import-Module Azure
Import-AzurePublishSettingsFile -PublishSettingsFile "C:\Cloud\Azure.publishsettings"
$VMImage = #(Get-AzureVMImage | Where-Object -Property Label -Match "Windows Server 2012 R2 Datacenter, November 2014").ImageName
$myVMName = "jsTestVM1"
$myAdminName ="jsTestAdmin1"
$myAdminPwd ="not telling you"
New-AzureQuickVM -ImageName $VMImage -Windows -Name $myVMName -ServiceName $myVMName -AdminUsername $myAdminName -Password $myAdminPwd -InstanceSize "ExtraSmall"
I get the following message:
New-AzureQuickVM : ResourceNotFound: The hosted service does not exist.
At line:1 char:1
+ New-AzureQuickVM -ImageName $VMImage -Windows -Name $myVMName -ServiceName $myVM ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzureQuickVM], CloudException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.PersistentVMs.NewQuickVM
I've tried samples from the web and they give the same error message as well.
Edit:
If I specify a location I get the error message 'Service already exists, Location cannot be specified'.
If I specify AffinityGroup I get 'Service already exists, AffinityGroup cannot be specified'

$VMImage = #(Get-AzureVMImage | Where-Object -Property Label -Match "Windows Server 2012 R2 Datacenter, November 2014").ImageName
$myVMName = "srikstest"
$myAdminName ="srikstest"
$myAdminPwd ="NeitherMe"
New-AzureQuickVM -Windows -ServiceName $myVMName -ImageName $VMImage -AdminUsername $myAdminName - Password $myAdminPwd -InstanceSize "ExtraSmall" -Location "Southeast Asia" -Name $myVMName -Verbose
You can create a new Azure service for the virtual machine by specifying either the Location or AffinityGroup parameters, or deploy the new virtual machine into an existing service.
I've just added the location parameter and it worked !!

In the end I added an affinity group and changed the service name I was using. This enabled me to create the VM. The service name I was using was not in use as far as I was aware in my subscription so either a previous failed install left some artefact around or the name needs to be globally unique. I've checked the docs here
http://msdn.microsoft.com/en-us/library/azure/dn495183.aspx
and it doesn't state the service name needs to be globally unique

Assign/replace the value to variable.
New-AzureVMConfig -Name $VmName -InstanceSize $InstanceSize -Label $VmName -ImageName $Imagename -DiskLabel $DiskLabel |
add-azureprovisioningconfig -LinuxUser $cred.GetNetworkCredential().Username -Linux -Password $cred.GetNetworkCredential().Password -SSHPublicKeys $sshkey |
Add-AzureEndpoint -LocalPort $LocalPort1 -Name $LocalPortName1 -Protocol tcp -PublicPort $LocalPort1 |
New-AzureVM -ServiceName $CloudServiceName -AffinityGroup $AffinityGroup –WaitForBoot

Related

Error creating plan while provisioning Ubuntu DSVM using PowerShell

I'm trying to create an Ubuntu DSVM using PowerShell. I've determined that the Ubuntu DSVM image is released by publisher microsoft-ads, under offer linux-data-science-vm-ubuntu and SKU linuxdsvmubuntu. I gather that when specifying my VM config in PowerShell, I need to use Set-AzureRmVMPlan and Set-AzureRmVMSourceImage, and have tried the following:
$vmConfig = New-AzureRmVMConfig -VMName $vmName -VMSize Standard_D4s_v3
$vmConfig = Set-AzureRmVMPlan -VM $vmConfig -Name "linuxdsvmubuntu" -Product "linux-data-science-vm-ubuntu" -Publisher "microsoft-ads"
$vmConfig = Set-AzureRmVMOperatingSystem -VM $vmConfig -Linux -ComputerName $vmName -Credential $cred
$vmConfig = Set-AzureRmVMSourceImage -VM $vmConfig -PublisherName "microsoft-ads" -Offer "linux-data-science-vm-ubuntu" -Skus "linuxdsvmubuntu" -Version latest
$vmConfig = Add-AzureRmVMNetworkInterface -VM $vmConfig -Id $nic.Id
New-AzureRmVM -ResourceGroupName $rgName -Location $location -VM $vmConfig
Unfortunately, I get an error message from the New-AzureRmVM command:
New-AzureRmVM : This resource was created without a plan. A new plan cannot be associated with an update.
ErrorCode: CannotSetPlanOnUpdate
ErrorMessage: This resource was created without a plan. A new plan cannot be associated with an update.
StatusCode: 400
ReasonPhrase: Bad Request
OperationID : 648c62cd-4029-408e-8b6c-2ae4310001f6
At line:1 char:1
+ New-AzureRmVM -ResourceGroupName $rgName -Location $location -VM $vmC ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzureRmVM], ComputeCloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.NewAzureVMCommand
It seems that I might not be using Set-AzureRmVMPlan correctly. Is it clear to anyone what I'm doing wrong?
I discovered that the problem was not with this command itself, but apparently with a failed deployment from an earlier version of the command.
The first time I tried to use Set-AzureRmVMSourceImage, I was not aware that I needed to use Set-AzureRmVMPlan as well. This resulted in a failed deployment, which I assumed meant that the deployed VM would be deleted from my resource group (or never be added to my resource group in the first place).
What actually happened is that the failed deployment left a VM with status "Failed" in my resource group. When I later ran the commands shown above, the New-AzureRmVM command was treated as an update step instead of a brand new VM creation. That's why the error message indicates that, "This resource was created without a plan."
Deleting everything and starting over resulted in success with the commands above.

Unable to create Azure VM using Powershell

Using PS 5. 0 on windows 10 I created an Azure Storage account and an Azure Service. Got the latest image name using the following command. But when I run the following command to create a VM I get following error:
PS Command to get the latest image:
$images = Get-AzureVMImage `
| where { $_.ImageFamily -eq “Windows Server 2012 Datacenter” } `
| Sort-Object -Descending -Property PublishedDate
$latestImage = $images[0]
$latestImage
The above command ran successfully and gave me the image name as: a699494373c04fc0bc8f2bb1389d6106__Windows-Server-2012-R2-20171017-en.us-127GB.vhd that I used in the following command for creating a VM.
PS command to create VM:
New-AzureVMConfig -Name "Server15" -InstanceSize ExtraSmall -ImageName "a699494373c04fc0bc8f2bb1389d6106__Windows-Server-2012-R2-20171017-en.us-127GB.vhd" | Add-AzureProvisioningConfig -Windows -AdminUsername "MyAdmin" -Password "MyPsswd" | New-AzureVM -ServiceName "MyServiceName"
Error:
WARNING: No deployment found in service: 'MyServiceName'.
New-AzureVM : BadRequest: OSImage a699494373c04fc0bc8f2bb1389d6106__Windows-Server-2012-R2-20171017-en.us-127GB.vhd
not found. If you are using a VM image, it must be specified as VMImageName for the role, not as SourceImageName for
OSVirtualHardDisk.
OperationID : '498779aecff53369ac9e793da15c16c3'
At line:1 char:250
+ ... d "D7v.oeiue4ieiur" | New-AzureVM -ServiceName "MyServiceName"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzureVM], ComputeCloudException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.PersistentVMs.NewAzureVMCommand
Your script works for me, here is the output:
PS C:\Users\jason> New-AzureVMConfig -Name "Server16" -InstanceSize ExtraSmall -ImageName "a699494373c04fc0bc8f2bb1389d6106__Windows-Server-2012-R2-20171017-en.us-127GB.vhd" | Add-AzureProvisioningConfig -Windows -AdminUse
rname "jason" -Password "xxxxxxx" | New-AzureVM -ServiceName "jasontest321"
OperationDescription OperationId OperationStatus
-------------------- ----------- ---------------
New-AzureVM 05a8d386-ac4b-3843-8fe4-1018325112a3 Succeeded
Please check your Azure PowerShell version, for now the latest version is 5.0.1, my Azure PowerShell version is 4.4.1, that script works fine, maybe we should upgrade your Azure PowerShell.
We can download Azure PowerShell 5.0.1 installer to your Windows 10 and install it, then test it again.
More information about Azure PowerShell Version, please refer to this link.
Hope this helps.

Azure Runbooks - Missing PowerShell Cmdlets Or Not Executing Against a VM

I need to execute PowerShell on VMs from an Azure Automation Runbook, akin to a WinRm execution/PowerShell Remoting.
I have created an Azure Runbook through the Azure Automation GUI, and am trying to run a script that works perfectly against physical and virtual machines to get key system information and ports. I am able to authenticate in Azure and it appears that I can execute some aspects of the script (unless it's only running against the Azure Automation Worker) via the Azure Runbook, such as getting the installed PowerShell Version of the targeted VMs using: $PSVersionTable.PSVersion so I am not having issues with security/access from what I can tell.
However, several other components fail as follows, and I don't know if I need to import a Module to Azure Automation and if so, which ones. Or if this is failing because it is running against the Worker and not the VMs.
Here are some of the code snippets I am running:
$computerSystem = Get-CimInstance Win32_ComputerSystem
"CPU: " + $computerCPU.Name
Get-WmiObject -Class Win32_LogicalDisk |
Where-Object {$_.DriveType -ne 5} |
Sort-Object -Property Name |
Select-Object Name, VolumeName, FileSystem, Description, `
#{"Label"="DiskSize(GB)";"Expression"={"{0:N}" -f ($_.Size/1GB) -as [float]}}, `
#{"Label"="FreeSpace(GB)";"Expression"={"{0:N}" -f ($_.FreeSpace/1GB) -as [float]}}, `
#{"Label"="%Free";"Expression"={"{0:N}" -f ($_.FreeSpace/$_.Size*100) -as [float]}} |
Format-Table -AutoSize
Get-NetAdapter -Name "*" | Format-Table
Get-NetOffloadGlobalSetting | Format-List
Test-NetConnection -Port 80
Here are the error messages, which I strongly suspect are EITHER due to missing PowerShell Modules that I need to upload, but am unsure where to find these OR is this a situation where I am not targeting the VM correctly and instead running this against the AZ Host? (if so, any good examples of how to target a single VM):
Get-CimInstance : The specified service does not exist as an installed
service.
Get-WmiObject : The specified service does not exist as an installed
service.
Get-NetAdapter : The term 'Get-NetAdapter' is not recognized as the
name of a cmdlet, function, script file, or operable program.
Get-NetOffloadGlobalSetting : The term 'Get-NetOffloadGlobalSetting'
is not recognized as the name of a cmdlet, function, script file, or
operable program.
Test-NetConnection : The term 'Test-NetConnection' is not recognized
as the name of a cmdlet, function, script file, or operable program.
If it is an issue with targeting the VM properly, I need some guidance. I suspect that I am targeting the Worker running the Runbooks and not the actual VMs. I am using the RunAs account/the new Azure Automation security methods (not classic) so I don't believe certificates come into play. Here is how I am trying to target the VM (which I suspect is incorrect/should be changed):
$Resources = Get-AzureRmResource -ResourceType "Microsoft.Compute/virtualMachines" -ResourceGroupName "MyTestGroup" -ResourceName "MyTestVM"
ForEach ($Resource in $Resources)
{
# PowerShell Code from Above here
}
UPDATE 1:
Now that we have determined that I am not targeting the VM properly, I tried Joe's recommendation, but when I try to run the following I get an error on the WinRm. I found the Connect-AzureVM.ps1, but am unsure if this is old or aligns to the newer RunAs Connection I am using. Here is my current script that attempts to connect to the VM and Invoke PowerShell.
param(
[parameter(Mandatory=$true)][String] 'https://myvmname.eastus.cloudapp.azure.com:5986,
[parameter(Mandatory=$true)][String] 'MyVMName'
)
$connectionName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Add-AzureRmAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
}
}
# Get credentials to Azure VM
$Credential = Get-AutomationPSCredential -Name $VMCredentialName
Invoke-Command -ConnectionUri $Uri -Credential $Credential -ScriptBlock {
# My PowerShell Here
}
This is the error the script produces. I suspect its because I need to import/create a WinRM certificate on the VM I am targeting, but unsure if the Connect-AzureVM.ps1 is the right script to use or if there is another/more updated method to use for WinRM access:
[myvmname.eastus.cloudapp.azure.com] Connecting to remote server
myvmname.eastus.cloudapp.azure.com failed with the following error
message : WinRM cannot complete the operation. Verify that the
specified computer name is valid, that the computer is accessible
over the network, and that a firewall exception for the WinRM service
is enabled and allows access from this computer. By default, the
WinRM firewall exception for public profiles limits access to remote
computers within the same local subnet. For more information, see the
about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (myvmname.eastus.cloudapp.azure.com:String) [],
PSRemotingTransportException
+ FullyQualifiedErrorId : WinRMOperationTimeout,PSSessionStateBroken
Run this inside the VM at an elevated prompt
https://gist.github.com/jeffpatton1971/2321f0db8025e48ad8ec13c243153045
From inside your Runbook do whatever you normally to wire it up but create some session options to pass along your invoke-command.
$SessionOption = New-PSSessionOption -SkipCACheck -SkipCNCheck
Invoke-Command -ComputerName $VMname -Credential $Credential -UseSSL -SessionOption $SessionOption -ScriptBlock { }
You need to either add the VMs you want to run these scripts on as Azure Automation hybrid workers, so that you can target the script to run on them, or you need to, from your runbook running on Azure Automation's own workers, remote into each VM and from within the remoting block run the commands.
For the former, see: https://learn.microsoft.com/en-us/azure/automation/automation-hybrid-runbook-worker
For the ladder:
Invoke-Command -ConnectionUri $Uri -Credential $Credential -ScriptBlock {
$computerSystem = Get-CimInstance Win32_ComputerSystem
"CPU: " + $computerCPU.Name
Get-WmiObject -Class Win32_LogicalDisk |
Where-Object {$_.DriveType -ne 5} |
Sort-Object -Property Name |
Select-Object Name, VolumeName, FileSystem, Description, `
#{"Label"="DiskSize(GB)";"Expression"={"{0:N}" -f ($_.Size/1GB) -as [float]}}, `
#{"Label"="FreeSpace(GB)";"Expression"={"{0:N}" -f ($_.FreeSpace/1GB) -as [float]}}, `
#{"Label"="%Free";"Expression"={"{0:N}" -f ($_.FreeSpace/$_.Size*100) -as [float]}} |
Format-Table -AutoSize
Get-NetAdapter -Name "*" | Format-Table
Get-NetOffloadGlobalSetting | Format-List
Test-NetConnection -Port 80
}

Assign Network Security Group to a Virtual Machine Network Interface using PowerShell

I have existing NSG and VM and planning to add the NSG to existing VM's NIC and simultaneously remove as well. I have prepared this based on example provided in http://windowsitpro.com/azure/manage-network-security-groups-powershel. The below command failing with method not supported errors.
$NICName = 'azwebvm0186'
$RGName = 'Prod_ResourceGroup'
$NsgName = 'Prod_ILB_SG'
$NSG = Get-AzureRmNetworkSecurityGroup -Name $NsgName -ResourceGroupName $RGName
$NIC = Get-AzureRmNetworkInterface -Name $NICName -ResourceGroupName $RGname
$NIC.NetworkSecurityGroup = $NSG
Set-AzureRmNetworkInterface -NetworkInterface $NIC
its failing with below error
$NIC.NetworkSecurityGroup = $NSG : Specified method is not supported.
+ CategoryInfo : NotImplemented: (:) [], PSNotSupportedException
+ FullyQualifiedErrorId : NotSupported
I have tested in my lab, your script works for me. I think you had better check as the following ways:
1.Check $NSG and $NIC.NetworkSecurityGroup value and type. Please ensure they have the same type.
PS C:\Users\v-shshui> $NIC|gm
TypeName: Microsoft.Azure.Commands.Network.Models.PSNetworkInterface
2. Check your Azure Powershell version. My version is 3.3.0. You could get version by use the following cmdlet.
Get-Module -ListAvailable -Name Azure -Refresh
If your version is not latest, I suggest you could update your version to latest. You can download the PS version 3.3.0 installation file from this link

vSphere Powercli - The specified privileges are from a different server

I have the following powercli script to add a local account to an esx host.
With all my research I believe this should work but when I run it I get this error.
New-VIRole : 3/04/2014 9:23:49 a.m. New-VIRole The specified privileges are from a different server.
At .\test.ps1:18 char:11
+ New-VIRole <<<< -Name "CIM Only" -Privilege "CIM interaction"
+ CategoryInfo : InvalidArgument: (VMware.VimAutom...ent.Privilege[]:Privilege[]) [New-VIRole], VimException
+ FullyQualifiedErrorId : Core_NewVIRole_DoWork_PrivilegeFromDifferentServerSpecified,VMware.VimAutomation.ViCore.Cmdlets.Commands.PermissionManagement.NewVIRole`
Here is the script
## As usual, load needed PowerCLI cmdlets
asnp VMware.VimAutomation.Core -ErrorAction SilentlyContinue
# Define the ESXi server
$server = "servername"
#Connect to ESXi server
Connect-VIServer -Server $server -user user -password password
#Create a new role CIM, with the only needed privilege assigned to it
New-VIRole -Name "CIM Only" -Privilege "CIM interaction"
#Create the cimuser account, assign it to root group, and deny it shell access
New-VMHostAccount -Id cimuser -Password password -UserAccount:$true -AssignGroups root -GrantShellAccess:$false
#Assign the role CIM to the newly created cimuser account
New-VIPermission -Entity $server -Principal cimuser -Role "CIM Only"
#Disconnect from ESXi server
Disconnect-VIServer -Server $server -Confirm:$false
Any help greatly appreciated.
Try this:
New-VIRole -Name "CIM Only" -Privilege ( Get-VIPrivilege "CIM interaction" )
What esxi version are you running?