如何用PowerShell从文本文件读取文件夹名称创建指定目录结构
Got it, let's refactor your existing PowerShell code to pull folder names from text files instead of hardcoding them. This makes updating your folder lists way easier without having to edit the script itself. Here's how to do it step by step:
Step 1: Prepare Your Text Files
First, create two plain text files (one for each set of folders) with one folder name per line:
- For the top-level folders (
Admin,user,server), save them in a file likemain_folders.txt:Admin user server - For the audio subfolders (
ABC3D_X00-00,WXY3Z_X01-00), save them inaudio_folders.txt:ABC3D_X00-00 WXY3Z_X01-00
Note: If these text files aren't in the same directory as your script, use full paths (like C:\scripts\main_folders.txt) when referencing them.
Step 2: Updated PowerShell Code
Replace your hardcoded arrays with Get-Content to read the text files. We'll also add a filter to skip empty lines (in case your text file has extra spaces or blank entries):
# Read main folder names from text file and create directories Get-Content 'main_folders.txt' | Where-Object { $_ -match '\S' } | # Skip empty lines to avoid invalid folder names ForEach-Object { $fullPath = Join-Path 'D:\test3\LV2\7212\win10\x64\' $_ New-Item -Path $fullPath -ItemType Directory -Force } # Read audio subfolder names from text file and create directories Get-Content 'audio_folders.txt' | Where-Object { $_ -match '\S' } | ForEach-Object { $fullPath = Join-Path 'D:\test3\LV2\7212\win10\x64\audio' $_ New-Item -Path $fullPath -ItemType Directory -Force }
Key Notes
- Flexibility: Now you can update your folder list anytime by editing the text files—no need to modify the script code.
- Robustness: The
Where-Objectfilter prevents accidental creation of empty-named folders if your text file has blank lines. - Maintainability: Separating folder names from the script logic makes the code cleaner and easier to troubleshoot later.
If you want to add error handling (like catching invalid folder name errors), you could wrap the New-Item call in a try/catch block, but the above version works perfectly for most basic use cases.
内容的提问来源于stack exchange,提问作者Shuhaib K V

