Hi, You can try this script:
# Import the AzureRM module
Import-Module AzureRM
# Authenticate to your Azure account
$connection = Get-AutomationConnection -Name 'AzureRunAsConnection'
Connect-AzureRmAccount -ServicePrincipal -TenantId $connection.TenantId `
-ApplicationId $connection.ApplicationId -CertificateThumbprint $connection.CertificateThumbprint
# Get the VM and NSG details
$vmName = 'VM1'
$resourceGroupName = 'YourResourceGroupName'
$nsgName = 'YourNSGName'
# Get the current time
$currentTime = Get-Date
# Define the time range for allowing the inbound rule
$allowStartTime = Get-Date -Year $currentTime.Year -Month $currentTime.Month -Day $currentTime.Day `
-Hour 9 -Minute 0 -Second 0 # Change to the desired start time
$allowEndTime = Get-Date -Year $currentTime.Year -Month $currentTime.Month -Day $currentTime.Day `
-Hour 17 -Minute 0 -Second 0 # Change to the desired end time
# Check if the current time is within the time range for allowing the inbound rule
if ($currentTime -ge $allowStartTime -and $currentTime -lt $allowEndTime) {
# Allow the inbound rule in the NSG
$nsg = Get-AzureRmNetworkSecurityGroup -ResourceGroupName $resourceGroupName -Name $nsgName
$ruleName = 'AllowInboundRule' # Change to the desired rule name
$rule = Get-AzureRmNetworkSecurityRuleConfig -Name $ruleName -Access Allow -Direction Inbound `
-Priority 100 -SourceAddressPrefix '*' -SourcePortRange '*' -DestinationAddressPrefix '*' `
-DestinationPortRange '*' -Protocol '*' # Change to the desired rule configuration
$nsg | Set-AzureRmNetworkSecurityRuleConfig -NetworkSecurityRule $rule | Set-AzureRmNetworkSecurityGroup
Write-Output 'Inbound rule has been allowed.'
} else {
# Deny the inbound rule in the NSG
$nsg = Get-AzureRmNetworkSecurityGroup -ResourceGroupName $resourceGroupName -Name $nsgName
$ruleName = 'AllowInboundRule' # Change to the desired rule name
$nsg | Remove-AzureRmNetworkSecurityRuleConfig -Name $ruleName | Set-AzureRmNetworkSecurityGroup
Write-Output 'Inbound rule has been denied.'
}