2011-06-24 37 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