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

7
这是我遇到的问题:
# 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路径写入数据?


很奇怪,它应该可以工作,但我也无法复制你的问题。 - ProfessionalAmateur
有趣。我无法复制这个。 - zdan
我很好奇 - 为什么需要使用-LiteralPath开关? - Goyuix
@zdan 你在运行脚本的计算机和托管网络共享的计算机上都使用哪个操作系统? - Rick
@Goyuix 需要使用"LiteralPath",因为我正在处理的文件名中有方括号,而我无法更改它们。 - Rick
2个回答

6
你可以在微软网站上找到有关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"

我尝试使用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

解决方案 1: 我使用以下方法解决了这个问题:

net use u: \\server\share
set-content -literalpath "u:\temp\test.txt" -Value "coucou"

然后是以下工作。
set-content -literalpath "u:\temp\[test].txt" -Value "coucou"

Turn arround solution 2 : using FileInfo

# Create the file
set-content -path '\\server\share\temp\`[test`].txt' -Value "coucou"
# Get a FileInfo
$fic = Get-Item '\\server\share\temp\`[test`].txt'
# Get a stream Writer
$sw = $fic.AppendText()
# Append what I need
$sw.WriteLine("test")
# Don't forget to close the stream writter
$sw.Close()

我认为解释在于,在-literalpath中,UNC支持不佳。

非常感谢。我相信有了你的代码,我可以让我的脚本正常工作。再次感谢! - Rick

0

方括号的通配符似乎只在 cmdlets 的 -path 参数中实现。文件信息对象的默认方法仍将它们视为文字。

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

在我的测试中,即使没有带方括号的文件,-literalPath 参数也不支持 UNC 名称,请您看一下,好吗? - JPBlanc
PS C:\testfiles> get-item -literalpath "\localhost\c$\testfiles\test[4].txt"目录: \\localhost\c$\testfiles模式 最后写入时间 长度 名称
-a--- 5/8/2011 10:35 AM 12 test[4].txtPS C:\testfiles>
- mjolinor
尝试使用 set-content 命令创建一个具有 UNC 名称的新文件。 - JPBlanc

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