首页 > 解决方案 > 使用 Literalpath 或有意复制项目的错误?

问题描述

考虑以下非常简单的代码:

Try {
    Copy-Item -Path '\\server\g$\thisfolder\thisfiledoesntexist.ini' -Destination 'c:\temp' -ErrorAction Stop
}
Catch {
    "Ran into an issue: $_"
}

这可以很好地捕获不存在的源文件的错误。但是以下不会 - 没有产生错误。

Try {
    Copy-Item -LiteralPath '\\?\UNC\server\g$\thisfolder\thisfiledoesntexist.ini' -Destination 'c:\temp' -ErrorAction Stop
}
Catch {
    "Ran into an issue: $_"
}

但是...这将捕获错误

Try {
    Get-ChildItem -LiteralPath '\\?\UNC\server\g$\thisfolder\thisfiledoesntexist.ini' -ErrorAction Stop | Copy-Item
}
Catch {
    "Ran into an issue: $_"
}

这是我第一次有机会使用文字路径 - 这种行为是有意的/预期的吗?

标签: powershell

解决方案


我认为您Copy-Item在 Windows PowerShell 下发现了一个错误。似乎?在输入中的任何位置都包含一个字符,-Path或者-LiteralPath阻止错误被困在不存在的路径中。

该错误似乎已在 PowerShell Core 上得到修复,您上面的代码确实会导致异常。


推荐阅读