我正在为“我的生日是***天!”倒计时编写脚本,并将其转换为HTML格式为MyBirthday.html。
到目前为止,这是
function Date {
$Name = Read-Host "Please enter your name"
$BirthMonth = Read-Host "Please enter your Month of Birthday"
$BirthDay = Read-Host "Please enter your Day of Birthday"
$BirthYear = (Get-Date).Year
$NumberOfDays=(New-TimeSpan -End "$BirthYear/$BirthMonth/$BirthDay").Days
if ($NumberOfDays -eq 0) {
Write-Host "Happy Birthday $Name. Today is your Birthday! Yeah!"
}
else {
Write-Host "Hello $Name, there are $NumberOfDays days to your Birthday!"
}
}
Out-File Date > C:\Users\Desktop\Date.html
答案 0 :(得分:0)
理想情况下,您希望将所有内容保留为对象(在本例中为DateTime对象),因为它更容易操作。
我会这样做 - 我已经注释了评论,但是如果你有任何问题请问。
function Date ($Name,$BirthMonth,$BirthDay)
{
#Create a datetime object
$Date = Get-Date -day $BirthDay -month $BirthMonth -year ((Get-Date).Year)
#Check if the entered date is before today
if($Date -lt (Get-Date))
{
#If so add 1 year
$Date = $Date.AddYears(1)
}
$NumberOfDays = New-Timespan -Start (Get-Date) -End $date
if ($NumberOfDays.Days -eq 0)
{
$result = "Happy Birthday $Name. Today is your Birthday! Yeah!"
}
else
{
$result = "Hello $Name, there are $($NumberOfDays.Days) days to your Birthday!"
}
#Create an object to return (Objects are easier and more flexible to work with down the pipeline)
$return = New-Object PSObject -Property @{
'Days Remaining' = $result
}
#Return the object
$return
}
#User input outside of the function (makes the function re-usable)
$Name = Read-Host "Please enter your name"
$BirthMonth = Read-Host "Please enter your Month of Birthday"
$BirthDay = Read-Host "Please enter your Day of Birthday"
#Call the function, pass the input and pipe the output
Date $Name $BirthMonth $BirthDay | ConvertTo-HTML > C:\users\jacob\desktop\date.html
#Demonstration of the returned object
Date $Name $BirthMonth $BirthDay