powershell nobind rewrite

<pre class="wp-block-syntaxhighlighter-code"># ============================================================================
# ============================================================================
# Script d'analyse des Rewrite Actions et Policies NetScaler
# ============================================================================
# 
# But : Identifier les rewrite actions et policies non utilisees
# - Une rewrite action est inutilisee si elle n'est referencee par aucune policy
# - Une rewrite policy est inutilisee si elle n'est bindee nulle part (global, lb vserver, vpn vserver)
#
# ============================================================================

# ========== CONFIGURATION ==========
# Modifiez cette ligne avec votre chemin vers ns.conf
$NS_CONF_PATH = "C:\logs\ns.conf"
# ====================================

# ============================================================================
# FONCTIONS PRINCIPALES
# ============================================================================

function Load-NSConf {
    param([string]$FilePath)
    
    if (Test-Path $FilePath) {
        Write-Host "`n[INFO] Chargement du fichier : $FilePath" -ForegroundColor Cyan
        return Get-Content -Path $FilePath -Encoding UTF8
    } else {
        Write-Host "`n[ERREUR] Le fichier $FilePath est introuvable !" -ForegroundColor Red
        exit 1
    }
}

function Get-RewriteActions {
    param([string[]]$Lines)
    
    $actions = @{}
    
    foreach ($line in $Lines) {
        # Recherche les lignes : add rewrite action <nom> ...
        if ($line -match '^add rewrite action\s+(\S+)') {
            $actionName = $Matches[1]
            $actions[$actionName] = $line
        }
    }
    
    return $actions
}

function Get-RewritePolicies {
    param([string[]]$Lines)
    
    $policies = @{}
    
    foreach ($line in $Lines) {
        # Recherche les lignes : add rewrite policy <nom> <expression> <action>
        if ($line -match '^add rewrite policy\s+(\S+)\s+(.+?)\s+(\S+)') {
            $policyName = $Matches[1]
            $expression = $Matches[2]
            $actionName = $Matches[3]
            
            $policies[$policyName] = @{
                'Line' = $line
                'Expression' = $expression
                'Action' = $actionName
            }
        }
    }
    
    return $policies
}

function Get-RewritePolicyBindings {
    param([string[]]$Lines)
    
    $bindings = @{
        'Global' = @()
        'LB_VServer' = @{}
        'VPN_VServer' = @{}
    }
    
    foreach ($line in $Lines) {
        # Bind rewrite global
        if ($line -match '^bind rewrite global\s+(\S+)') {
            $policyName = $Matches[1]
            $bindings['Global'] += @{
                'Policy' = $policyName
                'Line' = $line
            }
        }
        
        # Bind lb vserver ... -policy ... -priority ...
        if ($line -match '^bind lb vserver\s+(\S+).*-policy\s+(\S+).*-priority\s+(\d+)') {
            $vserverName = $Matches[1]
            $policyName = $Matches[2]
            $priority = $Matches[3]
            
            if (-not $bindings['LB_VServer'].ContainsKey($vserverName)) {
                $bindings['LB_VServer'][$vserverName] = @()
            }
            
            $bindings['LB_VServer'][$vserverName] += @{
                'Policy' = $policyName
                'Priority' = $priority
                'Line' = $line
            }
        }
        
        # Bind vpn vserver ... -policy ... -priority ...
        if ($line -match '^bind vpn vserver\s+(\S+).*-policy\s+(\S+).*-priority\s+(\d+)') {
            $vserverName = $Matches[1]
            $policyName = $Matches[2]
            $priority = $Matches[3]
            
            if (-not $bindings['VPN_VServer'].ContainsKey($vserverName)) {
                $bindings['VPN_VServer'][$vserverName] = @()
            }
            
            $bindings['VPN_VServer'][$vserverName] += @{
                'Policy' = $policyName
                'Priority' = $priority
                'Line' = $line
            }
        }
    }
    
    return $bindings
}

function Get-UsedActions {
    param($Policies)
    
    $usedActions = @{}
    
    foreach ($policyName in $Policies.Keys) {
        $actionName = $Policies[$policyName]['Action']
        if (-not $usedActions.ContainsKey($actionName)) {
            $usedActions[$actionName] = @()
        }
        $usedActions[$actionName] += $policyName
    }
    
    return $usedActions
}

