Search code examples
powershellunc

PowerShell: Unable to write data to a UNC path that contains square brackets


This is the problem I'm having:

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


Solution

  • 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 :

    Set-Content -LiteralPath "\\server\share\temp\test.txt" -Value "coucou"
    

    but (according to Microsoft article) the following works

    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

    New-PSDrive -Name u -PSProvider filesystem -Root "\\server\share"
    

    And it was even worst

    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 :

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

    And then the followwing works

    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()
    

    I think that the explanation is that in -literalpath UNC are poorly supported