Skip to content

Instantly share code, notes, and snippets.

@stknohg
Created March 7, 2016 08:02
Show Gist options
  • Save stknohg/7267be8b99842f75a350 to your computer and use it in GitHub Desktop.
Save stknohg/7267be8b99842f75a350 to your computer and use it in GitHub Desktop.
新規にDatetime型のオブジェクトを生成するコマンド
<#
.Synopsis
新規にDatetime型のオブジェクトを生成します。
.DESCRIPTION
新規にDatetime型のオブジェクトを生成します。
Get-Dateとは異なり現在時刻を基準とせず、未指定のパラメーターには初期値を割り当ててオブジェクトを生成します。
.OUTPUTS
Format パラメーターまたは UFormat パラメーターを使用した場合、Get-Date は文字列を返します。それ以外の場合は、DateTime オブジェクトが返されます。
.EXAMPLE
New-Date -Year 2016 -Month 3 -Day 7
.EXAMPLE
New-Date -Year 2016 -Month 3 -Day 7 -Format "yyyy/MM/dd"
.EXAMPLE
New-Date -Year 2016 -Month 3 -Day 7 -UFormat "%D"
#>
function New-Date
{
[CmdletBinding(DefaultParameterSetName="Default")]
[OutputType([Datetime], ParameterSetName="Default")]
[OutputType([string], ParameterSetName=("Format", "UFormat"))]
Param
(
[Parameter(Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Datetime]$Date,
[ValidateRange(1, 9999)]
[int]$Year,
[ValidateRange(1, 12)]
[int]$Month,
[ValidateRange(1, 31)]
[int]$Day,
[ValidateRange(0, 23)]
[int]$Hour,
[ValidateRange(0, 59)]
[int]$Minute,
[ValidateRange(0, 59)]
[int]$Second,
[ValidateRange(0, 999)]
[int]$Millisecond,
[Microsoft.PowerShell.Commands.DisplayHintType]$DisplayHint = [Microsoft.PowerShell.Commands.DisplayHintType]::DateTime,
[Parameter(ParameterSetName="Format")]
[string]$Format,
[Parameter(ParameterSetName="UFormat")]
[string]$UFormat
)
Process
{
$ReturnValue = $null
if( $null -ne $Date )
{
# Create Datetime from $Date object
$ReturnValue = $Date
}
if( $null -eq $ReturnValue )
{
# Create new Datetime object
if( $Year -le 0 ) { $Year = 1 }
if( $Month -le 0 ) { $Month = 1 }
if( $Day -le 0 ) { $Day = 1 }
if( $Hour -le 0 ) { $Hour = 0 }
if( $Minute -le 0 ) { $Minute = 0 }
if( $Second -le 0 ) { $Second = 0 }
if( $Millisecond -le 0 ) { $Millisecond = 0 }
Write-Verbose ("{0}/{1}/{2} {3}:{4}:{5}.{6:000}" -f $Year, $Month, $Day, $Hour, $Minute, $Second, $Millisecond)
$ReturnValue = New-Object System.DateTime $Year, $Month, $Day, $Hour, $Minute, $Second, $Millisecond
}
# Add DisplayHint property
Add-Member -InputObject $ReturnValue -MemberType NoteProperty -Name "DisplayHint" -Value $DisplayHint
# Format and return value.
if( $UFormat -ne "" )
{
return Get-Date -Date $ReturnValue -UFormat $UFormat
}
if( $Format -ne "" )
{
return Get-Date -Date $ReturnValue -Format $Format
}
return $ReturnValue
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment