简体   繁体   中英

Powershell escape special characters in variable

I'm trying to perform a Copy-Item on a series of files and I'm noticing that files containing [ and ] that are not being copied, however I'm not receiving any error.

I'm using the following function:

function fsync ($source,$target) {

    $sourceFiles = @(Get-ChildItem -Path $source -Recurse | select -expand FullName)

    foreach ($f in $sourceFiles) {
        $destFile = $f.Replace($source,$target)
        $exist = Test-Path $destFile

        if ($exist -eq $false) {
            Write-Host "Copying: " $f "to: " $destFile
            Copy-Item -Path "$f" -Destination "$destFile"
        } else {
            Write-Host "File: " $f "Already exists"
        }
    }
}

Every time it's run it will print Copying: C:\Users\jesse_b\tmp\foo[1].txt to: C:\Users\jesse_b\tmp\test\foo[1].txt , and display no error, but the file never actually copies.

I've tried double quoting the variable names but it didn't make a difference.

When I manually copy files with [ and ] in them on the terminal it works as long as those characters are escaped. Is there something I must to do to have my variables treated as literal strings?

I'm trying to perform a Copy-Item on a series of files and I'm noticing that files containing [ and ] that are not being copied, however I'm not receiving any error.

I'm using the following function:

function fsync ($source,$target) {

    $sourceFiles = @(Get-ChildItem -Path $source -Recurse | select -expand FullName)

    foreach ($f in $sourceFiles) {
        $destFile = $f.Replace($source,$target)
        $exist = Test-Path $destFile

        if ($exist -eq $false) {
            Write-Host "Copying: " $f "to: " $destFile
            Copy-Item -Path "$f" -Destination "$destFile"
        } else {
            Write-Host "File: " $f "Already exists"
        }
    }
}

Every time it's run it will print Copying: C:\Users\jesse_b\tmp\foo[1].txt to: C:\Users\jesse_b\tmp\test\foo[1].txt , and display no error, but the file never actually copies.

I've tried double quoting the variable names but it didn't make a difference.

When I manually copy files with [ and ] in them on the terminal it works as long as those characters are escaped. Is there something I must to do to have my variables treated as literal strings?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM