PowerShell脚本修改LastWriteTime遇类型转换错误,如何解决?
问题解决:修改文件LastWriteTime时的DateTime转换错误
错误原因很明确:PowerShell不会自动将字符串参数转换为DateTime类型,直接把$args[1]的字符串赋值给LastWriteTime属性(该属性要求System.DateTime对象),就会触发类型转换失败的异常;如果参数传递异常导致$args[1]为null,也会出现同样错误。
修复方案
方案1:显式转换字符串为DateTime对象
直接在赋值时将字符串参数转换为DateTime类型,有两种写法:
- 使用类型强制转换:
Get-ChildItem $args[0] | ForEach-Object { $_.LastWriteTime = [DateTime]$args[1] }
- 使用
Get-Date命令解析字符串:
Get-ChildItem $args[0] | ForEach-Object { $_.LastWriteTime = Get-Date $args[1] }
方案2:使用规范的参数定义(推荐)
用param块定义参数并添加类型约束,让PowerShell自动处理类型转换,同时提升脚本的可读性和容错性:
param( [Parameter(Mandatory=$true)] [string]$Path, [Parameter(Mandatory=$true)] [DateTime]$NewLastWriteTime ) Get-ChildItem $Path | ForEach-Object { $_.LastWriteTime = $NewLastWriteTime }
这种方式下,执行脚本时如果参数格式不正确,PowerShell会直接给出明确的错误提示,无需手动处理类型转换。
额外注意事项
- 日期字符串格式要匹配当前系统的区域设置,若要避免区域差异问题,建议使用ISO标准格式(如
"2024-01-01T19:27:00")。 - 如果目标路径是单个文件,也可以简化为
(Get-Item $args[0]).LastWriteTime = [DateTime]$args[1],无需遍历。
内容的提问来源于stack exchange,提问作者darchon
相关产品推荐
相关产品推荐

