Aid*_*ido 1 windows powershell delete-file windows-10
这是我的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)
}
Run Code Online (Sandbox Code Playgroud)
回声提供实际的文件名,但Test-Path解析为False,并且没有删除任何内容.
因为您的路径包含]由-Path参数(您隐式使用)作为模式的一部分解释的路径.
您应该使用-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)
}
Run Code Online (Sandbox Code Playgroud)
请注意,如果您改为使用原始对象进行管道传输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)
}
Run Code Online (Sandbox Code Playgroud)
为了证明这一点:
$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
Run Code Online (Sandbox Code Playgroud)