0

I would like to run a script which creates a VM in Azure.

These are the mandatory parameters:

$cred = Get-Credential -Message "Enter a username and password for the virtual machine."
$RG = 'AZ-PS-RG'
$VM_NAME = 'AZ-PS-VM'
$location = 'francecentral'
$image = 'UbuntuLTS'
$size = 'Standard_D2s_v3'
$vnetName='myVNet'
$SubnetName = 'mySubnet-ps'

I would also like to provide two optional parameters for PublicIpAddressName and DomainNameLabel:

$dnsName=''
$reservedIP= ''

The idea is that the script should check if those parameters are empty or not. If they are empty then simply create a VM with only mandatory parameters:

$vmParams = @{
  ResourceGroupName = $RG
  Name = $VM_NAME
  Location = $location
  ImageName = $image
  Credential = $cred
  VirtualNetworkName = $vnetName
  SubnetName = $SubnetName
  Size = $size
  # these two I would like to run only if they are provided
  PublicIpAddressName = $reservedIP
  DomainNameLabel = $dnsName

}
$newVM1 = New-AzVM @vmParams

If they are not, I would like to create the VM with these two additional parameters.

Does anyone know how to do it in Powershell?

5
  • And which parameters on New-AzVM would you like to bind/map $dnsName and $reservedIP to, if present? Commented Aug 22, 2022 at 7:44
  • Yes, exactly @MathiasR.Jessen. I want these parametrs to be optional while creating VM Commented Aug 22, 2022 at 7:55
  • But which parameters? New-AzVM has neither a -dnsName nor a -reservedIP parameter defined? Commented Aug 22, 2022 at 9:13
  • @MathiasR.Jessen -PublicIpAddressName = $reservedIP and -DomainNameLabel = $dnsName Commented Aug 22, 2022 at 9:34
  • Inside the Hash for splatting, you do not use the hyphen in front of the parameter name Commented Aug 22, 2022 at 11:06

1 Answer 1

1

Use a simple if statement to conditionally add entries to the splatting table:

if(-not [string]::IsNullOrWhiteSpace($dnsName)){
    $vmParams['DomainNameLabel'] = $dnsName
}

if(-not [string]::IsNullOrWhiteSpace($reservedIP)){
    $vmParams['PublicIpAddressName'] = $reservedIP
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.