带有PS脚本的每月文件夹

时间:2017-01-24 15:09:39

标签: powershell

我正在尝试创建一个脚本,在用户输入一年,文件路径和dayoftheweek之后。将在指定月份的第一天每月创建一个文件夹一年。因此,如果用户输入“星期三”,它将在每个月找到第一个星期三的日期并创建该文件夹。

输入示例为:

New-DayOfWeekFolders -parentPath c:\temp -year 2017  -dayOfWeek wednesday

我知道它有很多错误(我对脚本很糟糕)但这就是我现在所拥有的:

function NewMonthlyFolder{

    param(
    [string] $ParentPath,
    [string] $Year, 
    [string] $DayOfWeek
)

$start = Get-Date $Year
$end = Get-Date
    $day = [enum]::Parse([type]"System.DayOfWeek", $DayOfWeek)

    While($start.DayOfWeek -ne $day) 
    {
        $start = $start.AddDays(1)
    }
    Do
    {
        $folderName = $start.ToString("yyyy-MM-dd")
        New-Item -Path $ParentPath -Name $folderName -ItemType directory
        $start = $start.AddMonths(1)).AddDays(-1)
    } While($start -le $end)
}

2 个答案:

答案 0 :(得分:1)

尝试这样的事情

[string] $ParentPath="C:\temp"
[string] $Year="2005" 
[string] $DayOfWeek="lundi"


$LowerDayOfWeek=$DayOfWeek.ToLower()

for ($i = 1; $i -lt 13; $i++)
{ 
   $start = get-date -Year $Year -Month $i -Day 1

   for ($j = 0; $j -lt 7; $j++)
   {
       $currentdate=$start.AddDays($j)

       if ($currentdate.ToString("dddd") -eq $LowerDayOfWeek)
       {
           New-Item -ItemType Directory -path "$ParentPath\$($currentdate.ToString("yyyy-MM-dd"))" -Force
           break
       }
   }

}

答案 1 :(得分:0)

其他解决方案

[string] $ParentPath="C:\temp"
[string] $Year="2017" 
[string] $DayOfWeek="monday"

for ($i = 1; $i -lt 13; $i++)
{ 
   $start = get-date -Year $Year -Month $i -Day 1
   $daysToFirstCorrectDay = (([Int] [DayOfWeek] $DayOfWeek) - [Int]$start.DayOfWeek + 7) % 7;
   $NewParth=$start.AddDays($daysToFirstCorrectDay).ToString("yyyy-MM-dd");
   New-Item -ItemType Directory -path "$ParentPath\$NewParth" -Force -WhatIf
}