如下图所示,names.txt文件中有6个姓名,要求在C:\Users\admin\Desktop\演示目录目录中创建根据每个姓名创建对应的文件夹。
cmd 进入C:\Users\admin\Desktop\演示目录目录,执行powershell命令启动powershell,然后将下面的powershell脚本粘贴进去,回车,任务就完成了。
------>注:该脚本需要确保txt文件的格式是每行一个名字
# 设置TXT文件的路径和目标目录
$filePath = "C:\Users\admin\Desktop\names.txt"
$targetDirectory = "C:\Users\admin\Desktop\演示目录"
# 确保目标目录存在
if (-Not (Test-Path -Path $targetDirectory)) {
New-Item -ItemType Directory -Path $targetDirectory
}
# 读取TXT文件中的每一行(即每个人名)
Get-Content -Path $filePath | ForEach-Object {
# 去除人名可能的前后空格
$name = $_.Trim()
# 创建以人名命名的文件夹路径
$folderPath = Join-Path -Path $targetDirectory -ChildPath $name
# 检查文件夹是否已存在
if (-Not (Test-Path -Path $folderPath)) {
# 创建文件夹
New-Item -ItemType Directory -Path $folderPath
Write-Host "文件夹 '$folderPath' 已创建。"
} else {
Write-Host "文件夹 '$folderPath' 已存在。"
}
}