Question:
This is the problem I’m having:
1 2 3 4 5 6 |
# 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" |
I have already checked my permissions and I definitely have permission to write to the network share. The problem only happens when I use the “LiteralPath” parameter, which, unfortunately, is required for what I’m doing.
How can I write data to a UNC path that contains square brackets?
Answer:
you will find on Microsoft web site an explanation about strange behaviours of ‘sqare brackets‘ in PowerShell expressions.
BUT
When I just write the following (without brackets) it just does’t work for me :
1 2 |
Set-Content -LiteralPath "\\server\share\temp\test.txt" -Value "coucou" |
but (according to Microsoft article) the following works
1 2 3 |
Set-Content -Path "\\server\share\temp\test.txt" -Value "coucou" set-content -path '\\server\share\temp`[test`].txt' -Value "coucou" |
I tried to solve this trouble with PowerShell Drive
1 2 |
New-PSDrive -Name u -PSProvider filesystem -Root "\\server\share" |
And it was even worst
1 2 3 4 5 6 7 |
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 |
Turn arround solution 1 :
I solve it using :
1 2 3 |
net use u: \\server\share set-content -literalpath "u:\temp\test.txt" -Value "coucou" |
And then the followwing works
1 2 |
set-content -literalpath "u:\temp\[test].txt" -Value "coucou" |
Turn arround solution 2 : using FileInfo
1 2 3 4 5 6 7 8 9 10 11 |
# 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() |
I think that the explanation is that in -literalpath
UNC are poorly supported