我创建了一个脚本,它在每个月(格式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
}
}
}
Run Code Online (Sandbox Code Playgroud)
我认为你通过为参数提供默认值然后在使用默认值时给出错误消息来使事情过于复杂.如果您希望参数是必需的,您应该声明它们.实际上,您可以更进一步,将它们声明为有效路径和特定范围内的数字.
否则我的主要观察是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}"
}
}
Run Code Online (Sandbox Code Playgroud)
唯一的另一件事是,如果你想经常使用它,最好把它变成一个函数或cmdlet,然后你可以将它保存在一个带有其他cmdlet的模块中.此外,如果您这样做,每个参数之前的注释将成为帮助屏幕的一部分,您可以在功能声明顶部的注释中包含帮助屏幕的说明和示例.
PS对于血腥的PowerShell初学者我推荐http://www.microsoftvirtualacademy.com/training-courses/getting-started-with-powershell-3-0-jump-start
| 归档时间: |
|
| 查看次数: |
2489 次 |
| 最近记录: |