这是我的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)
}
echos提供实际的文件名,但Test-Path解析为False,并且不会删除任何内容。
答案 0 :(得分:5)
您应该使用-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