Forum Discussion
Need help with Azure VM reboot which checks users logged in.
Take this:
I created this script and tested it in Runbook. But getting an error.
The script:
workflow Restart-AVDVMsIfNoUser {
param (
[Parameter(Mandatory = $true)]
[string] $ResourceGroupName,
[Parameter(Mandatory = $true)]
[string[]] $VMNames,
[Parameter(Mandatory = $true)]
[string] $HostPoolName
)
InlineScript {
# Authenticate to Azure
Connect-AzAccount -Identity
# Loop through each VM name
foreach ($VMName in $using:VMNames) {
# Retrieve active user sessions on the VM
$userSessions = Get-AzWvdUserSession -ResourceGroupName $using:ResourceGroupName -HostPoolName $using:HostPoolName -Name $VMName
# Check if there are any active user sessions
if ($userSessions.Count -eq 0) {
# No users are logged in, restart the VM
Write-Output "Restarting VM: $VMName as no users are logged in"
Restart-AzVM -ResourceGroupName $using:ResourceGroupName -Name $VMName
}
else {
# Users are logged in, do not restart the VM
Write-Output "Not restarting VM: $VMName as users are logged in"
}
}
}
}
# Example usage of the workflow
Restart-AVDVMsIfNoUser -ResourceGroupName "YourResourceGroupName" -VMNames @("VM1Name", "VM2Name", "VM3Name") -HostPoolName "YourHostPoolName"
Getting error: A parameter cannot be found that matches parameter name 'Name'.
Sharing Output:
PSComputerName : localhost
PSSourceJobInstanceId : aab7e04e-c0d7-47f2-a8d4-a66f23ba8550
Environments : {AzureCloud, AzureUSGovernment, AzureChinaCloud, AzureGermanCloud}
Context : Microsoft.Azure.Commands.Profile.Models.Core.PSAzureContext
A parameter cannot be found that matches parameter name 'Name'.
Restarting VM: VM1Name as no users are logged in
PSComputerName : localhost
PSSourceJobInstanceId : aab7e04e-c0d7-47f2-a8d4-a66f23ba8550
OperationId : 0310417d-d60f-4c0e-805a-b4360e2de05f
Status : Succeeded
StartTime : 3/11/2024 4:35:10 PM
EndTime : 3/11/2024 4:37:09 PM
Error :
Name :
A parameter cannot be found that matches parameter name 'Name'.
Restarting VM: VM2Name as no users are logged in
PSComputerName : localhost
PSSourceJobInstanceId : aab7e04e-c0d7-47f2-a8d4-a66f23ba8550
OperationId : 6cd1cce4-a54a-4f66-8fc0-8b39d136af15
Status : Succeeded
StartTime : 3/11/2024 4:37:09 PM
EndTime : 3/11/2024 4:40:06 PM
Error :
Name :
A parameter cannot be found that matches parameter name 'Name'.
Restarting VM: VM3Name as no users are logged in
PSComputerName : localhost
PSSourceJobInstanceId : aab7e04e-c0d7-47f2-a8d4-a66f23ba8550
OperationId : f80f81b4-735e-4314-8b1c-2ec888a3ef44
Status : Succeeded
StartTime : 3/11/2024 4:40:06 PM
EndTime : 3/11/2024 4:42:01 PM
Error :
Name :