非IT企業に勤める中年サラリーマンのIT日記

非IT企業でしかもITとは全く関係ない部署にいる中年エンジニア。唯一の趣味がプログラミングという”自称”プログラマー。

PowerShellで時間操作(加算/減算/月末/シリアル値)

      2020/04/14

PowerShellで時間操作の方法です。

# 基本形
$d = Get-Date
Write-Output $d
# 出力
# 2020年4月12日日曜日 8:58:33

# 出力フォーマットを指定
$d = Get-Date -Format "yyyy/MM/dd HH:mm:ss"
Write-Output $d
# 出力
# 2020/04/12 08:58:33

# 次の日
$d = (Get-Date).AddDays(1)
Write-Output $d
# 出力
# 2020年4月13日月曜日 8:58:33

# 前の月
$d = (Get-Date).AddMonths(-1)
Write-Output $d
# 出力
# 2020年3月12日木曜日 8:58:33

#月初
$d = (Get-Date -Day 1)
Write-Output $d
# 出力
# 2020年4月1日水曜日 8:58:33

#月末
$d = (Get-Date -Day 1).AddMonths(1).AddDays(-1)
Write-Output $d
# 出力
# 2020年4月30日木曜日 8:58:33

#日付の差
$d1 = Get-Date
$d2 = (Get-Date).AddDays(1)
Write-Output ($d2-$d1).Days
# 出力
# 1

#シリアル値 1ティック=100ナノ秒
$d1 = Get-Date
$d2 = (Get-Date).AddDays(1)
Write-Output ($d2-$d1).Ticks
Write-Output ([int](($d2-$d1).Ticks / 10000000 / 60 / 60))
# 出力
# 864000002323
# 24
 

 

スポンサーリンク

 - PowerShell