删除,项目不能删除文件

问题描述:

这是我的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) 
} 

的回声,给实际的文件名,但测试的路径解析为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 
+0

哦,这是有道理的!非常感谢。它现在有效! –