I am new to powershell and using it as a one off to help me extract some files I've collected during my experiments.
I have many data sets with nested subfolders of processed data. They all have a folder in the path called "VPP" and I want to extract only the files in this folder and copy them to a new location. I want to do this while preserving the existing directory structure, so the parent folders will all be empty but the directory structure will be preserved. I need it like this so that I can preserve the organisation of the data (since I identify datasets from the parent folder name at the top of the tree) and so that I can copy files back to the original folder at a later date and have them end up in the right place.
So far, I have adapted a script I found online:
$sourceDirectory = "F:\OneDrive - University of Edinburgh\PhD\Results\Campaign1_Part4\GustData"
$destDirectory = "C:\Users\Anjali\Desktop\test"
$keyword = "VPP"
$children = Get-ChildItem -Path $sourceDirectory -Recurse
foreach ($child in $children)
{
if ($child -match $keyword)
{
try
{
Copy-Item -Path "$($sourceDirectory)\$($child )" -Destination $destDirectory -Force -Recurse
}
catch [System.Exception]
{
Write-Output $_.Exception
}
}
}
The problem I have is that the $child variables are only the filename and do not have any of the intermediate subfolders. I want $child to be the file path starting from $sourceDirectory e.g. "dataset1\folderA\folderB\VPP\file1" but it's coming out "file1".
How do I retrieve the intermediate filepath?
This will copy the VPP directories to a new location while maintaining the directory structure.
When you are confident that the correct directories will be copied, remove the
-WhatIfswitch from theCopy-Itemcommand.Note, this code will remove all files under the destination directory before copying. This is to ensure that no stray. extraneous files are left lying around. You may want to change that.
You will need to change the first line specifying the source directory.
Show the contents of the destination directory with the following command.