编写无需管理员权限的PowerShell脚本批量处理TXT文件
PowerShell Script to Prepend Line Breaks to Specific Strings in .txt Files
Got it, here's a PowerShell script that checks all your boxes—no admin rights required, preserves your original files, and handles the string prepending exactly as you described. It'll walk you through selecting your target directory, inputting the string you want to modify, and saves all changes to a new folder in the parent directory of your selected folder.
The Script
# Prompt user to select the target directory $targetDir = Read-Host "Please enter the full path of the directory containing .txt files (or drag-and-drop the folder here)" $targetDir = $targetDir.Trim('"') # Remove quotes if pasted via drag-and-drop # Validate the directory exists if (-not (Test-Path -Path $targetDir -PathType Container)) { Write-Host "Error: The specified directory does not exist. Exiting." -ForegroundColor Red exit 1 } # Prompt user for the string to prepend a line break before $targetString = Read-Host "Please enter the string to prepend a line break before" # Define output directory (parent of target directory) $outputDir = Join-Path -Path (Split-Path -Path $targetDir -Parent) -ChildPath "Modified_Txt_Files" # Create output directory if it doesn't exist if (-not (Test-Path -Path $outputDir -PathType Container)) { New-Item -Path $outputDir -ItemType Directory | Out-Null Write-Host "Created output directory: $outputDir" -ForegroundColor Green } # Get all .txt files in the target directory $txtFiles = Get-ChildItem -Path $targetDir -Filter "*.txt" -File if ($txtFiles.Count -eq 0) { Write-Host "No .txt files found in $targetDir. Exiting." -ForegroundColor Yellow exit 0 } # Process each .txt file foreach ($file in $txtFiles) { try { # Read the file content as a single raw string to handle multi-line content $content = Get-Content -Path $file.FullName -Raw -Encoding UTF8 # Replace the target string with a line break + the string, avoiding duplicate breaks $modifiedContent = $content -replace "(?<!`n)$([regex]::Escape($targetString))", "`n$targetString" # Define output file path $outputFile = Join-Path -Path $outputDir -ChildPath $file.Name # Write modified content to output file Set-Content -Path $outputFile -Value $modifiedContent -Encoding UTF8 Write-Host "Successfully processed: $($file.Name)" -ForegroundColor Green } catch { Write-Host "Failed to process $($file.Name): $_" -ForegroundColor Red } } Write-Host "`nProcessing complete! All modified files are in: $outputDir" -ForegroundColor Cyan
How It Works
Let's break down the key parts to help you understand what's happening:
- Directory Validation: It first checks if the directory you entered exists, so you don't waste time with typos. Drag-and-drop works too—it automatically removes quotes that get added when you drag a folder into the console.
- Safe String Handling: The script uses
[regex]::Escape()to handle special characters (like.,*, or?) in your target string, so you don't have to worry about regex breaking the replacement. - Avoid Duplicate Line Breaks: The regex
(?<!n)` ensures it only adds a line break if there isn't already one before your target string—no messy extra blank lines. - Original Files Stay Intact: All modified files are saved to a new
Modified_Txt_Filesfolder in the parent directory of your target folder, so your original .txt files never get touched. - Error Resilience: If a file can't be processed (locked, permission issues, etc.), it shows an error message but keeps running through the rest of the files.
Important Notes
- No Admin Rights Required: This script only reads from your selected directory and writes to a subfolder in its parent directory—no system-level changes, so you don't need admin privileges to run it.
- Encoding: It uses UTF8 encoding to preserve special characters. If your .txt files use a different encoding (like ASCII), just update the
-Encoding UTF8parameters to match your file's encoding. - Case Sensitivity: By default, the replacement is case-insensitive (PowerShell's default for
-replace). If you need case-sensitive matching, change-replaceto-creplace.
内容的提问来源于stack exchange,提问作者user9492893
相关产品推荐
相关产品推荐

