You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求编写适配多场景的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

  1. 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.
  2. Path Variables
    • $sourceRoot and $targetRoot store base paths so you don’t have to edit multiple lines if paths change later.
    • $pctFolders is an array listing all 5 district folders—easy to add/remove entries as needed.
  3. Foreach Loop
    • Repeats the copy process for every folder in $pctFolders, eliminating manual repetition.
  4. Path Construction
    • Join-Path safely combines paths (avoids errors from missing slashes like \ or /).
  5. Source Validation
    • Test-Path checks if the network source folder exists. If not, it skips that folder and logs a warning.
  6. Target Directory Creation
    • Creates the local target folder if it doesn’t exist, ensuring the copy has a destination.
  7. 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
  8. Exit Code Check
    • Robocopy uses exit codes 0-7 for successful transfers (even if some files were skipped). Codes above 7 indicate failures.
  9. 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-Path instead 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

  1. Save the script as Deploy-Configs.ps1 on your network share (e.g., X:\Desktop Support\Scripts).
  2. Right-click the file and select Run with PowerShell—it will automatically restart with admin rights if needed.
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 21:20:44