Home > Net >  How to set current directory to a file's location through a foreach loop
How to set current directory to a file's location through a foreach loop

Time:04-20

I have been trying to find a way to set my current working directory to a parent folder of a file so that I can copy a PDF that lives in a folder above a particular folder.

Basically what I am trying to do is this; Check which folders on a share have been modified in the last day Recursively search through those modified folders for a clxml file that contains a word I need Set my current location to that path, browse back a folder and copy out any PDF's to a new location.

So far I have everything working except I can't figure out how to set my current directory to the location of the clxml within the foreach loop. I can't figure out what needs to go between the final Get-ChildItem and my copy-item

$ClxmlFolder = Get-ChildItem "\\clwsdrapsi02\BATCH STORAGE\" -Directory| Where-Object {$_.LastWriteTime -ge ((Get-Date).Date) -and $_.LastWriteTime -lt ((Get-Date).Date).AddDays( 1)}

$ClxmlPath = Get-ChildItem $ClxmlFolder.FullName -Recurse -Directory -Include 'clxml' | Select-Object -Property FullName, Directory

foreach ($Folder in $ClxmlPath)
{
  $ClxmlPath.FullName
  break
}

foreach ($File in $ClxmlPath)
{
  $ClxmlFile = Get-ChildItem $ClxmlPath.FullName -Recurse -Filter "*.clxml" | Where-Object {Select-String Newton $_ -Quiet} | Select-Object -Property Fullname, Directory
  $ClxmlFile.Fullname
  Copy-Item .\*.PDF -destination "C:\test uploads\Uploaded" -Recurse -Force
  Break
}

CodePudding user response:

By using Select-Object -Property Fullname, Directory you're converting a FileInfo object into a PSCustomObject which in this case, you do not want. We can get the parent folder of a file (a FileInfo object) by calling it's .Directory property and furthermore, this would return a DirectoryInfo object which has a .Parent property.

Summarizing, first you can do your filtering:

$ClxmlFile = Get-ChildItem $ClxmlPath.FullName -Recurse -Filter "*.clxml" |
    Where-Object { Select-String Newton $_ -Quiet }

And then, assuming this only returns one file, you can either Set-Location or if you want to change directory to the parent folder and then go back, you can use Push-Location and Pop-Location.

if($ClxmlFile) { # if the above filtering returned a result
    Set-Location $ClxmlFile.Directory
    # rest of the logic here
}

If you want to change directory to the parent's parent directory:

Set-Location $ClxmlFile.Directory.Parent

Alternatively, instead of changing your current directory, you could simple combine the FullName of the Parent folder with \*.PDF:

$source = $ClxmlFile.Directory.FullName   '\*.PDF'
Copy-Item $source -Destination "C:\test uploads\Uploaded" -Recurse -Force
  • Related