I suggest you to explore the following method to connect azure VMs using PowerShell script. The method involves certain admin tasks on each VMs, prior to provide the PowerShell script to the users as follows
- Create Azure VM with preferred username and password
- Create SPNs corresponding to each rdp users who wanted to connect through PowerShell
- Create Azure Vault and save password for each users
- Prepare the PowerShell script and provide the script to the users. Users can easily connect the computer by running the script in PowerShell like PS D:\> .\rdp.ps1
Create Azure Vault New-AzKeyVault -Name "rdptestmanu" -ResourceGroupName "webapp" -Location "centralus"
Save the VM rdp password to the Vault. Here I set my VM password as Passw0rd@123
$secretvalue = ConvertTo-SecureString "Passw0rd@123" -AsPlainText -Force
$secret = Set-AzKeyVaultSecret -VaultName "rdptestmanu" -Name "rdp1" -SecretValue $secretvalue
Create SPNs
az ad sp create-for-rbac --role="Reader" --name rdpsp
The cmdlet will create the SPN and provide a similar output as below:
{
"appId": "73dad345-4c05-11f7-b99b-666d5r68dff6",
"displayName": "rdpsp",
"name": "73dad345-4c05-11f7-b99b-666d5r68dff6",
"password": "Xx25q4L_tKsN-.T2.GRkWOUT.s7hT0tD88",
"tenant": "67f4a13c-fa4r-4b14-bs86-fw934d00931j"
}
Get the SPN Id similar to the following: Get-AzadServicePrincipal -ServicePrincipalName 73dad345-4c05-11f7-b99b-666d5r68dff6
Id : 531bcg92-af2a-493d-b84f-f6ddfa00d481
Assign the permission to SPN to extract the password from the Vault: Set-AzKeyVaultAccessPolicy -VaultName rdptestmanu -ObjectId 531bcg92-af2a-493d-b84f-f6ddfa00d481 -PermissionsToSecrets get,list
Prepare rdp file with the following contents, save as .ps1 file
$password = ConvertTo-SecureString "Xx25q4L_tKsN-.T2.GRkWOUT.s7hT0tD88" -AsPlainText -Force
$psCredential = New-Object System.Management.Automation.PSCredential('73dad345-4c05-11f7-b99b-666d5r68dff6', $password)
Connect-AzAccount -ServicePrincipal -Credential $psCredential -Tenant "67f4a13c-fa4r-4b14-bs86-fw934d00931j"
$secret = Get-AzKeyVaultSecret -VaultName "rdptestmanu" -Name "rdp1" -AsPlainText
cmdkey /generic:'server ip address' /user:manuphilip /pass:$secret
mstsc.exe /v: 'server ip address'
exit
Users can easily connect the computer by running the script in PowerShell like PS D:\> .\rdp.ps1. They don't need to enter the password as the password is going to be fetched from the vault
--please don't forget to upvote
and Accept as answer
if the reply is helpful--