请求编写PowerShell脚本:批量替换多服务器指定文件中的主机FQDN
Got it, let's turn that single-server script into a multi-machine powerhouse! Here's a robust, scalable solution that'll let you batch-update the FQDN in your target file across multiple remote servers, with built-in error handling to keep things smooth.
Multi-Server PowerShell Script for FQDN Replacement
Prerequisites
Before diving in, make sure you have these covered:
- Administrator (or file-modification) permissions on all target servers
- WinRM enabled and configured on remote servers (most domain environments have this by default; for workgroups, you may need to run
Enable-PSRemoting -Forceon each server first) - Either a list of custom FQDNs per server, or the ability to auto-fetch each server's actual FQDN
The Complete Script
This script supports both custom FQDN mappings and auto-generated ones, plus clear success/failure reporting:
# Define your target servers - load from a text file with Get-Content if preferred $targetServers = @("Server01", "Server02", "Server03", "Server04") # Full path to the file you need to modify on remote servers $targetFilePath = "C:\AppConfig\config.json" # Adjust this to your actual file path # Optional: Use this hashtable if you need custom FQDNs per server (skip if using auto-fetched FQDNs) $customFqdns = @{ "Server01" = "server01.prod.yourdomain.com" "Server02" = "server02.prod.yourdomain.com" # Add more server-FQDN pairs as needed } # Pattern to match the old FQDN in the file - use regex for dynamic matches (e.g., '\b[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b' for any FQDN) $oldFqdnPattern = "legacy-fqdn.yourdomain.com" # Replace with your actual old string/pattern # Execute the batch replacement Invoke-Command -ComputerName $targetServers -ScriptBlock { param( [string]$FilePath, [string]$OldPattern, [string]$NewFqdn ) try { # Validate file exists before proceeding if (-not (Test-Path -Path $FilePath -PathType Leaf)) { throw "Target file not found at $FilePath" } # Read file content as a single string (preserves line breaks) $fileContent = Get-Content -Path $FilePath -Raw -ErrorAction Stop # Replace the old FQDN pattern with the new one $updatedContent = $fileContent -replace $OldPattern, $NewFqdn # Write changes back to the file Set-Content -Path $FilePath -Value $updatedContent -ErrorAction Stop Write-Host "✅ Successfully updated FQDN on $env:COMPUTERNAME" } catch { Write-Error "❌ Failed to update $env:COMPUTERNAME : $_" } } -ArgumentList $targetFilePath, $oldFqdnPattern, $( # Use custom FQDN if defined, else auto-fetch the server's actual FQDN if ($customFqdns.ContainsKey($using:PSItem)) { $customFqdns[$using:PSItem] } else { [System.Net.Dns]::GetHostEntry($using:PSItem).HostName } )
Key Features Breakdown
- Flexible Server Input: Swap the hardcoded
$targetServerswithGet-Content -Path "C:\Servers\prod_servers.txt"to load servers from a text file, or useImport-Csvfor CSV lists - Dual FQDN Mode: Use the
$customFqdnshashtable for manual mappings, or omit it to auto-pull each server's real FQDN via DNS - Safety & Visibility: Checks for file existence before making changes, and outputs clear success/error messages per server
- Efficient Remote Execution: Uses
Invoke-Commandto run the logic directly on each remote server, avoiding unnecessary file transfers
Critical Tips for Testing & Safety
- Test First: Add
-WhatIfto theSet-Contentline (e.g.,Set-Content -Path $FilePath -Value $updatedContent -WhatIf) to simulate changes without writing to the file - Elevated Session: Run the script in an elevated PowerShell window (Right-click > Run as Administrator) to avoid permission issues
- Regex Tweaks: If your old FQDN varies per server, use the regex pattern
'\b[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b'to match any valid FQDN in the file
内容的提问来源于stack exchange,提问作者Karthik Kumar
相关产品推荐
相关产品推荐

