2017-06-19 179 views
1

這是我的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,並沒有什麼徹底刪除。

回答

4

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

哦,這是有道理的!非常感謝。它現在有效! –