2016年12月17日

【PowerShell】カレンダー表示スクリプトを作ってみた


今年もあと残りわずかとなってきましたが、そろそろ来年のカレンダーの購入なんて考えてる方も多いのではないでしょうか。

そこでふと思ったのは、PowerShellでカレンダーの表示はできないものか?

調べたところ、どうやらそういうコマンドレットは無いらしいです。(当たり前か)

うーん・・・、じゃあ作るか!

そんなわけで、PowerShellでカレンダー表示スクリプトを作成してみました。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#カレンダー表示スクリプト
 
#パラメータ
Param($year, $month)
 
if (($year -eq $null) -And ($month -eq $null)){
    #両方nullなら今月
    $y = (Get-Date).Year
    $m = (Get-Date).Month
} elseif (($year -ne $null) -And ($month -ne $null)) {
    #パラメータがある場合は入力値の月
    $y = $year
    $m = $month
} else {
    #それ以外はエラー
    Write-Output 'パラメータが間違っています。[年] [月]を指定してください。'
    exit
}
 
#ついたちの曜日値を取得
$firstDayOfWeek = (Get-Date -Year $y -Month $m -Day 1).DayOfWeek.value__
 
#始まりの空白を設定
$startWeek = $firstDayOfWeek * 7 + 2
$space = ""
for ($j=0; $j -lt $startWeek; $j++){
    $space = $space + " "
}
 
#その月の最終日を取得
$nextMonthDate = (Get-Date -Year $y -Month $m -Day 1).AddMonths(1)
$lastDay = (Get-Date -Year $nextMonthDate.Year -Month $nextMonthDate.Month -Day 1).AddDays(-1).day
 
#年月表示
Write-Host $y"年"$m"月"
 
#曜日の表示
Write-Host "SUN    MON    TUE    WED    THU    FRI    SAT"
 
#日付部分を作成
$weekValue = $firstDayOfWeek
$dayString = $space
for ($i=1; $i -le $lastDay; $i++){
 
    if ($i -ge 9){
        $dayString = $dayString + $i + "     "
    } else {
        $dayString = $dayString + $i + "      "
    }
     
    $weekValue = $weekValue + 1
 
    if ($weekValue -eq 7) {
        #土曜日までいったら改行
        $dayString = $dayString.TrimEnd()
        if ($i -lt 9){
            $dayString = $dayString + "`n" + "  "
        } else {
            $dayString = $dayString + "`n" + " "
        }
        $weekValue = 0
    }
}
 
#日付の表示
Write-host $dayString.TrimEnd()
パラメータで年、月を指定すると、その年月のカレンダーが表示されます。
何も指定しなければ今月のカレンダーが表示されるようにしました。


実行するとこんな感じになります。

パラメータなし。
今月のカレンダーが表示されます。


パラメータあり。
2017年1月のカレンダーが表示されています。




スポンサーリンク



Follow Me on Pinterest
Clip to Evernote