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?

1 Answer 1

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
        }
    }
    
Sign up to request clarification or add additional context in comments.

2 Comments

I want to copy the folder and the items in it, not the file. That is why I should use recurse correct?
@Shawn Yes sorry, updated answer.. Your CSV column header of FILENAME contains the names of folders? That's a little misleading

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.