You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell脚本报错:[System.IO.DirectoryInfo]无op_Addition方法

解决PowerShell中[System.IO.DirectoryInfo] does not contain a method named 'op_Addition'报错

嘿,这个问题我碰到过好多次!你这是典型的PowerShell类型不匹配坑——你的$ParentDirectory是个[System.IO.DirectoryInfo]对象,不是字符串格式的路径,所以没法直接用+运算符跟其他字符串拼接,这就是报错的根源。

报错代码拆解

你出问题的代码行:

$LogPath = $ParentDirectory + '\InstallLog_' + $CurrentDate + '.txt'

这里的$ParentDirectory应该是通过Get-Item、Get-ChildItem这类命令拿到的目录对象,或者你新加的引用脚本里把它从字符串改成了DirectoryInfo类型,导致原本的字符串拼接逻辑直接失效。

三种靠谱解决方案

1. 调用对象的FullName属性(最直观)

直接用FullName获取字符串格式的完整路径,再拼接:

$LogPath = $ParentDirectory.FullName + '\InstallLog_' + $CurrentDate + '.txt'

2. 用Join-Path命令(强烈推荐,更专业)

PowerShell专门有处理路径的Join-Path命令,它会自动搞定路径分隔符,不用手动加\,跨平台也友好:

$LogPath = Join-Path -Path $ParentDirectory -ChildPath "InstallLog_$CurrentDate.txt"

甚至直接把DirectoryInfo对象传给-Path参数就行,PowerShell会自动识别路径。

3. 强制转成字符串

用双引号把变量包起来,PowerShell会自动把DirectoryInfo对象转成字符串(本质是调用它的ToString()方法,返回的就是完整路径):

$LogPath = "$ParentDirectory" + '\InstallLog_' + $CurrentDate + '.txt'

为啥加了引用脚本才报错?

大概率是你引用的脚本修改了$ParentDirectory的类型——比如原本它是个字符串路径,引用脚本里用Get-Item $ParentDirectory把它转成了DirectoryInfo对象,这下原本的字符串拼接逻辑就不适用啦。

内容的提问来源于stack exchange,提问作者Nayrb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:26:16