Description
Issue
When executing the Set-AzVMOSDisk cmdlet to specify an existing VHD file as OS disk with -CreateOption Attach.
After that, executing New-AzVM cmdlet to create VM using unmanaged disk, the VM creation failed with the error:
“Cannot attach an existing OS disk if the VM is created from a platform, user or a shared gallery image.”
Upon investigation, it appeared that a value was automatically inserted into $vm.StorageProfile.ImageReference.
It seems that is the cause of the error.
We set $vm.StorageProfile.ImageReference = $null before executing the New-AzVM cmdlet, however the value was automatically inserted during the New-AzVM process.
Environment
Azure Cloud Shell
Cmdlets
//setting
PS> $vm = New-AzVMConfig -VMName $vmName -VMSize $vmSize
PS> $vm = Set-AzVMOSDisk -VM $vm -Name "${vmName}-osdisk" -VhdUri $osVhdUri -CreateOption Attach -Windows
PS> $vm = Add-AzVMNetworkInterface -VM $vm -Id $nicId
// check $vm.StorageProfile.ImageReference
PS> $vm.StorageProfile.ImageReference
// null
// create VM
PS> New-AzVM -ResourceGroupName $resourceGroupName -Location $location -VM $vm -Debug -Verbose
Error
ErrorCode: InvalidParameter
ErrorMessage: Cannot attach an existing OS disk if the VM is created from a platform, user or a shared gallery image.
ErrorTarget: osDisk
StatusCode: 400
ReasonPhrase:
After executing New-AzVM cmdlets
PS> $vm.StorageProfile.ImageReference
Publisher : MicrosoftWindowsServer
Offer : WindowsServer
Sku : 2022-datacenter-azure-edition
Version : latest
ExactVersion :
SharedGalleryImageId :
CommunityGalleryImageId :
Id :
Issue script & Debug output
PS> $vm = New-AzVMConfig -VMName $vmName -VMSize $vmSize
PS> $vm = Set-AzVMOSDisk -VM $vm -Name "${vmName}-osdisk" -VhdUri $osVhdUri -CreateOption Attach -Windows
PS> $vm = Add-AzVMNetworkInterface -VM $vm -Id $nicId
PS> $vm.StorageProfile.ImageReference
// null
PS> $DebugPreference='Continue'
PS> New-AzVM -ResourceGroupName $resourceGroupName -Location $location -VM $vm -Debug -Verbose
DEBUG: 5:25:56 AM - [ConfigManager] Got [True] from [DisplaySecretsWarning], Module = [], Cmdlet = [].
DEBUG: 5:25:56 AM - NewAzureVMCommand begin processing with ParameterSet 'DefaultParameterSet'.
DEBUG: 5:25:56 AM - using account id 'MSI@50342'...
DEBUG: 5:25:56 AM - [ConfigManager] Got nothing from [DisplayBreakingChangeWarning], Module = [Az.Compute], Cmdlet = [New-AzVM]. Returning default value [True].
WARNING: Upcoming breaking changes in the cmdlet 'New-AzVM' :
The default VM size will change from 'Standard_D2s_v3' to 'Standard_D2s_v5'.
- This change will take effect on '11/1/2025'
- The change is expected to take effect in Az version : '15.0.0'
- The change is expected to take effect in Az.Compute version : '11.0.0'
Note : Go to https://aka.ms/azps-changewarnings for steps to suppress this breaking change warning, and other information on breaking changes in Azure PowerShell.
Confirm
Continue with this operation?
[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is "Y"): A
Confirm
Are you sure you want to perform this action?
Performing the operation "New" on target "<VM name>".
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"): A
DEBUG: [Common.Authentication]: Authenticating using Account: 'MSI@50342', environment: 'AzureCloud', tenant: '<tenant id>'
DEBUG: 5:25:59 AM - [ConfigManager] Got nothing from [DisableInstanceDiscovery], Module = [], Cmdlet = []. Returning default value [False].
DEBUG: 5:25:59 AM - [ManagedServiceIdentityAuthenticator] Calling ManagedIdentityCredential.GetTokenAsync - TenantId:'<tenant id>', Scopes:'https://management.core.windows.net/', UserId:''
DEBUG: ManagedIdentityCredential.GetToken invoked. Scopes: [ https://management.core.windows.net/ ] ParentRequestId:
DEBUG: False MSAL 4.65.0.0 MSAL.CoreCLR .NET 9.0.11 Linux [2026-02-10 05:25:59Z - 1b7158f8-cf63-4267-a7c7-471fc3214027] MSAL MSAL.CoreCLR with assembly version '4.65.0.0'. CorrelationId(1b7158f8-cf63-4267-a7c7-471fc3214027)
DEBUG: False MSAL 4.65.0.0 MSAL.CoreCLR .NET 9.0.11 Linux [2026-02-10 05:25:59Z - 1b7158f8-cf63-4267-a7c7-471fc3214027] === AcquireTokenForManagedIdentityParameters ===
ForceRefresh: False
Resource: https://management.core.windows.net/
DEBUG: False MSAL 4.65.0.0 MSAL.CoreCLR .NET 9.0.11 Linux [2026-02-10 05:25:59Z - 1b7158f8-cf63-4267-a7c7-471fc3214027]
=== Request Data ===
Authority Provided? - True
Scopes - https://management.core.windows.net/
Extra Query Params Keys (space separated) -
ApiId - AcquireTokenForSystemAssignedManagedIdentity
IsConfidentialClient - False
SendX5C - False
LoginHint ? False
IsBrokerConfigured - False
HomeAccountId - False
CorrelationId - 1b7158f8-cf63-4267-a7c7-471fc3214027
UserAssertion set: False
LongRunningOboCacheKey set: False
Region configured:
DEBUG: False MSAL 4.65.0.0 MSAL.CoreCLR .NET 9.0.11 Linux [2026-02-10 05:25:59Z - 1b7158f8-cf63-4267-a7c7-471fc3214027] === Token Acquisition (ManagedIdentityAuthRequest) started:
Scopes: https://management.core.windows.net/
Authority Host: login.microsoftonline.com
DEBUG: False MSAL 4.65.0.0 MSAL.CoreCLR .NET 9.0.11 Linux [2026-02-10 05:25:59Z - 1b7158f8-cf63-4267-a7c7-471fc3214027] [Internal cache] Total number of cache partitions found while getting access tokens: 1
DEBUG: False MSAL 4.65.0.0 MSAL.CoreCLR .NET 9.0.11 Linux [2026-02-10 05:25:59Z - 1b7158f8-cf63-4267-a7c7-471fc3214027] [FindAccessTokenAsync] Discovered 1 access tokens in cache using partition key: system_assigned_managed_identity_managed_identity_AppTokenCache
DEBUG: False MSAL 4.65.0.0 MSAL.CoreCLR .NET 9.0.11 Linux [2026-02-10 05:25:59Z - 1b7158f8-cf63-4267-a7c7-471fc3214027] [Region discovery] Not using a regional authority.
DEBUG: False MSAL 4.65.0.0 MSAL.CoreCLR .NET 9.0.11 Linux [2026-02-10 05:25:59Z - 1b7158f8-cf63-4267-a7c7-471fc3214027] Skipping Instance discovery for Aad authority because it is not enabled.
DEBUG: False MSAL 4.65.0.0 MSAL.CoreCLR .NET 9.0.11 Linux [2026-02-10 05:25:59Z - 1b7158f8-cf63-4267-a7c7-471fc3214027] Access token is not expired. Returning the found cache entry. [Current time (02/10/2026 05:25:59) - Expiration Time (02/10/2026 05:31:54 +00:00) - Extended Expiration Time (02/10/2026 05:11:36 +00:00)]
DEBUG: False MSAL 4.65.0.0 MSAL.CoreCLR .NET 9.0.11 Linux [2026-02-10 05:25:59Z - 1b7158f8-cf63-4267-a7c7-471fc3214027] [ManagedIdentityRequest] Access token retrieved from cache.
DEBUG: False MSAL 4.65.0.0 MSAL.CoreCLR .NET 9.0.11 Linux [2026-02-10 05:25:59Z - 1b7158f8-cf63-4267-a7c7-471fc3214027]
=== Token Acquisition finished successfully:
DEBUG: False MSAL 4.65.0.0 MSAL.CoreCLR .NET 9.0.11 Linux [2026-02-10 05:25:59Z - 1b7158f8-cf63-4267-a7c7-471fc3214027] AT expiration time: 2/10/2026 5:31:54 AM +00:00, scopes: https://management.core.windows.net/. source: Cache
DEBUG: False MSAL 4.65.0.0 MSAL.CoreCLR .NET 9.0.11 Linux [2026-02-10 05:25:59Z - 1b7158f8-cf63-4267-a7c7-471fc3214027]
[LogMetricsFromAuthResult] Cache Refresh Reason: NotApplicable
[LogMetricsFromAuthResult] DurationInCacheInMs: 0
[LogMetricsFromAuthResult] DurationTotalInMs: 0
[LogMetricsFromAuthResult] DurationInHttpInMs: 0
DEBUG: False MSAL 4.65.0.0 MSAL.CoreCLR .NET 9.0.11 Linux [2026-02-10 05:25:59Z - 1b7158f8-cf63-4267-a7c7-471fc3214027] TokenEndpoint: ****
DEBUG: ManagedIdentityCredential.GetToken succeeded. Scopes: [ https://management.core.windows.net/ ] ParentRequestId: ExpiresOn: 2026-02-10T05:31:54.2561775+00:00
DEBUG: [Common.Authentication]: Received token with LoginType 'User', Tenant: '<tenant id>', UserId: 'MSI@50342'
DEBUG: ============================ HTTP REQUEST ============================
HTTP Method:
PUT
Absolute Uri:
https://management.azure.com/subscriptions/<subscription id>/resourceGroups/<rg name>/providers/Microsoft.Compute/virtualMachines/<VM name>?api-version=2025-04-01
Headers:
Accept-Language : en-US
x-ms-client-request-id : d5edfed5-6c94-4813-a173-9952b3a7fc3f
Body:
{
"properties": {
"hardwareProfile": {
"vmSize": "Standard_B1ms"
},
"storageProfile": {
"imageReference": {
"publisher": "MicrosoftWindowsServer",
"offer": "WindowsServer",
"sku": "2022-datacenter-azure-edition",
"version": "latest"
},
"osDisk": {
"osType": "Windows",
"name": "<OS disk name>",
"vhd": {
"uri": "https://<storage account name>.blob.core.windows.net/<container name>/<file name>.vhd"
},
"writeAcceleratorEnabled": false,
"createOption": "Attach"
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/<subscription is>/resourceGroups/<rg name>/providers/Microsoft.Network/networkInterfaces/testvhdnic"
}
]
},
"securityProfile": {
"uefiSettings": {
"secureBootEnabled": true,
"vTpmEnabled": true
},
"securityType": "trustedlaunch"
},
"diagnosticsProfile": {
"bootDiagnostics": {
"enabled": true,
"storageUri": "https://<storage account name>.blob.core.windows.net/"
}
}
},
"location": "Japan East"
}
DEBUG: ============================ HTTP RESPONSE ============================
Status Code:
BadRequest
Headers:
Cache-Control : no-cache
Pragma : no-cache
x-ms-ratelimit-remaining-resource: Microsoft.Compute/PutVMSubscriptionMaximum;1499,Microsoft.Compute/PutVMResource;11
x-ms-need-to-refresh-epl-cache: False
Strict-Transport-Security : max-age=31536000; includeSubDomains
x-ms-request-id : 7cb71a12-e9c4-4ffe-acb2-fa9438966819
x-ms-operation-identifier : tenantId=<tenant id> ,objectId=14036b0f-2eba-4d5f-8a06-04bb60e286ab/japaneast/4031c67c-09dd-4ce9-99a6-24886ef6d4b2
x-ms-ratelimit-remaining-subscription-writes: 199
x-ms-ratelimit-remaining-subscription-global-writes: 2999
x-ms-correlation-request-id : f31b382f-77b2-401f-aca6-a18d70341e39
x-ms-routing-request-id : JAPANEAST:20260210T052559Z:f31b382f-77b2-401f-aca6-a18d70341e39
X-Content-Type-Options : nosniff
X-Cache : CONFIG_NOCACHE
X-MSEdge-Ref : Ref A: 69A1454818344BF0B2EEFE461D6121EA Ref B: SG2AA1040515060 Ref C: 2026-02-10T05:25:59Z
Date : Tue, 10 Feb 2026 05:25:59 GMT
Body:
{
"error": {
"code": "InvalidParameter",
"message": "Cannot attach an existing OS disk if the VM is created from a platform, user or a shared gallery image.",
"target": "osDisk"
}
}
DEBUG: 5:25:59 AM - [ConfigManager] Got nothing from [DisplayRegionIdentified], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: 5:25:59 AM - [ConfigManager] Got nothing from [CheckForUpgrade], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: 5:25:59 AM - No authentication telemetry is found for the current cmdlet with Id d5edfed5-6c94-4813-a173-9952b3a7fc3f.
DEBUG: AzureQoSEvent: Module: Az.Compute:11.2.0; CommandName: New-AzVM; PSVersion: 7.5.4; IsSuccess: True; Duration: 00:00:03.4962889; SanitizeDuration: 00:00:00
DEBUG: 5:25:59 AM - [ConfigManager] Got [True] from [EnableDataCollection], Module = [], Cmdlet = [].
DEBUG: 5:25:59 AM - NewAzureVMCommand end processing.
DEBUG: 5:25:59 AM - [ConfigManager] Got nothing from [EnableErrorRecordsPersistence], Module = [Az.Compute], Cmdlet = [New-AzVM]. Returning default value [False].
New-AzVM: Cannot attach an existing OS disk if the VM is created from a platform, user or a shared gallery image.
ErrorCode: InvalidParameter
ErrorMessage: Cannot attach an existing OS disk if the VM is created from a platform, user or a shared gallery image.
ErrorTarget: osDisk
StatusCode: 400
ReasonPhrase:
OperationID : 7cb71a12-e9c4-4ffe-acb2-fa9438966819
DEBUG: 5:25:59 AM - [ConfigManager] Got nothing from [DisplayBreakingChangeWarning], Module = [Az.Compute], Cmdlet = [New-AzVM]. Returning default value [True].
DEBUG: 5:25:59 AM - [ConfigManager] Got nothing from [DisplayRegionIdentified], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: 5:25:59 AM - [ConfigManager] Got nothing from [CheckForUpgrade], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: 5:25:59 AM - No authentication telemetry is found for the current cmdlet with Id d5edfed5-6c94-4813-a173-9952b3a7fc3f.
DEBUG: AzureQoSEvent: Module: Az.Compute:11.2.0; CommandName: New-AzVM; PSVersion: 7.5.4; IsSuccess: False; Duration: 00:00:03.4962889; SanitizeDuration: 00:00:00; Exception: Cannot attach an existing OS disk if the VM is created from a platform, user or a shared gallery image.
ErrorCode: InvalidParameter
ErrorMessage: Cannot attach an existing OS disk if the VM is created from a platform, user or a shared gallery image.
ErrorTarget: osDisk
StatusCode: 400
ReasonPhrase:
OperationID : 7cb71a12-e9c4-4ffe-acb2-fa9438966819;
DEBUG: 5:25:59 AM - NewAzureVMCommand end processing.
Environment data
**Azure Cloud Shell**
PS> $PSVersionTable
Name Value
---- -----
PSVersion 7.5.4
PSEdition Core
GitCommitId 7.5.4
OS Microsoft Azure Linux 3.0
Platform Unix
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0
Module versions
**Azure Cloud Shell**
PS> Get-Module Az*
ModuleType Version PreRelease Name ExportedCommands
---------- ------- ---------- ---- ----------------
Script 5.3.2 Az.Accounts {Add-AzEnvironment, Clear-AzConfig, Clear-AzContext, Clear-AzDefault…}
Script 11.2.0 Az.Compute {Add-AzGalleryInVMAccessControlProfileVersionRulesIdentity, Add-AzGalleryInVMAccessControlProfileVersionRulesPrivilege, Add-AzGalleryInVMAccessCon…
Script 7.24.1 Az.Network {Add-AzApplicationGatewayAuthenticationCertificate, Add-AzApplicationGatewayBackendAddressPool, Add-AzApplicationGatewayBackendHttpSetting, Add-Az…
Script 9.0.0 Az.Resources {Export-AzResourceGroup, Export-AzTemplateSpec, Get-AzDenyAssignment, Get-AzDeployment…}
Script 9.5.0 Az.Storage {Add-AzRmStorageContainerLegalHold, Add-AzStorageAccountManagementPolicyAction, Add-AzStorageAccountNetworkRule, Close-AzStorageFileHandle…}
Script 1.1.3 Az.Tools.Predictor {Disable-AzPredictor, Enable-AzPredictor, Open-AzPredictorSurvey, Send-AzPredictorRating}
Script 0.0.0.10 AzureAD.Standard.Preview {Add-AzureADApplicationOwner, Add-AzureADDeviceRegisteredOwner, Add-AzureADDeviceRegisteredUser, Add-AzureADDirectoryRoleMember…}
Script 0.9.3 AzurePSDrive
Error output
PS> Resolve-AzError
DEBUG: 5:37:38 AM - [ConfigManager] Got [True] from [DisplaySecretsWarning], Module = [], Cmdlet = [].
DEBUG: 5:37:38 AM - ResolveError begin processing with ParameterSet 'AnyErrorParameterSet'.
DEBUG: 5:37:38 AM - using account id 'MSI@50342'...
DEBUG: 5:37:38 AM - [ConfigManager] Got nothing from [DisplayBreakingChangeWarning], Module = [Az.Accounts], Cmdlet = [Resolve-AzError]. Returning default value [True].
DEBUG: 5:37:38 AM - [ConfigManager] Got [True] from [DisplaySecretsWarning], Module = [], Cmdlet = [].
HistoryId: 17
RequestId :
Message : Cannot attach an existing OS disk if the VM is created from a platform, user or a shared gallery image.
ErrorCode: InvalidParameter
ErrorMessage: Cannot attach an existing OS disk if the VM is created from a platform, user or a shared gallery image.
ErrorTarget: osDisk
StatusCode: 400
ReasonPhrase:
OperationID : 7cb71a12-e9c4-4ffe-acb2-fa9438966819
ServerMessage :
ServerResponse :
RequestMessage :
InvocationInfo : {New-AzVM}
Line : New-AzVM -ResourceGroupName $resourceGroupName -Location $location -VM $vm -Debug -Verbose
Position : At line:1 char:1
+ New-AzVM -ResourceGroupName $resourceGroupName -Location $location -V …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
StackTrace : at Microsoft.Azure.Commands.Compute.ComputeClientBaseCmdlet.ExecuteClientAction(Action action)
at Microsoft.Azure.Commands.Compute.NewAzureVMCommand.DefaultExecuteCmdlet()
at Microsoft.Azure.Commands.Compute.NewAzureVMCommand.ExecuteCmdlet()
at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.<>c__3`1.<ExecuteSynchronouslyOrAsJob>b__3_0(T c)
at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.ExecuteSynchronouslyOrAsJob[T](T cmdlet, Action`1 executor)
at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.ExecuteSynchronouslyOrAsJob[T](T cmdlet)
at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord()
HistoryId : 17
Description
Issue
When executing the Set-AzVMOSDisk cmdlet to specify an existing VHD file as OS disk with -CreateOption Attach.
After that, executing New-AzVM cmdlet to create VM using unmanaged disk, the VM creation failed with the error:
“Cannot attach an existing OS disk if the VM is created from a platform, user or a shared gallery image.”
Upon investigation, it appeared that a value was automatically inserted into $vm.StorageProfile.ImageReference.
It seems that is the cause of the error.
We set $vm.StorageProfile.ImageReference = $null before executing the New-AzVM cmdlet, however the value was automatically inserted during the New-AzVM process.
Environment
Azure Cloud Shell
Cmdlets
Error
ErrorCode: InvalidParameter
ErrorMessage: Cannot attach an existing OS disk if the VM is created from a platform, user or a shared gallery image.
ErrorTarget: osDisk
StatusCode: 400
ReasonPhrase:
After executing New-AzVM cmdlets
Publisher : MicrosoftWindowsServer
Offer : WindowsServer
Sku : 2022-datacenter-azure-edition
Version : latest
ExactVersion :
SharedGalleryImageId :
CommunityGalleryImageId :
Id :
Issue script & Debug output
Environment data
Module versions
Error output