如何在PowerShell Plus中创建一组接受用户输入的文件夹
我试图通过提示用户输入年份,为每个月创建12个文件夹。一旦用户输入年份,我会让程序检查文件夹名称是否存在。如果它不存在,我希望程序创建带有_01、_02、_03等的文件夹名。。。在文件夹名称的末尾自动生成文件夹名称示例2020\u 01。我可以创建一个没有foreach语句的文件夹。一旦我添加foreach以限制文件夹数量并自动命名文件夹,我就失败了。任何指导都将不胜感激如何在PowerShell Plus中创建一组接受用户输入的文件夹,powershell,foreach,directory,Powershell,Foreach,Directory,我试图通过提示用户输入年份,为每个月创建12个文件夹。一旦用户输入年份,我会让程序检查文件夹名称是否存在。如果它不存在,我希望程序创建带有_01、_02、_03等的文件夹名。。。在文件夹名称的末尾自动生成文件夹名称示例2020\u 01。我可以创建一个没有foreach语句的文件夹。一旦我添加foreach以限制文件夹数量并自动命名文件夹,我就失败了。任何指导都将不胜感激 $folderpath = "C:\MyScripts" Do { $curryear = Join
$folderpath = "C:\MyScripts"
Do
{
$curryear = Join-Path $folderpath (Read-Host -Prompt "Enter the year
for the folder structure: ")
If (Test-Path -Path $curryear)
{
$existingFolder = $true
Write-Host "Folder exists"
}
Else
{
$existingFolder = $false
ForEach-Object {
New-Item -Path $folderpath -ItemType Directory -Name ($curryear + "-01") |
Out-Null
Write-Host "Creating folder name " $curryear
}
}
} While ($existingFolder)
在for-each循环中,您没有定义任何要查看的数字或列表。您需要定义数字,例如1-12(月份),以迭代并基于这些数字创建文件夹。我使用了
(1..12)
,这与for循环的用法大致相同,for(inti=0;I<12;I++)
此外,当您迭代这些数字时,您可以使用格式化选项在创建文件夹时使用01,而不仅仅是1,以确保名称的一致性。为此,请使用-f选项(“0:d2”-f1)
我注意到的另一个问题是,在创建文件夹时,您使用了完整路径作为文件夹的名称。您只需要在-name
参数中提供名称,因为您已经提供了路径。为此更改了$curryear
分配
$folderpath = "C:\Temp\Date"
Do
{
$curryear = Read-Host -Prompt "Enter the year for the folder structure: "
If (Test-Path -Path (Join-Path $folderpath $curryear*))
{
$existingFolder = $true
Write-Host "Folder exists"
}
Else
{
$existingFolder = $false
(1..12) | ForEach-Object {
$month = curryear + ("_{0:d2}" -f $_)
New-Item -Path $folderpath -ItemType Directory -Name $month |Out-Null
Write-Host "Creating folder name " $month
}
}
} While ($existingFolder)
上述方法的另一个变体是继续创建文件夹,除非写入退出。如果删除了以前已创建的一年的子文件夹,则此过程将起作用,并且只创建丢失的文件夹
$folderpath = "C:\Temp\Date"
While ($true)
{
$curryear = Read-Host -Prompt "Enter the year for the folder structure (quit): "
if ($curryear -eq "quit") {
break
}
(1..12) | ForEach-Object {
$month = $curryear + ("_{0:d2}" -f $_)
try {
New-Item -Path $folderpath -ItemType Directory -Name $month -ea Stop |Out-Null
Write-Host "Creating folder name " $month
}
catch{
Write-Host "Folder $month already exists"
}
}
}
如何回显创建的文件夹名?@CVYCCVYC将*添加到测试路径语句中。另外,将Name和Write Host语句更改为使用变量$month。请参阅上面的更改:)我感谢您的帮助。@CVYCCVYC创建文件夹的不同方式(假设删除了一年中特定月份的文件夹),同时继续循环直到您写入退出。