Powershell Problems with Character [

Asked

Viewed 49 times

2

Good afternoon, I’m using the following script on powershell to copy files from one folder to another:

Function CopyFiles
{
    Param ($folderSource, $folderDestiny)
    
    $allFilesSource = Get-ChildItem -Path $folderSource
    $allFilesDestiny = Get-ChildItem -Path $folderDestiny

    for ($i = 0; $i -lt $allFilesSource.Count; $i++) 
    {
        $curFileName = $allFilesSource[$i].Name
        $fileExist = "$folderDestiny\$curFileName"
        
        for ($j = 0; $j -lt $allFilesDestiny.Count; $j++)
        {               
            if (-not(Test-Path -path $fileExist))
            {                
                Copy-Item $allFilesSource[$i].FullName $folderDestiny
            }            
        }        
    }
}

CopyFiles 'c:\PastaOrigem' 'D:\PastaDestino'

The problem is that in the folder Grassland there are files with the character "[" and these files script don’t copy, someone can help me?

1 answer

2

The solution is to use the parameter -LiteralPath in place of -Path.

Documentation can be found here.

-Literalpath

Specifies a path to one or more Locations. The value of Literalpath is used Exactly as it’s typed. No characters are Interpreted as wildcards. If the path includes escape characters, enclose it in single quotation Marks. Single quotation Marks Tell Powershell not to interpret any characters as escape sequences.

I made some changes to your function so that it works properly.

Function CopyFiles
{
    Param ($folderSource, $folderDestiny)
    
    Get-ChildItem -Path $folderSource | % {
        
        $curFileName = $_.Name
        $curFullFileName = $_.FullName

        Get-Item -Path $folderDestiny | Where { -not (Test-Path -LiteralPath "$_\$curFileName") } | % {
            Copy-Item -LiteralPath $curFullFileName "$_.\$curFileName"
        }
    }
}

CopyFiles 'c:\PastaOrigem' 'D:\PastaDestino'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.