From 96f2085a20c96894a51cf590b8bae5ea78d49fe3 Mon Sep 17 00:00:00 2001 From: Danny de Kooker Date: Mon, 3 Nov 2025 07:33:37 +0000 Subject: [PATCH] Change default server to localhost --- Services/Install-configure-SNMP-Service.ps1 | 77 +++++++++++++++------ 1 file changed, 54 insertions(+), 23 deletions(-) diff --git a/Services/Install-configure-SNMP-Service.ps1 b/Services/Install-configure-SNMP-Service.ps1 index d84d0c3..1029b2a 100644 --- a/Services/Install-configure-SNMP-Service.ps1 +++ b/Services/Install-configure-SNMP-Service.ps1 @@ -1,15 +1,15 @@ <# .SYNOPSIS -Installs, configures, and secures the SNMP Service and components on a remote Windows Server. -It includes optional parameters for setting Agent Contact and Location details. +Installs, configures, and secures the SNMP Service and components on a remote or local Windows Server. .DESCRIPTION -This script is idempotent. It installs the SNMP features, uses the RFC1156Agent key to set sysServices, sysContact, and sysLocation, -configures the Community String (Read Only), checks if the Allowed IP is already present before adding it to the Permitted Managers, -creates missing registry keys only if needed, and opens UDP 161 in the Windows Firewall. +This script is idempotent. It installs the SNMP features, sets Agent details, configures the Community String, +checks if the Allowed IP is already present before adding it, creates missing registry keys only if needed, +opens UDP 161 in the Windows Firewall, and correctly executes commands locally if the target is the local machine +(bypassing Invoke-Command for local execution). .PARAMETER ComputerName -The name of the remote computer (Windows Server) where SNMP will be installed. +The name of the remote computer (Windows Server) where SNMP will be installed. Defaults to the local machine if not specified. .PARAMETER CommunityString The custom community string to be configured for the SNMP Service. @@ -25,14 +25,16 @@ Optional. The contact person or email address for the SNMP agent (written to sys Optional. The physical location of the SNMP agent (written to sysLocation). .EXAMPLE -.\Install-Configure-SNMP.ps1 -ComputerName "Server01" -CommunityString "MySecureString" -AllowedIPOrHost "192.168.1.10" -AgentContact "IT Operations" -AgentLocation "Server Room A" +# Run on the local machine (commands execute directly, no Invoke-Command) +.\Install-Configure-SNMP.ps1 -CommunityString "MySecureString" -AllowedIPOrHost "192.168.1.10" .EXAMPLE -.\Install-Configure-SNMP.ps1 -ComputerName "TestServer" -CommunityString "PublicAccess" -AllowedIPOrHost "0.0.0.0" +# Run on a remote machine (commands execute via Invoke-Command) +.\Install-Configure-SNMP.ps1 -ComputerName "Server01" -CommunityString "MySecureString" -AllowedIPOrHost "192.168.1.10" -AgentContact "IT Operations" #> param( - [Parameter(Mandatory=$true)] - [string]$ComputerName, + [Parameter(Mandatory=$false)] + [string]$ComputerName = $env:COMPUTERNAME, [Parameter(Mandatory=$true)] [string]$CommunityString, @@ -53,19 +55,45 @@ $FirewallRuleName = "Allow-SNMP-Inbound-UDP161" $SNMPPort = 161 $AgentServicesName = "sysServices" $AgentServicesValue = 79 +$IsLocal = ($ComputerName -ceq $env:COMPUTERNAME) # Check if target is the local machine (case-exact) Write-Host "--- Starting SNMP Service installation, configuration, and firewall setup on $($ComputerName) ---" +if ($IsLocal) { + Write-Host "NOTE: Running in LOCAL execution mode (bypassing Invoke-Command). 🖥️" +} else { + Write-Host "NOTE: Running in REMOTE execution mode (using Invoke-Command). 🌐" +} +Write-Host "--------------------------------------------------------------------------------" + +# --- Function to handle execution (Local or Remote) --- +function Execute-ScriptBlock { + param( + [ScriptBlock]$ScriptBlock, + [Array]$ArgumentList + ) + + if ($IsLocal) { + # Run locally by invoking the script block directly + & $ScriptBlock @ArgumentList + } else { + # Run remotely via Invoke-Command + Invoke-Command -ComputerName $ComputerName -ScriptBlock $ScriptBlock -ArgumentList $ArgumentList -ErrorAction Stop + } +} +# ----------------------------------------------------- try { - # 1. Install SNMP Service and WMI Provider (including RSAT-SNMP) remotely + # 1. Install SNMP Service and WMI Provider (including RSAT-SNMP) Write-Host "1. Installing $($SNMPFeatures -join ', ') on $($ComputerName)..." - Invoke-Command -ComputerName $ComputerName -ScriptBlock { + $InstallFeaturesBlock = { param($Features) - # Install the features if not already present + $InstalledFeatures = Get-WindowsFeature $Features | Where-Object { $_.Installed -eq $true } + if ($InstalledFeatures.Count -ne $Features.Count) { Write-Host "Installing features..." + # Using -IncludeAllSubFeature to ensure all dependencies are met $InstallationResult = Install-WindowsFeature -Name $Features -IncludeAllSubFeature -ErrorAction Stop if (-not $InstallationResult.Success) { throw "Feature installation failed. Details: $($InstallationResult | Out-String)" @@ -73,12 +101,13 @@ try { } else { Write-Host "SNMP features are already installed." } - } -ArgumentList $SNMPFeatures -ErrorAction Stop + } + Execute-ScriptBlock -ScriptBlock $InstallFeaturesBlock -ArgumentList @($SNMPFeatures) - # 2. Configure SNMP Service remotely (Contact, Location, Community String, Allowed IPs, and Agent Services) + # 2. Configure SNMP Service (Contact, Location, Community String, Allowed IPs, and Agent Services) Write-Host "2. Configuring SNMP Service parameters on $($ComputerName)..." - Invoke-Command -ComputerName $ComputerName -ScriptBlock { + $ConfigureSNMPBlock = { param($Community, $IPOrHost, $ServicesName, $ServicesValue, $Contact, $Location) # Define Registry paths @@ -93,6 +122,7 @@ try { # Check and create the parent 'Parameters' key if it's missing (needed for subsequent checks) if (-not (Test-Path $SNMPRegBase)) { Write-Host " -> Creating base Parameters key: $SNMPRegBase" + # Using -Force here is necessary to ensure it's created if 'SNMP' exists but 'Parameters' doesn't. New-Item -Path $SNMPRegBase -Type Directory -Force -ErrorAction Stop | Out-Null } @@ -113,7 +143,6 @@ try { # --- Configure Agent Contact (sysContact) --- if (-not [string]::IsNullOrEmpty($Contact)) { Write-Host " -> Setting Agent Contact (sysContact) to '$Contact'." - # Use Type STRING (RegSZ) for text fields Set-ItemProperty -Path $RFC1156AgentRegKey -Name "sysContact" -Value $Contact -Type String -Force -ErrorAction Stop } else { Write-Host " -> Agent Contact parameter was empty, skipping sysContact configuration." @@ -122,7 +151,6 @@ try { # --- Configure Agent Location (sysLocation) --- if (-not [string]::IsNullOrEmpty($Location)) { Write-Host " -> Setting Agent Location (sysLocation) to '$Location'." - # Use Type STRING (RegSZ) for text fields Set-ItemProperty -Path $RFC1156AgentRegKey -Name "sysLocation" -Value $Location -Type String -Force -ErrorAction Stop } else { Write-Host " -> Agent Location parameter was empty, skipping sysLocation configuration." @@ -154,12 +182,13 @@ try { Set-ItemProperty -Path $PermittedManagersRegKey -Name $Index -Value $IPOrHost -Type STRING -Force -ErrorAction Stop } - } -ArgumentList $CommunityString, $AllowedIPOrHost, $AgentServicesName, $AgentServicesValue, $AgentContact, $AgentLocation -ErrorAction Stop + } + Execute-ScriptBlock -ScriptBlock $ConfigureSNMPBlock -ArgumentList @($CommunityString, $AllowedIPOrHost, $AgentServicesName, $AgentServicesValue, $AgentContact, $AgentLocation) # 3. Configure Windows Firewall Rule (Idempotent: removes and re-creates) Write-Host "3. Configuring Windows Firewall to allow UDP port $($SNMPPort) from $($AllowedIPOrHost) on $($ComputerName)..." - Invoke-Command -ComputerName $ComputerName -ScriptBlock { + $ConfigureFirewallBlock = { param($RuleName, $Port, $IPOrHost) # Remove existing rule if it exists (for clean updates) @@ -179,14 +208,16 @@ try { -Profile Any ` -ErrorAction Stop - } -ArgumentList $FirewallRuleName, $SNMPPort, $AllowedIPOrHost -ErrorAction Stop + } + Execute-ScriptBlock -ScriptBlock $ConfigureFirewallBlock -ArgumentList @($FirewallRuleName, $SNMPPort, $AllowedIPOrHost) # 4. Restart SNMP Service Write-Host "4. Restarting SNMP Service on $($ComputerName) to apply all changes (Configuration & Firewall)." - Invoke-Command -ComputerName $ComputerName -ScriptBlock { + $RestartServiceBlock = { Restart-Service -Name "SNMP" -ErrorAction Stop - } -ErrorAction Stop + } + Execute-ScriptBlock -ScriptBlock $RestartServiceBlock Write-Host "--- SNMP installation, configuration, and firewall setup on $($ComputerName) is complete! ✅ ---"