Powershell的Add-Content应该创建路径,但是出现了“找不到路径的一部分”的异常。

5

我正在使用 PowerShell 的 Add-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" 

此命令创建一个新目录和文件,并将现有文件的内容复制到新创建的文件中。该命令使用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 似乎是Add-Content中的一个明显问题,你能重现这个问题吗?
编辑:我正在运行PowerShell版本5.1.16299.64
BR Matthias

我认为文档缺少代码片段的一部分。正如动词所示; 它会将内容“添加”到现有项目中。 - gvee
1
我打开了一个问题:https://windowsserver.uservoice.com/forums/301869-powershell/suggestions/33062206-add-content-should-create-folder-but-returns-error - Matthias
你的PowerShell版本是什么?你正在运行5.1吗?这很重要,但在你的问题或错误报告中并没有明确说明。 - Matt
好的,我正在运行5.1.16299.64。 - Matthias
2个回答

6

只是另一种选择:

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

即使这个答案与@fdafadf相同,我认为这个解决方案更易读。 - Pierre-Gilles Levallois

5
< p > Add-Content cmdlet 无法创建路径,只能创建文件。它可以正常工作:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接