简体   繁体   中英

Read-Host Powershell datetime

I am trying to read date and time in powershell and using that date and time to sort by name and last write time. When I enter the value with only date I don't see any issues but when I add time I keep getting the below error. How do I get this working?

Could not compare "05/20/2014 11:42:18" to "'05/22/2014 10:00:00'". Error: "Cannot convert value "'05/22/2014 10:00:00'" to type "System.DateTime". Error: "String was not recognized as a valid DateTime.""

My Powershell code

$datetime= Read-Host "Enter the date time in this format 'mm/dd/yyyy hh:mm:ss'"
if(($datetime -as [DateTime]) -ne $null)
{
  $datetime = [DateTime]::Parse($datetime)
  $datetime
}
else
{
  Write-Host "You did not enter proper date time"
}

$File= Get-ChildItem $FileLocation -Filter *.sql -Recurse | Where-Object {$_.LastWriteTime -gt $datetime} | Sort-Object Name

尝试使用(Get-Date $ datetime)获取要使用的PowerShell日期对象。

There is two problems.

The first is that, based on the error message you are entering in the date time with single quotes around the date time. You do not need to do this.

The second is that, yes it is not a valid date time. So the if statement will output "You did not enter proper date time"

Then it proceeds to the $File= Get-Child .... , which of course will throw an error because the date time is improper.

What you need to do is to put the line $File= Get-Child .... inside your if statement so that it will only execute if the date time is proper.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM