PowerShell在周一至周五打印此工作周

时间:2019-01-24 00:29:15

标签: powershell

我希望Powershell确定当前星期和印刷星期一-星期五,格式为:

mm/dd/yyyy - mm/dd/yyyy

我看到了一种获取星期几的方法,这很好,但是我想让它显示日期。

到目前为止,我可以使用它,但是如果我在星期一以外的任何时间运行,日期将不显示:

$bar = "------------------------------------"
$today = (Get-Date)
$dates = @($today.AddDays(0).ToString('MM-dd-yyyy'),
$today.AddDays(1).ToString('MM-dd-yyyy'),
$today.AddDays(2).ToString('MM-dd-yyyy'),
$today.AddDays(3).ToString('MM-dd-yyyy'),
$today.AddDays(4).ToString('MM-dd-yyyy'))

$result = "`n{0}`n{1}`n`n`n{2}`n{3}`n`n`n{4}`n{5}`n`n`n{6}`n{7}`n`n`n{8}`n{9}`n" -f $dates[0], $bar, $dates[1], $bar, $dates[2], $bar, $dates[3], $bar, $dates[4], $bar

echo $result

2 个答案:

答案 0 :(得分:0)

这似乎可以满足您的要求。 [ grin ]它使用内置的工作日列表,使用当前工作日名称将其索引,计算当前一周的第一天,生成当前星期的日期数组,最后将其打印出来与您想要的线条和垂直间距。

# for my locale, the 1st day is "Sunday"
$WeekDayList = [System.DayOfWeek].GetEnumNames()
$Line = '-' * 40
$Newline = [environment]::NewLine
$BlankLineCount = 3

# the ".Date" property gives you midnite, not "now"
$Today = (Get-Date).Date
$TodayNumber = $WeekDayList.IndexOf($Today.DayOfWeek.ToString())
$WeekStartDate = $Today.AddDays(-$TodayNumber)

$CurrentWeek = foreach ($Offset in 0..6)
    {
    $WeekStartDate.AddDays($Offset).ToString('yyyy-MM-dd')
    }

-join ($CurrentWeek -join "$Newline$Line$($Newline * $BlankLineCount)"), "$Line$($Newline * $BlankLineCount)"

输出...

2019-01-20
----------------------------------------


2019-01-21
----------------------------------------


2019-01-22
----------------------------------------


2019-01-23
----------------------------------------


2019-01-24
----------------------------------------


2019-01-25
----------------------------------------


2019-01-26
----------------------------------------


[not part of the output - needed to show that there are two blank lines above this one. [*grin*]     

答案 1 :(得分:0)

我遇到了从工作日开始获取日期的要求,并编写了一个返回[DateTime]的函数。

使用此功能和ToString()将日期格式化为您的要求,输出为:

2019/01/21 - 2019/01/25

代码:

Function Get-DateFromDay {
    param(
        [Parameter(Mandatory = $true)]
        [ValidateSet('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')]
        [string]$WeekDay,

        [Int]$AddWeeks = 0
    )

    $DayNumber = @{
        'Saturday'  = 1; 
        'Sunday'    = 0; 
        'Monday'    = -1;
        'Tuesday'   = -2; 
        'Wednesday' = -3;
        'Thursday'  = -4
        'Friday'    = -5
    }

    [System.Datetime]$Today = Get-Date
    $NumDaysSinceDateFromDay = $Today.DayOfWeek.value__ + $DayNumber[$WeekDay]

    [System.Datetime]$DateFromDayThisWeek = $Today.AddDays(-$NumDaysSinceDateFromDay)
    $DateFromDayThisWeek.AddDays( + ($AddWeeks * 7))
}


$Monday = (Get-DateFromDay -WeekDay Monday).ToString('yyyy/MM/dd')
$Friday = (Get-DateFromDay -WeekDay Friday).ToString('yyyy/MM/dd')

Write-Output "$Monday - $Friday"

以及一些以后使用此帖子的人的使用示例:

下周星期四:

Get-DateFromDay -WeekDay Thursday -AddWeeks 1

上周二:

Get-DateFromDay -WeekDay Tuesday -AddWeeks -1