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?
$child.FullName?$child.FullName.Substring($sourceDirectory.Length)or theResolve-Pathcommand.$sourceDirectoryagain to get the full path so you can copy it.. As aside, Get-ChildItem also returns DirectoryInfo objects, not just FileInfo objects unless you tell it what you want returned using parameter-Fileor-DirectoryCopy-Item -Path $child.FullNameinstead of trying to manually combine the source path with the stringified object$child. P.S. With this:if ($child -match $keyword)do you want to match the file Name with $keyword or should that be a match on the entire full path and filename? Since you're not specifying what property of$childto use, you are testing the stringified form Powershell uses on FileInfo objects, which happens to be the.Nameproperty$child, I made a mistake in the for loop and really confused myself. I would like the keyword to match folder names too i.e. for a folder called "VPP" copy all the files inside to the corresponding folder in the destination folder tree. The code inside the for loop is nowCopy-Item -Path $child.fullName -Destination "$($destDirectory)\$($child.fullName.substring($sourceDirectory.length))" -Force -Recurse