PowerShell:无法将数据写入包含方括号的UNC路径

PowerShell:无法将数据写入包含方括号的UNC路径,powershell,unc,Powershell,Unc,这就是我遇到的问题: # The following line works Add-Content -LiteralPath "$Env:USERPROFILE\Desktop\[Test].txt" -Value "This is a test" # The following line does not work and does not output an error message Add-Content -LiteralPath "\\Server\Share\[Test].txt"

这就是我遇到的问题:

# The following line works
Add-Content -LiteralPath "$Env:USERPROFILE\Desktop\[Test].txt" -Value "This is a test"

# The following line does not work and does not output an error message
Add-Content -LiteralPath "\\Server\Share\[Test].txt" -Value "This is a test"
我已经检查了我的权限,我肯定有权限写入网络共享。只有当我使用“LiteralPath”参数时,问题才会出现,不幸的是,这是我所做的工作所必需的

如何将数据写入包含方括号的UNC路径?

您将在有关PowerShell表达式中“方括号”奇怪行为的解释中找到

但是

当我写下以下内容(没有括号)时,它对我来说根本不起作用:

Set-Content -LiteralPath "\\server\share\temp\test.txt" -Value "coucou"
但是(根据微软的文章)以下方法是有效的

Set-Content -Path "\\server\share\temp\test.txt" -Value "coucou"
set-content -path '\\server\share\temp\`[test`].txt' -Value "coucou"
set-content -literalpath "u:\temp\[test].txt" -Value "coucou"
我试图用PowerShell Drive解决这个问题

New-PSDrive -Name u -PSProvider filesystem -Root "\\server\share"
甚至是最糟糕的

Set-Content : Impossible de trouver une partie du chemin d'accès '\\server\share\server\share\server\share\temp\test.txt'.
Au niveau de ligne : 1 Caractère : 12
+ set-content <<<<  -literalpath "u:\temp\test.txt" -Value "coucou"
    + CategoryInfo          : ObjectNotFound: (\\server\shar...e\temp\test.txt:String) [Set-Content], DirectoryNotFo
   undException
    + FullyQualifiedErrorId : GetContentWriterDirectoryNotFoundError,Microsoft.PowerShell.Commands.SetContentCommand
接下来的工作就开始了

Set-Content -Path "\\server\share\temp\test.txt" -Value "coucou"
set-content -path '\\server\share\temp\`[test`].txt' -Value "coucou"
set-content -literalpath "u:\temp\[test].txt" -Value "coucou"
转向解决方案2


我认为解释是,在
-literalpath
中,UNC的支持较差

方括号的通配符似乎只在cmdlet的-path参数中实现。fileinfo对象的默认方法仍然将它们视为文本:

 $fic = [io.directoryinfo]"\\server\share\temp\[test].txt"

这是奇怪的,它应该工作,但我可以复制您的问题以及有趣的。我无法复制此内容。我很好奇-为什么需要使用-LiteralPath开关?@zdan运行脚本的计算机和承载网络共享的计算机都在运行哪个操作系统?@Goyuix“LiteralPath”是必需的,因为我正在处理的文件的文件名中有方括号,我无法更改。在我的测试中,即使没有带方括号的文件,UNC名称在-literalPath参数中也不受支持,请看一看。PS C:\testfiles>get item-literalPath“\\localhost\C$\testfiles\test[4].txt”目录:\\localhost\c$\testfiles Mode LastWriteTime长度名称-----a---5/8/2011 10:35 AM 12测试[4]。txt PS c:\testfiles>尝试设置内容以创建具有UNC名称的新文件非常感谢。我相信通过你的代码,我可以让我的脚本正常工作。再次感谢!