简体   繁体   中英

Powershell Copying files with varying folders in the path

Right up front apologies for my lack of knowledge with Powershell. Very new to the language . I need to copy some files located in a certain path to another similar path. For example:

C:\TEMP\Users\<username1>\Documents\<varyingfoldername>\*
C:\TEMP\Users\<username2>\Documents\<varyingfoldername>\*
C:\TEMP\Users\<username3>\Documents\<varyingfoldername>\*
C:\TEMP\Users\<username4>\Documents\<varyingfoldername>\*

etc....

to

C:\Files\Users\<username1>\Documents\<varyingfoldername>\*
C:\Files\Users\<username2>\Documents\<varyingfoldername>\*
C:\Files\Users\<username3>\Documents\<varyingfoldername>\*
C:\Files\Users\<username4>\Documents\<varyingfoldername>\*

etc....

So basically all files and directories from path one need to be copied to the second path for each one of the different paths. The only known constant is the first part of the path like C:\\TEMP\\Users...... and the first part of the destination like C:\\Files\\Users.....

I can get all the different paths and files by using:

gci C:\TEMP\[a-z]*\Documents\[a-z]*\ 

but I am not sure how to then pass what's found in the wildcards so I can use them when I do the copy. Any help would be appreciated here.

This should work:

Get-ChildItem "C:\TEMP\*\Documents\*" | ForEach-Object {
    $old = $_.FullName
    $new = $_.FullName.Replace("C:\TEMP\Users\","C:\Files\Users\")
    Move-Item $old $new
    }

For additional complexity in matching folder levels, something like this should work:

Get-ChildItem "C:\TEMP\*\Documents\*" -File | ForEach-Object {
    $old = $_.FullName

    $pathArray = $old.Split("\") # Splits the path into an array
    $new = [system.String]::Join("\", $pathArray[0..1]) # Creates a starting point, in this case C:\Temp
    $new += "\" + $pathArray[4] # Appends another folder level, you can change the index to match the folder you're after
    $new += "\" + $pathArray[6] # You can repeat this line to keep matching different folders

    Copy-Item -Recurse -Force $old $new
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM