Azure Custom script extension issue - azure

I am trying to add a custom script extension to a virtual machine and running the below command but it is giving below error.
Command Used:
Set-AzVMCustomScriptExtension -Location "East US" -VMName "TINFAD01" -Name "TINFAD01DSC" -StorageAccountName "p1caddraassbdevdevdiag" -StorageAccountKey "XXXXXX" -FileName "TINFAD01.ps1" -ContainerName "dscfiles"| Update-AzVM -Verbose
**Error** PS C:\WINDOWS\system32> Set-AzVMCustomScriptExtension -Location "East US" -VMName "TINFAD01" -Name "TINFAD01DSC" -StorageAccountName "p1caddraassbdevdevdiag" -StorageAccountKey "D4o3I7fzY3vuxhRHJ1yAEkOklCIETqmoK voq0ISDMb6wQqyVF5AVaNMl05v9foABwOeQ/+a604HioP7smE3gqQ==" -FileName "TINFAD01.ps1" -ContainerName "dscfiles" | Update-AzVM -Verbose
cmdlet Set-AzVMCustomScriptExtension at command pipeline position 1 Supply values for the following parameters: (Type !? for Help.) ResourceGroupName: p1cad-draas-sb-dev-dev Set-AzVMCustomScriptExtension : Object reference not set to an instance of an object. At line:1 char:1
+ Set-AzVMCustomScriptExtension -Location "East US" -VMName "TINFAD01" ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Set-AzVMCustomScriptExtension], NullReferenceException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.SetAzureVMCustomScriptExtensionCommand

Here is powershell command to add custom extension to a virtual machine:
Set-AzVMCustomScriptExtension
[-ResourceGroupName] <String>
[-VMName] <String>
[-Name <String>]
-ContainerName <String>
-FileName <String[]>
[-StorageAccountName <String>]
[-StorageEndpointSuffix <String>]
[-StorageAccountKey <String>]
[-Run <String>]
[-Argument <String>]
[-SecureExecution]
[-TypeHandlerVersion <String>]
[-Location <String>]
[-DisableAutoUpgradeMinorVersion]
[-ForceRerun <String>]
[-NoWait]
[-DefaultProfile <IAzureContextContainer>]
[-WhatIf]
[-Confirm]
[<CommonParameters>]
By looking at you code it clearly says that you have not provided the resource name:
Set-AzVMCustomScriptExtension -Location "East US" -VMName "TINFAD01" -Name "TINFAD01DSC" -StorageAccountName "p1caddraassbdevdevdiag" -StorageAccountKey "XXXXXX" -FileName "TINFAD01.ps1" -ContainerName "dscfiles"| Update-AzVM -Verbose
Please provide the resource group information and see if it helps.
Additional reference:
https://learn.microsoft.com/en-us/powershell/module/az.compute/set-azvmcustomscriptextension?view=azps-3.0.0
Feel free to tag me in your conversation for additional help.

Related

I need to Specify OS Disk Name while Creating Azure VMSS using PowerShell

I want to Specify OS Disk Name while Creating VMSS using PowerShell to overcome the random OS Disk name like "VMSSNAME_1686_disk1_b5f021da0ba7409fbe7d028bdd50".
Command :
Set-AzVmssStorageProfile $vmssConfig `
-OsDiskCreateOption "FromImage" `
-ImageReferenceId $galleryImage.Id -OsDiskName $OSDiskName
# Set up information for authenticating with the virtual machine
Set-AzVmssOsProfile $vmssConfig `
-AdminUsername $username `
-AdminPassword $Password `
-ComputerNamePrefix "UKSSPAG"
# Attach the virtual network to the config object
Add-AzVmssNetworkInterfaceConfiguration -VirtualMachineScaleSet $vmssConfig -Name "NICConfig" -Primary $true -IPConfiguration $ipConfig
# Create the scale set with the config object (this step might take a few minutes)
New-AzVmss -ResourceGroupName $resourceGroup -VMScaleSetName $scaleSetName -VirtualMachineScaleSet $vmssConfig
Error :
New-AzVmss : Parameter 'osDisk.name' is not allowed.
ErrorCode: InvalidParameter
ErrorMessage: Parameter 'osDisk.name' is not allowed.
ErrorTarget: osDisk.name
StatusCode: 400
ReasonPhrase: Bad Request
OperationID : e97450a3-ed89-46f8-84fa-6779a002a3e9
At line:1 char:1
+ New-AzVmss -ResourceGroupName $resourceGroup -VMScaleSetName $scaleSe ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzVmss], ComputeCloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.Automation.NewAzureRmVmss

Availability Set in Availability Zone Arm Configuration

I'm trying to build out a script which deploys a vm into an availability set within an Azure availability zone.
However I keep getting the following error. I think (guessing) that it's to do with the fact the av set is not deployed to the same zone as the vm, but cannot find anywhere to set the zone on the availability set.
Error:
New-AzResourceGroupDeployment : 22:41:38 - Error: Code=InvalidRequestContent; Message=The request content was invalid and could not be deserialized: 'Could not find member 'zone' on
object of type 'TemplateResource'. Path 'properties.template.resources[3].zone', line 217, position 17.'.
At C:\ps\test-vm-build.ps1:182 char:7
+ New-AzResourceGroupDeployment -Name "SapTestDeploy" -ResourceGr ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [New-AzResourceGroupDeployment], Exception
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.NewAzureResourceGroupDeploymentCmdlet
The ARM template has been uploaded to:
https://pastebin.com/embed_js/5Afn6Pip
Hoping someone has ome across this and can point me in the right direction, Thanks in advance :)
Create an availability set:
New-AzAvailabilitySet `
-Location "EastUS" `
-Name "myAvailabilitySet" `
-ResourceGroupName "myResourceGroupAvailability" `
-Sku aligned `
-PlatformFaultDomainCount 2 `
-PlatformUpdateDomainCount 2
Create a Virtual Machine inside the availability set:
New-AzVm `
-ResourceGroupName "myResourceGroupAvailability" `
-Name "myVM$i" `
-Location "East US" `
-VirtualNetworkName "myVnet" `
-SubnetName "mySubnet" `
-SecurityGroupName "myNetworkSecurityGroup" `
-PublicIpAddressName "myPublicIpAddress$i" `
-AvailabilitySetName "myAvailabilitySet" `
-Credential $cred
UPDATE (Location/UpdateDomain/FaultDomain):
New-AzAvailabilitySet
[-ResourceGroupName] <String>
[-Name] <String>
[-Location] <String>
[[-PlatformUpdateDomainCount] <Int32>]
[[-PlatformFaultDomainCount] <Int32>]
[[-Sku] <String>]
[-ProximityPlacementGroupId <String>]
[-Tag <Hashtable>]
[-AsJob]
[-DefaultProfile <IAzureContextContainer>]
[<CommonParameters>]
UPDATE:
Powershell to move a VM to an Availability Zone:
https://github.com/kpantos/azure-automation/blob/master/powershell/change-vm-zone.ps1

Cannot parse the request - MissingJsonReferenceId : Error while creating NIC using PowerShell Az command

I am using below Az PowerShell command to create the NIC for virtual machine.
# Create a NIC for the web server VM.
$nicVMweb = New-AzNetworkInterface -ResourceGroupName $rgName -Location $location `
-Name $VmFrontendNICCardName -PublicIpAddress $publicipvm1 `
-NetworkSecurityGroup $nsgfe -Subnet $virtualNetwork.Subnets[0]
Cannot parse the request. StatusCode: 400 ReasonPhrase: Bad Request ErrorCode: InvalidRequestFormat ErrorMessage: Cannot parse the request. Additional details: Code: MissingJsonReferenceId Message: Value for
| reference id is missing. Path properties.ipConfigurations[0].properties.subnet. OperationID : 78525e42-a036-460f-10f9-5b993b7ca5e6
Issue Resolved by Below PowerShell
$Subnet = Get-AzVirtualNetwork -Name $virtualNetworkName -ResourceGroupName $rgName
$IPconfig = New-AzNetworkInterfaceIpConfig -Name $VmFrontendIpConfigName -PrivateIpAddressVersion IPv4 -PrivateIpAddress "10.0.0.10" -SubnetId $Subnet.Subnets[0].Id
$nicVMweb = New-AzNetworkInterface -Name $VmFrontendNICCardName -ResourceGroupName $rgName -Location $location -IpConfiguration $IPconfig
What is the issue in first command?
Could not reproduce your issue, your first command works fine on my side.
$virtualNetwork = Get-AzVirtualNetwork -Name "<vnet-name>" -ResourceGroupName "<group-name>"
$publicipvm1 = Get-AzPublicIpAddress -ResourceGroupName <group-name> -Name joyvm-ip2
$nsgfe = Get-AzNetworkSecurityGroup -Name joyvm-nsg -ResourceGroupName <group-name>
$nicVMweb = New-AzNetworkInterface -ResourceGroupName <group-name> -Location "West US 2" -Name "joyinter" -PublicIpAddress $publicipvm1 -NetworkSecurityGroup $nsgfe -Subnet $virtualNetwork.Subnets[0]
For this issue, it may be related to the version of Az.Network module, I use the 3.3.0 version, try to update it to the latest version:
Update-Module -Name Az.Network

