PowerShell遍历指定父文件夹子目录,检测文件并删除需求求助
PowerShell Solution for Checking and Deleting Folders with
can_erase.txt Got it, let's get your script working properly. Your goal is to check through stream1 to stream4, look for subfolders containing can_erase.txt, save the parameters from that file, then delete those subfolders. Here's a polished, reliable solution that fixes your foreach confusion and avoids common pitfalls like directory switching issues:
# Loop through each stream folder (stream1 to stream4) foreach ($streamNum in 1..4) { # Build the full path to the current stream folder without using cd $streamPath = Join-Path -Path $PWD.Path -ChildPath "stream$streamNum" # Get all subfolders under the current stream folder (recursively) Get-ChildItem -Path $streamPath -Directory -Recurse | ForEach-Object { # Define the full path to can_erase.txt in the current subfolder $canEraseFile = Join-Path -Path $_.FullName -ChildPath "can_erase.txt" # Check if the file exists (confirm it's a file, not a folder) if (Test-Path -Path $canEraseFile -PathType Leaf) { # Read the file content to save the parameters $fileParameters = Get-Content -Path $canEraseFile -Raw # Optional: Save these parameters to a log file for record-keeping # Add-Content -Path "erase_records.log" -Value "Folder: $($_.FullName) | Parameters: $fileParameters" # Delete the subfolder and all its contents # Add -WhatIf to test before actual deletion (no changes made) Remove-Item -Path $_.FullName -Recurse -Force Write-Host "Successfully deleted folder: $($_.FullName)" } } }
Breakdown of Key Parts:
- No more
cd: UsingJoin-Pathto construct full paths keeps your script running safely from your current working directory, no need to switch back and forth. Get-ChildItem -Directory -Recurse: This specifically targets subfolders (ignores files) and digs into all nested subdirectories under each stream folder.Test-Path -PathType Leaf: Ensures we're verifying a file exists, not a folder with the same name.- Reading the file:
Get-Content -Rawpulls the entire file content as a single string. Omit-Rawif you want each line as a separate item in an array. - Safe deletion: Add
-WhatIfto theRemove-Itemline first (likeRemove-Item ... -WhatIf) to preview which folders will be deleted without making any changes.
Quick Testing Tip:
Run the script with -WhatIf on the delete command first to confirm it's targeting the right folders. Once you're confident, remove -WhatIf to execute the actual deletion.
内容的提问来源于stack exchange,提问作者madsantos
相关产品推荐
相关产品推荐

