Powershell - 使用CSV文件创建文件夹

lot*_*227 1 powershell-2.0

我刚刚创建了一个使用CSV文件批量创建文件夹的小脚本.但我看到有些人使用不同的方式创建文件夹.

CSV:

folder
4.1.1 Process
4.1.2 Score card
4.1.3 Strategy
4.1.4 Governance
4.1.5 Master plan  Calendar
4.1.6 Budget follow up
4.1.7 Budget documentation
4.1.8 Benchmarkvision
4.1.9 Std Documentation
4.1.10 Layout
4.1.11 Project
4.1.12 Training
4.1.13 Team structure
4.1.14 Work shop
4.1.15 Tools
4.1.16 Problem solving
4.1.17 Presentation
4.1.18 Working data zone
4.1.19 meeting
4.1.20 S
4.1.21 Miscellenous
Run Code Online (Sandbox Code Playgroud)

脚本:

#change the $folderlist path as it's a hard link.
$folderlist = Import-Csv "C:\folders.csv"
$rootpath = read-host "Enter the path of the root folder where the csv files will be created"

foreach ($folder in $folderlist){
    $path = $rootpath+$folder.folder
    new-item -type directory -path $path
    } 
Run Code Online (Sandbox Code Playgroud)

很简单,但我看到人们使用$(_$.folder)我不理解的东西或其他功能.是否有人可以通过其他方式向我展示使用$_%{ }

我希望我的问题很明确,如果不是我会提供更多信息.

约翰

alr*_*roc 5

我认为我唯一会改变的(假设您的输入CSV格式正确)是您构建路径的方式.

foreach ($folder in $folderlist){
    $path = join-path -path $rootpath -childpath $folder.folder;
    new-item -type directory -path $path;
    } 
Run Code Online (Sandbox Code Playgroud)

备用:

foreach ($folder in $folderlist){
    new-item -type directory -path $rootpath -name $folder.folder;
    }
Run Code Online (Sandbox Code Playgroud)

备选2(源自上文):

$folderlist|foreach-object {new-item -type directory -path $rootpath -name $_.folder;}
Run Code Online (Sandbox Code Playgroud)

备选3(源自上文):

$folderlist|foreach-object {new-item -type directory -path (join-path -path $rootpath -childpath $_.folder);}
Run Code Online (Sandbox Code Playgroud)

%是别名foreach-object- 我总是在脚本和解释中使用扩展别名,以确保一切都清晰.

编辑:更简洁的一种方式,取决于您的CSV文件的大小,可能会更好地使用内存.

$rootpath = read-host "Enter the path of the root folder where the csv files will be created"
Import-Csv "C:\folders.csv"|foreach-object {new-item -type directory -path (join-path -path $rootpath -childpath $_.folder);}
Run Code Online (Sandbox Code Playgroud)