Set-AzVMCustomScriptExtension in catch?

Attempting to add an extension when not detected but keep failing to find the secret sauce to get this to work. Mind you I am a BASH guy and this is a first foray into PowerShell..
#requires -version 2
# Required parameter $subscription: name of the subscription to enable Custom Script Extensions in
param (
# NOTE: See below for reason...
# [Parameter(Mandatory = $true)] [String] $subscription
# NOTE: Prompting is great for using the script interactively, but if this will also be executed
# from a build server or ...
# NOTE: Once the parameter is marked as mandatory PowerShell it will prompt for value. That said,
# if you remove the mandatory attribute then you can set a default value as a T_THROW ...
# NOTE: This _does_ contain shortcomings if this will be used as a pipeline param ...
# https://stackoverflow.com/questions/33600279/is-it-possible-to-force-powershell-script-to-throw-if-a-required-pipeline-para
[Parameter()]
[ValidateNotNullOrEmpty()]
[String]$SubscriptionName=$(Throw "`SubscriptionName` is mandatory, please provide a value...")
)
# Connect to the current Azure account
Write-Output "Pulling Azure account credentials..."
Start-Process "https://microsoft.com/devicelogin" # steals focus...
# Login to Azure account
Connect-AzAccount
# Set the active subscription
$null = Get-AzSubscription -SubscriptionName "$SubscriptionName" |Set-AzContext
# TODO: error handling
$vms = Get-AzVM
$cseName = "VulnerabilityManagementTools"
ForEach ($vm in $vms) {
try {
$cseStatus = Get-AzVMCustomScriptExtension `
-ResourceGroupName $vm.ResourceGroupName `
-VMName $vm.Name `
-Name $cseName `
-Status
}
catch {
Write-Output "Enabling Custom Script Extension for $vm."
Set-AzVMCustomScriptExtension `
-ResourceGroupName $vm.ResourceGroup `
-Location $vm.Location `
-VMName $vm.Name `
-Name $cseName `
-TypeHandlerVersion "1.1" `
-StorageAccountName "VulnerabilityManagementTools" `
-FileName "VulnerabilityManagementInstaller.ps1" `
-ContainerName "VulnerabilityManagementTools"
}
}
End up err'ing out with
PS /.../automation-scripts> ./EnableCustomScriptExtension.ps1 SubscriptionName
Pulling Azure account credentials...
WARNING: To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code XXXXXX to authenticate.
Account SubscriptionName TenantId Environment
------- ---------------- -------- -----------
XXXX#analytics.com SubName XXXXXX-XXXX AzureCloud
Get-AzVMCustomScriptExtension : The Resource 'Microsoft.Compute/virtualMachines/XXXX/extensions/VulnerabilityManagementTools' under resource group '{NAME}' was not found.
ErrorCode: ResourceNotFound
ErrorMessage: The Resource 'Microsoft.Compute/virtualMachines/XXXX/extensions/VulnerabilityManagementTools' under resource group '{NAME}' was not found.
ErrorTarget:
StatusCode: 404
ReasonPhrase: Not Found
At /.../automation-scripts/EnableCustomScriptExtension.ps1:59 char:18
+ $cseStatus = Get-AzVMCustomScriptExtension `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzVMCustomScriptExtension], ComputeCloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.GetAzureVMCustomScriptExtensionCommand
Get-AzVMCustomScriptExtension : The Resource 'Microsoft.Compute/virtualMachines/XXXXX/extensions/VulnerabilityManagementTools' under resource group '{RESOURCE_GROUPNAME}' was not found.
ErrorCode: ResourceNotFound
ErrorMessage: The Resource 'Microsoft.Compute/virtualMachines/XXXX/extensions/VulnerabilityManagementTools' under resource group '{RESOURCE_GROUPNAME}' was not found.
ErrorTarget:
StatusCode: 404
ReasonPhrase: Not Found
At /.../automation-scripts/EnableCustomScriptExtension.ps1:59 char:18
+ $cseStatus = Get-AzVMCustomScriptExtension `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzVMCustomScriptExtension], ComputeCloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.GetAzureVMCustomScriptExtensionCommand
Get-AzVMCustomScriptExtension : The Resource 'Microsoft.Compute/virtualMachines/{VMName}/extensions/VulnerabilityManagementTools' under resource group '{RESOURCEX_GROUPNAME}' was not found.
ErrorCode: ResourceNotFound
ErrorMessage: The Resource 'Microsoft.Compute/virtualMachines/{VMName}/extensions/VulnerabilityManagementTools' under resource group '{RESOURCEX_GROUPNAME}' was not found.
ErrorTarget:
StatusCode: 404
ReasonPhrase: Not Found
At /.../automation-scripts/EnableCustomScriptExtension.ps1:59 char:18
+ $cseStatus = Get-AzVMCustomScriptExtension `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzVMCustomScriptExtension], ComputeCloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.GetAzureVMCustomScriptExtensionCommand`
In your case, you just need to use the if(){}else{} statement, try the script as below instead of the ForEach part of yours, it works fine on my side.
ForEach ($vm in $vms) {
$cseStatus = Get-AzVMCustomScriptExtension `
-ResourceGroupName $vm.ResourceGroupName `
-VMName $vm.Name `
-Name $cseName `
-Status `
-ErrorAction SilentlyContinue
if ($cseStatus){
Write-Host "The extension has been set for" $vm.Name
}else{
Write-Host "Enabling Custom Script Extension for" $vm.Name
Set-AzVMCustomScriptExtension `
-ResourceGroupName $vm.ResourceGroup `
-Location $vm.Location `
-VMName $vm.Name `
-Name $cseName `
-TypeHandlerVersion "1.1" `
-StorageAccountName "VulnerabilityManagementTools" `
-FileName "VulnerabilityManagementInstaller.ps1" `
-ContainerName "VulnerabilityManagementTools"
}
}
Test result:
You'll need to create an Azure AD Service Principal using password authentication and use the credentials of this to pass to the Connect-AzAccount cmdlet as follows:
$credentials = Get-Credential
Connect-AzAccount -ServicePrincipal -Credentials $credentials
The service account will need to have the necessary permissions to use the Set-AzVMCustomScriptExtensions cmdlet.
More information on creating the service account here:
https://learn.microsoft.com/en-us/powershell/azure/create-azure-service-principal-azureps?view=azps-2.8.0

Create VM in Azure with powershell with no public IP

I'm creating VM on Azure from an Image using powershell.
This is the script I'm using .
$UserName = "username"
$Password = ConvertTo-SecureString "password#123" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($UserName, $Password)
New-AzureRmVm `
-ResourceGroupName "RSG" `
-Name "VMName" `
-ImageName "ImageName" `
-Location "West US" `
-VirtualNetworkName "VNName" `
-SubnetName "default" `
-Credential $psCred
-PublicIpAddressName "None" `
-OpenPorts 3389
But, when I got into the Azure portal and see, some Public Ip is getting assigned by default. I have also tried without giving PublicIpAddressName property assuming , it wont assign any IP, but still it is assigning.
I want the Public IP to be none.Can anyone help me achieve this.Thanks!
Currently this an issue which is still in Open state on official azure-powershell github. You can refer it here . Incase if you still want to bypass this you can try using New-AzureReservedIP or after the deployment command try to remove the public ip by yourself Remove-AzureRmPublicIpAddress.
Note : I have'nt tested it yet. Just an idea.
Refer : Docs
To set no public ip address you have can just define it as "" , in powershell you will need to quote that again so it will be """" .
If you are using PowerShell, then you will need to escape all empty parameters by changing "" to '""' to properly pass an empty string into the command. Without this, PowerShell will not pass the empty string, and you will get an error from the command indicating it's missing a parameter.
$winVmCred = Get-Credential `
-Message "Enter username and password for the Windows management virtual machine."
# Create a NIC for the VM.
$winVmNic = New-AzNetworkInterface -Name "winVMNIC01" `
-ResourceGroupName $resourceGroup.ResourceGroupName `
-Location $location `
-SubnetId $targetVMSubnet.Id `
-PrivateIpAddress "10.10.12.10"
# Configure the Windows management VM.
$winVmConfig = New-AzVMConfig -VMName $winVmName -VMSize $winVmSize | `
Set-AzVMOperatingSystem -Windows -ComputerName $winVmName -Credential $winVmCred | `
Set-AzVMSourceImage -PublisherName $winVmPublisher `
-Offer $winVmOffer `
-Skus $winVmSku `
-Version $winVmVersion | `
Add-AzVMNetworkInterface -Id $winVmNic.Id
# Create the VM.
$winVM = New-AzVM -ResourceGroupName $resourceGroup.ResourceGroupName `
-Location $location `
-VM $winVmConfig `
-ErrorAction Stop

Resources