运行powershell脚本时出错

时间:2015-08-30 11:55:12

标签: powershell

我想从所有子文件夹中删除给定路径后的bak文件,因此所有带有扩展名.bak的重复文件都将被删除,我在脚本下面运行但是收到错误。

$filePath = "d:\Test\"

$Afiles = Get-ChildItem -Recurse -Path $filePath | Where-Object {$_.Extension -eq ".bak"}
$Bfiles = Get-ChildItem -Recurse -Path $filePath | Where-Object {$_.Extension -eq ".7z"}

$Alist = @()
$Blist = @()

foreach( $A in $Afiles) {
    $Alist += $A.baseName
}

foreach( $B in $Bfiles) {
    $Blist += $B.baseName
}

foreach($A in $Alist) {
    if($Blist -contains $a) 
    {
        rm ("$A.bak") 
    }
}

我收到以下错误:

Remove-Item : Cannot find path 'C:\Users\******\Desktop\master_backup_2015_08_21_013722_8370267.bak' because it does not exist.
At C:\Users\*****\Desktop\duplicatedelete1.ps1:26 char:10
+        rm <<<<  ("$A.bak") 
    + CategoryInfo          : ObjectNotFound: (C:\Users\****....722_8370267.bak:String) [Remove-Item], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand

1 个答案:

答案 0 :(得分:0)

您收到错误是因为您未指定rm命令的完整路径,而PowerShell尝试删除当前目录中的文件。

试试这个:

$Path = 'D:\Test'

Get-ChildItem -Path $Path -Recurse -Filter '*.7z' | ForEach-Object {
    $BackupFile = Join-Path -Path (Split-Path $_.FullName -Parent) -ChildPath ($_.BaseName + '.bak')
    if(Test-Path -Path $BackupFile){
        Remove-Item -Path $BackupFile
    }
}