powershell 如何运行带有可选参数的脚本?

zbq4xfa0  于 2022-11-10  发布在  Shell
关注(0)|答案(1)|浏览(157)

我想运行一个在Azure中创建VM的脚本。
以下是必选参数:

$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'

我还想为PublicIpAddressNameDomainNameLabel提供两个可选参数:

$dnsName=''
$reservedIP= ''

其想法是,脚本应该检查这些参数是否为空。如果它们为空,则只需创建一个仅包含必需参数的VM:

$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

如果它们不是,我想用这两个额外的参数创建VM。
有人知道如何在PowerShell中做到这一点吗?

xqkwcwgp

xqkwcwgp1#

使用一条简单的if语句有条件地将条目添加到Splting表中:

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

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

相关问题