2011-06-24 31 views
7

UNC路径这是我遇到的问题:我已经检查了我的权限,我肯定有写权限到网络共享的PowerShell:无法将数据写入到包含方括号

# 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路径?

+0

也就是说离奇,它应该工作,但是我可以复制你的问题,也是 – ProfessionalAmateur

+0

有趣。我无法复制这个。 – zdan

+0

我很好奇 - 为什么要使用-LiteralPath开关? – Goyuix

回答

6

你会发现在Microsoft web site关于'sqare括号'在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" 

然后是followwing工作

set-content -literalpath "u:\temp\[test].txt" -Value "coucou" 

打开角落找寻解决办法2using 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不善支持

+0

非常感谢。我确信用你的代码我可以让我的脚本工作。再次感谢! – Rick

0

方括号的通配符,似乎只有在的-Path参数来实现的cmdlet。 FileInfo对象的默认方法仍然认为他们的文字:

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

在我的测试中,即使没有带方括号的文件,UNC名称在-literalPath参数中也不受支持,请您看看吗? – JPBlanc

+0

PS C:\ testfiles> get-item -literalpath“\\ localhost \ c $ \ testfiles \ test [4]。TXT” 目录:\\本地主机\ C $ \ testfiles 模式LastWriteTime长度名称 ---- ------------- ------ ---- -a --- 5/8/2011 10:35 AM 12 test [4] .txt PS C:\ testfiles> – mjolinor

+0

尝试set-content创建一个带有UNC名称的新文件 – JPBlanc