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

Ric*_*ick 7 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" -Value "This is a test"
Run Code Online (Sandbox Code Playgroud)

我已经检查了我的权限,我肯定有权写入网络共享.问题只发生在我使用"LiteralPath"参数时,遗憾的是,这是我正在做的事情所必需的.

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

JPB*_*anc 6

您将在Microsoft网站上找到有关PowerShell表达式中" sqare括号 "的奇怪行为的说明.

当我写下面的内容(没有括号)时,它对我不起作用:

Set-Content -LiteralPath "\\server\share\temp\test.txt" -Value "coucou"
Run Code Online (Sandbox Code Playgroud)

但是(根据微软的文章)以下工作

Set-Content -Path "\\server\share\temp\test.txt" -Value "coucou"
set-content -path '\\server\share\temp\`[test`].txt' -Value "coucou"
Run Code Online (Sandbox Code Playgroud)

我试图用PowerShell Drive解决这个问题

New-PSDrive -Name u -PSProvider filesystem -Root "\\server\share"
Run Code Online (Sandbox Code Playgroud)

这甚至是最糟糕的

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
Run Code Online (Sandbox Code Playgroud)

转动解决方案1: 我使用以下方法解决它:

net use u: \\server\share
set-content -literalpath "u:\temp\test.txt" -Value "coucou"
Run Code Online (Sandbox Code Playgroud)

然后跟随工作

set-content -literalpath "u:\temp\[test].txt" -Value "coucou"
Run Code Online (Sandbox Code Playgroud)

转动arround解决方案2:使用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()
Run Code Online (Sandbox Code Playgroud)

我认为解释是在-literalpathUNC得到了很少的支持