Remove-Item 不删除文件

Remove-Item not deleting files

这是我的 PowerShell 脚本:

$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)
}

回声给出了实际的文件名,但 Test-Path 解析为 False,并且没有任何内容被删除。

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

您应该改用 -LiteralPath 参数:

$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)
}

请注意,如果您改为从 Get-ChildItem 中输入原始对象,它将 自动绑定到 -LiteralPath,因此需要考虑这一点:

$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)
}

证明这一点:

$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