function Get-BoundPolicies {
    param($Bindings)
    
    $boundPolicies = @{}
    
    # Global bindings
    foreach ($binding in $Bindings['Global']) {
        $policyName = $binding['Policy']
        if (-not $boundPolicies.ContainsKey($policyName)) {
            $boundPolicies[$policyName] = @()
        }
        $boundPolicies[$policyName] += "Global"
    }
    
    # LB VServer bindings
    foreach ($vserverName in $Bindings['LB_VServer'].Keys) {
        foreach ($binding in $Bindings['LB_VServer'][$vserverName]) {
            $policyName = $binding['Policy']
            if (-not $boundPolicies.ContainsKey($policyName)) {
                $boundPolicies[$policyName] = @()
            }
            $boundPolicies[$policyName] += "LB VServer: $vserverName (Priority: $($binding['Priority']))"
        }
    }
    
    # VPN VServer bindings
    foreach ($vserverName in $Bindings['VPN_VServer'].Keys) {
        foreach ($binding in $Bindings['VPN_VServer'][$vserverName]) {
            $policyName = $binding['Policy']
            if (-not $boundPolicies.ContainsKey($policyName)) {
                $boundPolicies[$policyName] = @()
            }
            $boundPolicies[$policyName] += "VPN VServer: $vserverName (Priority: $($binding['Priority']))"
        }
    }
    
    return $boundPolicies
}

# ============================================================================
# AFFICHAGE DES RESULTATS
# ============================================================================

function Show-UnusedActions {
    param($Actions, $UsedActions)
    
    Write-Host "`n==================================================================" -ForegroundColor Red
    Write-Host " REWRITE ACTIONS NON UTILISEES" -ForegroundColor Red -BackgroundColor Black
    Write-Host "==================================================================" -ForegroundColor Red
    
    $unusedActions = @()
    
    foreach ($actionName in $Actions.Keys) {
        if (-not $UsedActions.ContainsKey($actionName)) {
            $unusedActions += $actionName
        }
    }
    
    if ($unusedActions.Count -eq 0) {
        Write-Host "`nAucune rewrite action inutilisee trouvee !" -ForegroundColor Green
    } else {
        Write-Host "`nNombre d'actions non utilisees : $($unusedActions.Count)" -ForegroundColor Red
        Write-Host "Ces actions ne sont referencees par AUCUNE policy :`n" -ForegroundColor Yellow
        
        foreach ($actionName in ($unusedActions | Sort-Object)) {
            Write-Host "  ├─ " -NoNewline -ForegroundColor Red
            Write-Host "$actionName" -ForegroundColor Red
            Write-Host "  │  " -NoNewline -ForegroundColor DarkGray
            Write-Host "$($Actions[$actionName])" -ForegroundColor White
            Write-Host "  │" -ForegroundColor DarkGray
            Write-Host "  │  Commande de suppression :" -ForegroundColor DarkGray
            Write-Host "  │  " -NoNewline -ForegroundColor DarkGray
            Write-Host "rm rewrite action $actionName" -ForegroundColor White
            Write-Host "  │" -ForegroundColor DarkGray
        }
        Write-Host "  └─────────────────────────────────────────────────────────────" -ForegroundColor Red
    }
}

function Show-UnusedPolicies {
    param($Policies, $BoundPolicies)
    
    Write-Host "`n==================================================================" -ForegroundColor Red
    Write-Host " REWRITE POLICIES NON BINDEES" -ForegroundColor Red -BackgroundColor Black
    Write-Host "==================================================================" -ForegroundColor Red
    
    $unusedPolicies = @()
    
    foreach ($policyName in $Policies.Keys) {
        if (-not $BoundPolicies.ContainsKey($policyName)) {
            $unusedPolicies += $policyName
        }
    }
    
    if ($unusedPolicies.Count -eq 0) {
        Write-Host "`nAucune rewrite policy non bindee trouvee !" -ForegroundColor Green
    } else {
        Write-Host "`nNombre de policies non bindees : $($unusedPolicies.Count)" -ForegroundColor Red
        Write-Host "Ces policies ne sont bindees NULLE PART (ni global, ni lb/vpn vserver) :`n" -ForegroundColor Yellow
        
        foreach ($policyName in ($unusedPolicies | Sort-Object)) {
            $policy = $Policies[$policyName]
            Write-Host "  ├─ " -NoNewline -ForegroundColor Red
            Write-Host "$policyName" -ForegroundColor Red
            Write-Host "  │  " -NoNewline -ForegroundColor DarkGray
            Write-Host "Action utilisee : " -NoNewline -ForegroundColor DarkGray
            Write-Host "$($policy['Action'])" -ForegroundColor Cyan
            Write-Host "  │  " -NoNewline -ForegroundColor DarkGray
            Write-Host "$($policy['Line'])" -ForegroundColor White
            Write-Host "  │" -ForegroundColor DarkGray
            Write-Host "  │  Commande de suppression :" -ForegroundColor DarkGray
            Write-Host "  │  " -NoNewline -ForegroundColor DarkGray
            Write-Host "rm rewrite policy $policyName" -ForegroundColor White
            Write-Host "  │" -ForegroundColor DarkGray
        }
        Write-Host "  └─────────────────────────────────────────────────────────────" -ForegroundColor Red
    }
}

