Cheries
Cheries

Reputation: 902

How to find a file and get the path using powershell?

I have some folder, the total of the folder is always different. Each folder has two file named as "ID" and "ID_DONE", for the file "ID_DONE" generate by other process. I want to remove file "ID" once "ID_DONE" generate to each folder. I tried this, but I can not remove the "ID" file if I have more than one folder to check. Anyone can help, please.

if(Test-Path -Path "$OpJob_Path\*\ID_DON"){
$Path_ID_DON = Get-ChildItem -Path "$OpJob_Path\*\ID_DON"
$Split = Split-Path -Path $Path_ID_DON
$Split
    if(Test-Path -Path "$Split\ID")
    {
        Write-Host "Remove"
        Remove-Item -Path "$Split\ID"

    }
    else{
        Write-Host "Not Found"
    }
}
else{
    Write-Host "Continue..........."
}

Upvotes: 2

Views: 1690

Answers (2)

Esperento57
Esperento57

Reputation: 17492

Something like this ?

Get-ChildItem "$OpJob_Path" -File -Filter "ID_DON" -Recurse | %{Remove-Item "$($_.DirectoryName)\ID" -ErrorAction SilentlyContinue}

Upvotes: 0

mklement0
mklement0

Reputation: 440431

Given that you're matching files across multiple directories with wildcard expression "$OpJob_Path\*\ID_DON", $Path_ID_DON will likely contain an array of files ([System.IO.FileSystem] items).

Therefore,

$Split = Split-Path -Path $Path_ID_DON

results in $Split containing an array of the parent-directory paths of the files stored in $Path_ID_DON.

If you want to remove a file named ID from all these directories, if present, use the following:

$Split | ForEach-Object { 
  $file = Join-Path $_ 'ID'
  if (Test-Path $file) { Remove-Item $file -WhatIf }
}

-WhatIf previews the operation. Remove it once you're sure it will do what you want.

Upvotes: 2

Related Questions