请求编写适配多场景的Windows 10/11配置文件夹部署PowerShell脚本
PowerShell Script for Config Folder Deployment & Explanation
Full Script
# Check if running as Administrator $currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) if (-not $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { # Restart the script with admin privileges Start-Process powershell.exe "-File `"$PSCommandPath`"" -Verb RunAs exit } # Define core paths (easily modifiable) $sourceRoot = "X:\Desktop Support\Software" $targetRoot = "C:\Program Files (x86)\Redacted" # List of 5 constable district folders to copy $pctFolders = @("Constable Pct 1", "Constable Pct 2", "Constable Pct 3", "Constable Pct 4", "Constable Pct 5") # Loop through each district folder to perform copy foreach ($folder in $pctFolders) { # Build full source and target paths safely $sourcePath = Join-Path -Path $sourceRoot -ChildPath $folder $targetPath = Join-Path -Path $targetRoot -ChildPath $folder # Skip if source folder doesn't exist if (-not (Test-Path -Path $sourcePath -PathType Container)) { Write-Warning "Source folder missing: $sourcePath" continue } # Create target directory if it doesn't exist if (-not (Test-Path -Path $targetPath -PathType Container)) { New-Item -Path $targetPath -ItemType Directory | Out-Null Write-Host "Created target folder: $targetPath" } # Copy folder contents using Robocopy (robust for network transfers) robocopy $sourcePath $targetPath /E /COPYALL /R:3 /W:5 /NP /NFL /NDL # Validate Robocopy exit status (0-7 = successful) if ($LASTEXITCODE -le 7) { Write-Host "Successfully copied $folder to $targetPath" -ForegroundColor Green } else { Write-Error "Copy failed for $folder. Robocopy exit code: $LASTEXITCODE" } } # Keep window open to review results Write-Host "`nConfig deployment finished. Press any key to exit..." $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Line-by-Line Logic Breakdown
- Admin Privilege Check
- Verifies the script is running as admin (required to write to
Program Files (x86)). If not, it restarts itself with elevated rights.
- Verifies the script is running as admin (required to write to
- Path Variables
$sourceRootand$targetRootstore base paths so you don’t have to edit multiple lines if paths change later.$pctFoldersis an array listing all 5 district folders—easy to add/remove entries as needed.
- Foreach Loop
- Repeats the copy process for every folder in
$pctFolders, eliminating manual repetition.
- Repeats the copy process for every folder in
- Path Construction
Join-Pathsafely combines paths (avoids errors from missing slashes like\or/).
- Source Validation
Test-Pathchecks if the network source folder exists. If not, it skips that folder and logs a warning.
- Target Directory Creation
- Creates the local target folder if it doesn’t exist, ensuring the copy has a destination.
- Robocopy Command
/E: Copies all subfolders (including empty ones)/COPYALL: Copies all file attributes (permissions, timestamps, etc.)/R:3: Retries 3 times if a file is locked/W:5: Waits 5 seconds between retries/NP /NFL /NDL: Hides progress and file/directory lists to keep output clean
- Exit Code Check
- Robocopy uses exit codes 0-7 for successful transfers (even if some files were skipped). Codes above 7 indicate failures.
- Final Prompt
- Keeps the PowerShell window open so you can review results before closing.
Key Concepts to Understand
- Admin Requirements: Windows restricts writes to system directories like
Program Files (x86)—elevated rights are non-negotiable here. - Robocopy vs. Copy-Item: Robocopy is built for robust file transfers (especially over networks) and handles errors better than PowerShell’s native
Copy-Item. - Path Safety: Always use
Join-Pathinstead of string concatenation (e.g.,$sourceRoot + "\" + $folder) to avoid path formatting errors. - Error Handling: Checking for existing paths and validating exit codes prevents silent failures and makes troubleshooting easier.
How to Run
- Save the script as
Deploy-Configs.ps1on your network share (e.g.,X:\Desktop Support\Scripts). - Right-click the file and select Run with PowerShell—it will automatically restart with admin rights if needed.
- For cross-location use, replace the drive letter
X:with the UNC path (e.g.,\\FileServer\DesktopSupport\Software) to avoid drive mapping issues on remote devices.
内容的提问来源于stack exchange,提问作者Kamia2003
相关产品推荐
相关产品推荐