function Show-UsedActions {
    param($Actions, $UsedActions)
    
    Write-Host "`n==================================================================" -ForegroundColor Green
    Write-Host " REWRITE ACTIONS UTILISEES" -ForegroundColor Green -BackgroundColor Black
    Write-Host "==================================================================" -ForegroundColor Green
    
    $usedActionsList = @()
    
    foreach ($actionName in $Actions.Keys) {
        if ($UsedActions.ContainsKey($actionName)) {
            $usedActionsList += $actionName
        }
    }
    
    if ($usedActionsList.Count -eq 0) {
        Write-Host "`nAucune rewrite action utilisee trouvee !" -ForegroundColor Yellow
    } else {
        Write-Host "`nNombre d'actions utilisees : $($usedActionsList.Count)" -ForegroundColor Green
        Write-Host "Ces actions sont referencees par au moins une policy :`n" -ForegroundColor Green
        
        foreach ($actionName in ($usedActionsList | Sort-Object)) {
            Write-Host "  ├─ " -NoNewline -ForegroundColor Green
            Write-Host "$actionName" -ForegroundColor Green
            Write-Host "  │  " -NoNewline -ForegroundColor DarkGray
            Write-Host "Utilisee par les policies :" -ForegroundColor DarkGray
            
            foreach ($policyName in $UsedActions[$actionName]) {
                Write-Host "  │    • " -NoNewline -ForegroundColor DarkGray
                Write-Host "$policyName" -ForegroundColor Cyan
            }
            Write-Host "  │" -ForegroundColor DarkGray
        }
        Write-Host "  └─────────────────────────────────────────────────────────────" -ForegroundColor Green
    }
}

function Show-UsedPolicies {
    param($Policies, $BoundPolicies)
    
    Write-Host "`n==================================================================" -ForegroundColor Green
    Write-Host " REWRITE POLICIES BINDEES" -ForegroundColor Green -BackgroundColor Black
    Write-Host "==================================================================" -ForegroundColor Green
    
    $usedPoliciesList = @()
    
    foreach ($policyName in $Policies.Keys) {
        if ($BoundPolicies.ContainsKey($policyName)) {
            $usedPoliciesList += $policyName
        }
    }
    
    if ($usedPoliciesList.Count -eq 0) {
        Write-Host "`nAucune rewrite policy bindee trouvee !" -ForegroundColor Yellow
    } else {
        Write-Host "`nNombre de policies bindees : $($usedPoliciesList.Count)" -ForegroundColor Green
        Write-Host "Ces policies sont bindees quelque part (global, lb vserver ou vpn vserver) :`n" -ForegroundColor Green
        
        foreach ($policyName in ($usedPoliciesList | Sort-Object)) {
            $policy = $Policies[$policyName]
            Write-Host "  ├─ " -NoNewline -ForegroundColor Green
            Write-Host "$policyName" -ForegroundColor Green
            Write-Host "  │  " -NoNewline -ForegroundColor DarkGray
            Write-Host "Action utilisee : " -NoNewline -ForegroundColor DarkGray
            Write-Host "$($policy['Action'])" -ForegroundColor Cyan
            Write-Host "  │  " -NoNewline -ForegroundColor DarkGray
            Write-Host "Bindee sur :" -ForegroundColor DarkGray
            
            foreach ($binding in $BoundPolicies[$policyName]) {
                Write-Host "  │    • " -NoNewline -ForegroundColor DarkGray
                Write-Host "$binding" -ForegroundColor Cyan
            }
            Write-Host "  │" -ForegroundColor DarkGray
        }
        Write-Host "  └─────────────────────────────────────────────────────────────" -ForegroundColor Green
    }
}

