简体   繁体   中英

Remove-Item not deleting files

This is my PowerShell script:

$dir = ([io.fileinfo]$MyInvocation.MyCommand.Definition).DirectoryName

Get-ChildItem -Path .\ -Filter *.png -Recurse -File | Where-Object {$_.Name -match ".+[\]]+.png"} | ForEach-Object {
    echo $_.FullName $(Test-Path $_.FullName)
    Remove-Item $_
    echo $_.FullName $(Test-Path $_.FullName)
}

The echos give actual filenames, but Test-Path resolves to False and nothing is ever deleted.

Because your paths contain ] which is interpreted by the -Path parameter (which you're using implicitly) as part of a pattern.

You should use the -LiteralPath parameter instead:

$dir = ([io.fileinfo]$MyInvocation.MyCommand.Definition).DirectoryName

Get-ChildItem -Path .\ -Filter *.png -Recurse -File | Where-Object {$_.Name -match ".+[\]]+.png"} | ForEach-Object {
    echo $_.FullName $(Test-Path -LiteralPath $_.FullName)
    Remove-Item -LiteralPath $_
    echo $_.FullName $(Test-Path -LiteralPath $_.FullName)
}

Note that if you instead piped in the original object from Get-ChildItem , it would automatically bind to -LiteralPath so that's something to consider:

$dir = ([io.fileinfo]$MyInvocation.MyCommand.Definition).DirectoryName

Get-ChildItem -Path .\ -Filter *.png -Recurse -File | Where-Object {$_.Name -match ".+[\]]+.png"} | ForEach-Object {
    echo $_.FullName $($_ | Test-Path)
    $_ | Remove-Item
    echo $_.FullName $($_ | Test-Path)
}

To prove this:

$dir = ([io.fileinfo]$MyInvocation.MyCommand.Definition).DirectoryName

$fileSample = Get-ChildItem -Path .\ -Filter *.png -Recurse -File | 
    Where-Object {$_.Name -match ".+[\]]+.png"} | 
    Select-Object -First 1


Trace-Command -Name ParameterBinding -Expression { 
    $fileSample.FullName | Test-Path 
} -PSHost  # $fileSample.FullName is a string, still binds to Path

Trace-Command -Name ParameterBinding -Expression { 
    $fileSample | Test-Path 
} -PSHost  # binds to LiteralPath

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