powershell - 解析日期时间时出错

标签 powershell powershell-2.0

我正在尝试解析“时间”字符串以进行比较

$Test2 =[datetime]::Parse("24/09/2015 05:41:27",[Globalization.cultureinfo]::GetCultureInfo("en-US")) 
$Test2

$Test =[datetime]::Parse("23/09/2015 05:41:27",[Globalization.cultureinfo]::GetCultureInfo("en-US")) 
$Test


if($Test2 -gt $Test)
 write-host comparison works

我收到以下错误:

Exception calling "Parse" with "2" argument(s): "String was not recognized as
a valid DateTime."
At C:\Users\Desktop\ne.ps1:1 char:1
+ $Test =[datetime]::Parse("23/09/2015
05:41:27",[Globalization.cultureinfo]::GetC ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FormatException

最佳答案

en-US 区域性使用月-日-年格式,因此您需要:

  1. 转换您使用的文化
  2. 改变输入字符串的格式

这是一个代码示例:

### Change the date/time input string
[datetime]::Parse("09/23/2015 05:41:27")

### Use the Great Britain culture
[datetime]::Parse("23/09/2015 05:41:27", [cultureinfo]::GetCultureInfo('en-GB'))

DateTime

关于powershell - 解析日期时间时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32894418/

相关文章:

sql-server - 使用 powershell 检查 RAM、页面文件、/PAE、/3GB、SQL 服务器内存

Powershell 构建脚本 - 从任何机器执行它

.net - 在 PowerShell 中使用 System.Net.WebClient 通过 SAN 证书访问 HTTPS URL

powershell - 对列表使用for循环并将元素设置为环境变量,然后获取值

powershell - 如何在powershell中传递 "get-content command "中的变量

powershell - 新对象 : The term New-Object is not recognized as the name of a cmdlet

windows - 我需要一个 powershell 脚本来监控正在运行的 Windows 计划任务超过 X 分钟

powershell - 使用PowerShell脚本替换DLL版本信息中的内部版本号

powershell - 尚未为 Windows PowerShell 版本 2 注册任何管理单元

powershell - 尝试通过网络共享在远程PC上创建进程