powershell 获取文件时间提示错误FullyQualifiedErrorIdInvokeMethodOnNull InvokeMethodOnNull

前言全局说明


一、说明

1.1 调试环境:

Windows 11 家庭版 24H2 26100.4061

二、PowerShell版本

$PSVersionTable.PSVersion
Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      26100  7920

三、问题

图片内容:
image

文本内容:

PS D:\tmp> $PSVersionTable.PSVersion

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      26100  7920


PS D:\tmp>
PS D:\tmp>
PS D:\tmp> powershell -command "(Get-Item 't1.doc').LastWriteTime.ToString('yyyy-MM-dd HH:mm:ss')"
2026-04-10 12:10:43
PS D:\tmp>
PS D:\tmp> powershell -command "(Get-Item 't2_[自].doc').LastWriteTime.ToString('yyyy-MM-dd HH:mm:ss')"
不能对 Null 值表达式调用方法。
所在位置 行:1 字符: 1
+ (Get-Item 't2_[自].doc').LastWriteTime.ToString('yyyy-MM-dd HH:mm:ss')
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [],RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

PS D:\tmp>
PS D:\tmp>

四、原因、解决方法

4.1 原因

因为 PowerShell 中 [ 和 ] 是通配符,用于匹配任意字符。

执行 Get-Item 't2_[自].doc' 时,PowerShell 把它当作通配符路径解析,
找不到匹配的文件,返回了 $null,因此对 $null 调用 .LastWriteTime 就报错了。

4.2 解决方法(推荐)

使用 -LiteralPath 告诉 PowerShell 把路径当作字面字符串处理,不解释通配符
适合处理文件名中带有特殊字符(如 [、]、`、*、? 等)

powershell -command "(Get-Item -LiteralPath 't2_[自].doc').LastWriteTime.ToString('yyyy-MM-dd HH:mm:ss')"

image

4.3 解决方法 (不推荐,不灵活)

另一种方法,在特殊符号前加上转义符号
把 [ 替换成 `[
把 ] 替换成 `]

powershell -command "(Get-Item 't2_`[自`].doc').LastWriteTime.ToString('yyyy-MM-dd HH:mm:ss')"


免责声明:本号所涉及内容仅供安全研究与教学使用,如出现其他风险,后果自负。




参考、来源:
https://chat.deepseek.com/a/chat/s/0732ada7-34c8-4bb9-9cef-80be29876e19



posted @ 2026-05-07 20:35  悟透  阅读(43)  评论(0)    收藏  举报