在每个月初的目录中,我需要为该月的每一天创建一个文件夹(格式为 DDMMYYYY)。我只想在每个月的第一天运行此脚本并计算该月的天数。我尝试过以下脚本,但不确定如何对其进行自定义以满足我的需求:
非常感谢任何想法/建议。
答案1
编辑:我错过了DDMMYYYY
要求,现已修复。
Powershell 单行命令。只需在目录中打开 PowerShell 控制台并运行:
袖珍的:
1..([datetime]::DaysInMonth([datetime]::Now.Year,[datetime]::Now.Month)) | % {md ".\$(([datetime]::ParseExact("$_/$([datetime]::Now.Month)/$([datetime]::Now.Year)", 'd/M/yyyy', [System.Globalization.CultureInfo]::InvariantCulture)).ToString('ddMMyyyy'))"}
无别名:
1..([datetime]::DaysInMonth([datetime]::Now.Year,[datetime]::Now.Month)) | ForEach-Object {New-Item -ItemType Directory -Path ".\$(([datetime]::ParseExact("$_/$([datetime]::Now.Month)/$([datetime]::Now.Year)", 'd/M/yyyy', [System.Globalization.CultureInfo]::InvariantCulture)).ToString('ddMMyyyy'))"}
人类可读的:
1..([datetime]::DaysInMonth([datetime]::Now.Year,[datetime]::Now.Month)) |
ForEach-Object {
New-Item -ItemType Directory -Path ".\$(([datetime]::ParseExact("$_/$([datetime]::Now.Month)/$([datetime]::Now.Year)", 'd/M/yyyy', [System.Globalization.CultureInfo]::InvariantCulture)).ToString('ddMMyyyy'))"
}
这更像脚本,您必须将其保存为CreateFolders.ps1
并从 PowerShell 控制台运行,如下所示:.\CreateFolders.ps1
。已注释,因此您可以真正了解幕后发生的事情:
# Get current Year and Month
$CurrYear = [datetime]::Now.Year
$CurrMonth = [datetime]::Now.Month
# Create new array with numbers from 1 to DaysInMonth
1..([datetime]::DaysInMonth($CurrYear, $CurrMonth)) |
# For each element in array
ForEach-Object {
# Generate name for new directory in ddMMyyyy format
# To do so, we create new DateTime Object with day from pipeline and current year and month
# Then we convert it to the abovementioned format
$DirName = ([datetime]::ParseExact("$_/$CurrMonth/$CurrYear", 'd/M/yyyy', [System.Globalization.CultureInfo]::InvariantCulture)).ToString('ddMMyyyy')
# Correctly join path with current directory and new folder name
$Path = Join-Path -Path (Get-Location).Path -ChildPath $DirName
# Create new directory
New-Item -ItemType Directory -Path $Path
}