windows - Remove-Item 不删除文件

标签 windows powershell windows-10 delete-file

这是我的 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 中输入原始对象,它将自动绑定(bind)到 -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

关于windows - Remove-Item 不删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44635205/

相关文章:

MySQL InnoDB 插入性能 (Windows)

windows - 如何从 LLVM ir 创建可执行文件?

来自 Powershell 和 Windows 编码的 MysqlDump

c - Win10破解了printf函数

python - 无法在 Windows 10 上 pip 安装 mysqlclient 或 cython 或 lxml

windows - Windows 上的自更新 Exe par

windows - 如何通过批处理文件在 Windows 防火墙上打开端口

powershell - move 带有文件的文件夹(异常(exception))

powershell - 如何将 Invoke-Expression 的输出通过管道传输到字符串?

visual-studio - Visual Studio 2015 RC 卡在电话模拟器安装中