0

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?

Shawn
  • 2,356
  • 6
  • 48
  • 82

1 Answers1

0

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
        }
    }
    
Cole9350
  • 5,444
  • 2
  • 34
  • 50
  • I want to copy the folder and the items in it, not the file. That is why I should use recurse correct? – Shawn May 07 '14 at 15:27
  • @Shawn Yes sorry, updated answer.. Your CSV column header of FILENAME contains the names of folders? That's a little misleading – Cole9350 May 07 '14 at 15:37