public/Enable-AzureNSGDiagnostics.ps1

function Enable-AzureNSGDiagnostics {

<#
 
.SYNOPSIS
 
Enabling azure diagnostics logging for all network security groups
 
.DESCRIPTION
 
Enable-AzureNSGDiagnostics cmdlet enables azure diagnostics logging for all network security groups in a given Azure subscription, and sends the data to an oms workspace with a retention policy or archiving to storage.
  
.PARAMETER SubscriptionName
 
specify the subscriptionName
 
.PARAMETER WorkspaceName
 
Specify the OMS workspace by the full name.
 
.EXAMPLE
 
Enable-AzureNSGDiagnostics -SubscriptionName <SubscriptionName> -WorkspaceName <WorkspaceName> -verbose
 
#>


    [cmdletbinding()]    
    
    Param (


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

        [Parameter(Mandatory=$true)]
        [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
        }
        
        
        Try {
            Select-AzureRmSubscription -SubscriptionName $subscriptionname -ErrorAction Stop -Verbose | Out-Null
        }
        Catch {
            $error[0].Exception
            break
        }

        
        # resolve oms workspace
        $workspace = (Get-AzureRmOperationalInsightsWorkspace).Where({$_.Name -eq "$workspaceName"})
        $workspaceID = $workspace.ResourceId
        
        # if null or collection greather than 1, break
        if (($null -eq $workspaceID)) {
            Write-Warning "Could not resolve oms workspace, exiting."
            break
        }
        
        
        # Get NSGs for all resource groups (or exit if none)
        Try {
            $nsgs = Get-AzureRmNetworkSecurityGroup -ErrorAction Stop -Verbose
        }
        Catch {
            $error[0].Exception
            break
        }

        
        if (($null -eq $nsgs) -or ($nsgs.count -eq 0)) {
            Write-Warning "No NSGs found, exiting."
            break
        }
        
        
        # itterate through nsgs and enable diagnostics (straight to oms, no storage account or retention specified)
        else {
            $results = @()
            foreach ($nsg in $nsgs) {
                Try {
                    $op = Set-AzureRmDiagnosticSetting -ResourceId $nsg.ID -WorkspaceId $workspaceID -Enabled $true -ErrorAction Stop -Verbose
                    $results += $op
                }
                Catch {
                    $error[0].Exception
                    continue
                }
    
            }
        }

        return $results

    }

}