# ============================================================================
# EXECUTION PRINCIPALE
# ============================================================================

Clear-Host

Write-Host "`n" -NoNewline
Write-Host "╔" -NoNewline -ForegroundColor Cyan
Write-Host "═══════════════════════════════════════════════════════════════════════════════╗" -ForegroundColor Cyan
Write-Host "║" -NoNewline -ForegroundColor Cyan
Write-Host "                                                                               " -NoNewline
Write-Host "║" -ForegroundColor Cyan
Write-Host "║" -NoNewline -ForegroundColor Cyan
Write-Host "           ANALYSE DES REWRITE ACTIONS ET POLICIES NETSCALER                   " -NoNewline -ForegroundColor Yellow
Write-Host "║" -ForegroundColor Cyan
Write-Host "║" -NoNewline -ForegroundColor Cyan
Write-Host "                                                                               " -NoNewline
Write-Host "║" -ForegroundColor Cyan
Write-Host "╚" -NoNewline -ForegroundColor Cyan
Write-Host "═══════════════════════════════════════════════════════════════════════════════╝" -ForegroundColor Cyan

# Charger la configuration
$lines = Load-NSConf -FilePath $NS_CONF_PATH

# Extraire les objets
Write-Host "`n[ETAPE 1] Extraction des rewrite actions..." -ForegroundColor Cyan
$actions = Get-RewriteActions -Lines $lines

Write-Host "`n[ETAPE 2] Extraction des rewrite policies..." -ForegroundColor Cyan
$policies = Get-RewritePolicies -Lines $lines

Write-Host "`n[ETAPE 3] Extraction des bindings de policies..." -ForegroundColor Cyan
$bindings = Get-RewritePolicyBindings -Lines $lines

# Analyser l'utilisation
Write-Host "`n[ETAPE 4] Analyse de l'utilisation des actions..." -ForegroundColor Cyan
$usedActions = Get-UsedActions -Policies $policies

Write-Host "`n[ETAPE 5] Analyse de l'utilisation des policies..." -ForegroundColor Cyan
$boundPolicies = Get-BoundPolicies -Bindings $bindings

# Afficher les résultats
Write-Host "`n[ETAPE 6] Generation du rapport..." -ForegroundColor Cyan

# Calculer les statistiques
$unusedActionsCount = ($actions.Keys | Where-Object { -not $usedActions.ContainsKey($_) }).Count
$usedActionsCount = ($actions.Keys | Where-Object { $usedActions.ContainsKey($_) }).Count
$unusedPoliciesCount = ($policies.Keys | Where-Object { -not $boundPolicies.ContainsKey($_) }).Count
$usedPoliciesCount = ($policies.Keys | Where-Object { $boundPolicies.ContainsKey($_) }).Count

# Afficher le RESUME en premier
Write-Host "`n==================================================================" -ForegroundColor Cyan
Write-Host " RESUME DE L'ANALYSE" -ForegroundColor Yellow -BackgroundColor Black
Write-Host "==================================================================" -ForegroundColor Cyan

Write-Host "`nREWRITE ACTIONS :" -ForegroundColor White
Write-Host "  • Total : $($actions.Count)" -ForegroundColor Cyan
Write-Host "  • Utilisees : $usedActionsCount" -ForegroundColor Green
Write-Host "  • Non utilisees : $unusedActionsCount" -ForegroundColor Red

Write-Host "`nREWRITE POLICIES :" -ForegroundColor White
Write-Host "  • Total : $($policies.Count)" -ForegroundColor Cyan
Write-Host "  • Bindees : $usedPoliciesCount" -ForegroundColor Green
Write-Host "  • Non bindees : $unusedPoliciesCount" -ForegroundColor Red

Write-Host "`n==================================================================" -ForegroundColor Cyan

# Afficher d'abord les objets NON UTILISÉS en ROUGE
Show-UnusedActions -Actions $actions -UsedActions $usedActions
Show-UnusedPolicies -Policies $policies -BoundPolicies $boundPolicies

# Afficher ensuite les objets UTILISÉS en VERT
Show-UsedActions -Actions $actions -UsedActions $usedActions
Show-UsedPolicies -Policies $policies -BoundPolicies $boundPolicies

Write-Host "`nAnalyse terminee avec succes !" -ForegroundColor Green
Write-Host ""
</pre>