Powershell Add-Content 应该创建路径但抛出异常“无法找到路径的一部分”

Mat*_*ias 5 powershell

我正在使用 powershellAdd-Content创建文件。但是,当文件的文件夹不存在时,我收到错误:

Add-Content : Could not find a part of the path 'C:\tests\test134\logs\test134.log'.

根据文档,这应该创建文件夹:

PS C:\> Add-Content -Value (Get-Content "test.log") -Path  "C:\tests\test134\logs\test134.log" 
Run Code Online (Sandbox Code Playgroud)

此命令创建一个新的目录和文件,并将现有文件的内容复制到新创建的文件中。

此命令使用 Add-Content cmdlet 添加内容。Value 参数的值是一个 Get-Content 命令,该命令从现有文件 Test.log 中获取内容。

path参数的值为命令运行时不存在的路径。在此示例中,仅存在 C:\Tests 目录。该命令创建其余目录和 Test134.log 文件。

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/add-content?view=powershell-5.1

这似乎是添加内容中的一个明显问题,不是吗?你能重现这个吗?

编辑:我正在运行 PowerShell 版本 5.1.16299.64

BR马蒂亚斯

小智 6

只是另一种选择:

$Path = "C:\tests\test134\logs2\test134.log"
If (!(Test-Path $Path)) {New-Item -Path $Path -Force}
Add-Content -Path $Path -Value "Sample Content"
Run Code Online (Sandbox Code Playgroud)


fda*_*adf 5

Add-Contentcmdlet 无法创建路径,只能创建文件。有用:

$Path = "C:\tests\test134\logs2\test134.log"
$Path |% { 
           If (Test-Path -Path $_) { Get-Item $_ } 
           Else { New-Item -Path $_ -Force } 
} | Add-Content -Value 'sample content'
Run Code Online (Sandbox Code Playgroud)