gpt4 book ai didi

powershell - 生成一整年的月文件夹和日子文件夹

转载 作者:行者123 更新时间:2023-12-04 14:12:18 24 4
gpt4 key购买 nike

我创建了一个脚本,该脚本在给定路径(第一个参数)中生成每个月的文件夹(格式 yyyy_mm),并在每个文件夹中生成每天的子文件夹(格式 yyyy_mm_dd)。

该代码有效,但有没有更简单的解决方案?

param(
[string]$inppath = '',
[string]$inpyear = '0'
)
function dayfolder
{
1..[DateTime]::DaysInMonth($inpyear,$month) | ForEach-Object {
$day = $_
New-Item -ItemType directory -Force -Path ($inppath + '\' + $inpyear + '_' + ("{0:D2}" -f $month) + '\' + $inpyear + '_' + ("{0:D2}" -f $month) + '_' + ("{0:D2}" -f $day) ) }
}

if ($inppath -eq '')
{
echo 'No path in input! First parameter!'
}
else
{
if ($inpyear -eq '0')
{
echo 'No year in input! Second parameter! Format: YYYY'
}
else
{
1..12 | ForEach-Object {
$month = $_
New-Item -ItemType directory -Force -Path ($inppath + '\' + $inpyear + '_' + ("{0:D2}" -f $month))
dayfolder
}
}
}

最佳答案

我认为您通过为参数提供默认值然后在使用默认值时给出错误消息来使事情变得过于复杂。如果您希望参数是强制性的,您应该这样声明它们。事实上,您可以更进一步,将它们声明为有效路径和特定范围内的数字。

否则我的主要观察是 New-Item 创建它需要的任何父项,因此您不需要单独创建月份文件夹。

有多种方法可以构建路径字符串,但我认为在这种情况下,最简单的方法是格式化月份和日期,然后只使用单个字符串(请注意,_ 是变量名中的有效字符在某些情况下使用 ${...} 形式的变量扩展):

param(
# Path to an existing folder.
[Parameter(Mandatory=$True)]
[ValidateScript({Test-Path $_ -PathType 'Container'})]
[string]$inppath,

# Year must be fairly recent or in the future. Warranty expires 2100
[Parameter(Mandatory=$True)]
[ValidateRange(1999,2100)]
[int]$inpyear
)

1..12 | ForEach-Object {
$month = "{0:D2}" -f $_
1..[DateTime]::DaysInMonth($inpyear,$month) | ForEach-Object {
$day = "{0:D2}" -f $_
New-Item -ItemType directory -Force -Path "$inppath\${inpyear}_$month\${inpyear}_${month}_${day}"
}
}

唯一的另一件事是,如果您想经常使用它,最好将其转换为函数或 cmdlet,然后您可以将其与其他 cmdlet 一起保存在模块中。此外,如果您这样做,每个参数之前的注释将成为帮助屏幕的一部分,您可以在函数声明顶部的注释中包含帮助屏幕的描述和示例。

附言对于血腥的 powershell 初学者,我推荐 http://www.microsoftvirtualacademy.com/training-courses/getting-started-with-powershell-3-0-jump-start

关于powershell - 生成一整年的月文件夹和日子文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27500025/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com