public/Enable-AzureNSGDiagnostics.ps1

function Enable-AzureNSGDiagnostics {

    [CmdletBinding()]

    Param (
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]$subscriptionName,
        

        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]$workspaceName
    
    )

    Process {
    
        # check to see if local token exists (ran Login-AzureRMAccount)
        if (($null -eq (Get-AzureRmContext).Account)) {
            Write-Warning "Please run < Login-AzureRMAccount > first to create a session token...exiting."
            break
        } 

        # Get subscription name
        Try {
            Select-AzureRmSubscription -SubscriptionName $subscriptionName -ErrorAction Stop -Verbose | Out-Null
        }
        Catch {
            $error[0].Exception
            break
        }

        # resolve workspace
        Try {
            $workspace = (Get-AzureRmOperationalInsightsWorkspace -ErrorAction Stop -Verbose).Where({$_.Name -eq "$workspaceName"})
            $workspaceID = $workspace.ResourceID
        }
        Catch {
        
        }
        
        Try {
            $nsg_data = Get-AzureRmNetworkSecurityGroup -ErrorAction Stop -Verbose
        }
        Catch {
            $error[0].exception
            break
        }

        $results = @()

        $nsg_data | ForEach-Object {
        
            Try {
                $op = Set-AzureRmDiagnosticSetting -ResourceId $_.Id -WorkspaceId $workspaceID -Enabled $true -RetentionInDays 1 -ErrorAction Stop -Verbose
                $results += $op
            }
            Catch {
                $error[0].exception
                break
            }
        }

        return $results

    
    } # end process block

} # end function