Search code examples
powershellget-childitemcopy-item

Powershell search subfolders for specific folder and copy


I'm trying to write a powershell scripts to search a folder and its subfolders for a specific folder from a csv file and then copy that folder elsewhere.

[CmdletBinding()]
Param(
    [Parameter(Mandatory=$True,Position=1)]
    [string]$filePath,
    [Parameter(Mandatory=$True,Position=2)]
    [string]$InstanceName
)

Import-CSV -Delim ',' -Path $filePath  | ForEach-Object {
    Get-ChildItem -Path D:\Folder\$InstanceName -Directory -Recurse
    Copy-Item $_.FOLDERNAME d:\CopyFolder\$InstanceName -recurse
}

That seems to run forever and obviously errors a lot because the files aren't there when it tries to copy. Is there a way to just use Copy-Item if I don't know the specific path? OR some other alternative way to go about this?


Solution

  • A couple of things:

    • You can use the -filter parameter to search for the particular folder
    • Pipe the results of your get-childitem so that it only tries to do a copy-item when it finds a folder
    • Use the FullName property when using the -recurse parameter on get-childitem to ensure the full path to the item is always used

      Import-CSV -Delim ',' -Path $filePath  | ForEach-Object {
          Get-ChildItem -Path D:\Folder\$InstanceName -Recurse -Directory -Filter $_.FOLDERNAME | ForEach-Object {
              Copy-Item $_.FullName d:\CopyFolder\$InstanceName -Recurse
          }
      }