Attaching disks to VMs - error

Hello there,

I’ve created a script which in first place is creating new disks and later I’d like to attach those new disks to existing VMs.
Here is piece of script to attach the disks:

foreach ($D in $Disks)
{
    Add-AzVMDataDisk -VM (Get-AzVM -ResourceGroupName $D.RG -Name ($D.VM).Split('/')[8]) -CreateOption Attach -ManagedDiskId (Get-AzDisk -ResourceGroupName $D.RG -DiskName $D.DiskName).Id -Caching ReadWrite
    Update-AzVM -ResourceGroupName $D.RG -VM (Get-AzVM -ResourceGroupName $D.RG -Name ($D.VM).Split('/')[8])
}

But I’m getting such error:

Generic types are not supported for input fields at this time.
At line:1 char:1
+ Add-AzVMDataDisk -VM $VM -Name "DiskName" -CreateOption At ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : Argument

More details:

PS C:\Users\wikolo> $error[0] | fl * -Force



PSMessageDetails      :
Exception             : System.Management.Automation.RuntimeException: Generic types are not supported for input fields at this time. ---> System.Management.Automation.PSArgumentException: Generic types are not supported for input fields at 
                        this time.
                           at Microsoft.PowerShell.EditorServices.Services.PowerShellContext.FieldDetails..ctor(String name, String label, Type fieldType, Boolean isMandatory, Object defaultValue)
                           at Microsoft.PowerShell.EditorServices.Services.PowerShellContext.FieldDetails.Create(FieldDescription fieldDescription, ILogger logger)
                           at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
                           at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
                           at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
                           at Microsoft.PowerShell.EditorServices.Services.PowerShellContext.EditorServicesPSHostUserInterface.Prompt(String promptCaption, String promptMessage, Collection`1 fieldDescriptions)
                           at System.Management.Automation.Internal.Host.InternalHostUserInterface.Prompt(String caption, String message, Collection`1 descriptions)
                           at System.Management.Automation.CmdletParameterBinderController.PromptForMissingMandatoryParameters(Collection`1 fieldDescriptionList, Collection`1 missingMandatoryParameters)       
                           at System.Management.Automation.CmdletParameterBinderController.HandleUnboundMandatoryParameters(Int32 validParameterSetCount, Boolean processMissingMandatory, Boolean promptForMandatory, Boolean
                        isPipelineInputExpected, Collection`1& missingMandatoryParameters)
                           at System.Management.Automation.CmdletParameterBinderController.BindCommandLineParameters(Collection`1 arguments)
                           at System.Management.Automation.CommandProcessor.BindCommandLineParameters()
                           at System.Management.Automation.CommandProcessor.Prepare(IDictionary psDefaultParameterValues)
                           at System.Management.Automation.CommandProcessorBase.DoPrepare(IDictionary psDefaultParameterValues)
                           at System.Management.Automation.Internal.PipelineProcessor.Start(Boolean incomingStream)
                           at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(Object input)
                           at System.Management.Automation.PipelineOps.InvokePipeline(Object input, Boolean ignoreInput, CommandParameterInternal[][] pipeElements, CommandBaseAst[] pipeElementAsts, CommandRedirection[][] commandRedirections,   
                        FunctionContext funcContext)
                           at System.Management.Automation.Interpreter.ActionCallInstruction`6.Run(InterpretedFrame frame)
                           at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
                           --- End of inner exception stack trace ---
TargetObject          :
CategoryInfo          : InvalidArgument: (:) [], RuntimeException
FullyQualifiedErrorId : Argument
ErrorDetails          :
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {}

Can someone explain what the error is about?
Also for Add-AzVMDataDisk - is there a way to select first free LUN by script or I have to provide LUN number? I have sometimes 2-3 disks to attach to the same VM. Can the LUN number be scripted to grow incrementally?

Best regards,
Wiktor

Ah and if I run it with LUN it look like this:

foreach ($D in $Disks)
{
    Add-AzVMDataDisk -VM (Get-AzVM -ResourceGroupName $D.RG -Name ($D.VM).Split('/')[8]) -Name $D.DiskName -CreateOption Attach -ManagedDiskId (Get-AzDisk -ResourceGroupName $D.RG -DiskName $D.DiskName).Id -Caching ReadWrite -Lun 5
    Update-AzVM -ResourceGroupName $D.RG -VM (Get-AzVM -ResourceGroupName $D.RG -Name ($D.VM).Split('/')[8])
}

And there’s output:

ResourceGroupName       : RGName
Id                      : /subscriptions/xxx/resourceGroups/RGName/providers/Microsoft.Compute/virtualMachines/VMName
VmId                    : xxx
Name                    : VMName
Type                    : Microsoft.Compute/virtualMachines
Location                : southcentralus
LicenseType             : Windows_Server
Tags                    : {xxx}
DiagnosticsProfile      : {BootDiagnostics}
Extensions              : {BGInfo, IaaSAntimalware, MDE.Windows, MicrosoftMonitoringAgent, SiteRecovery-Windows, SqlIaasExtension}
HardwareProfile         : {VmSize}
NetworkProfile          : {NetworkInterfaces}
OSProfile               : {ComputerName, AdminUsername, WindowsConfiguration, Secrets, AllowExtensionOperations, RequireGuestProvisionSignal}
ProvisioningState       : Succeeded
StorageProfile          : {ImageReference, OsDisk, DataDisks}
ProximityPlacementGroup : {Id}


RequestId           :
IsSuccessStatusCode : True
StatusCode          : OK
ReasonPhrase        : OK