Noob to PowerShell, copying files within folder

非 Y 不嫁゛ 提交于 2019-12-11 03:12:29

问题


Sorry if this is a really simple process.

I've got a folder structure with ~4,000 directories at root level (empty), and another location with another set of folders with data.

I want to copy only the files from within the folders in location2 to the folders within location1 ie \FolderABC123\Archive, but only if the directory names match. I'm sure windows explorer copy, or xcopy or some other utility can do it with more ease, but I'd like to get my head into PowerShell, and think this would be a good start?

thank you. Chris


回答1:


    # Fist, get a list of all target directories (i.e.: directories under $destination that have a match in $source)

    $targetDirs = dir -Path $source -Recurse -Force |
        ?{ $_.psIsContainer } |
        %{ $_.FullName -replace [regex]::Escape($source), $destination } |
        %{ if (Test-Path $_) { $_ }}

    # Then, enumerate all files from source and copy them only if the corresponding target dir exists

    dir -Path $source -Recurse -Force | 
        ?{ -not $_.psIsContainer } |
        ?{ Test-Path (Split-Path ($_.FullName -replace [regex]::Escape($source), $destination) -Parent) } |
        copy -Force -Destination { $_.FullName -replace [regex]::Escape($source), $destination }



回答2:


You can use powershell.
Set the path in the beginning.

$strSouce = "Path"
$strDestination = "Path"

Then search foreach file in the source.

Foreach ($objFile in Get-ChildItem -Path $strSouce -Recurse | Where-Object -FilterScript {$_.PsIsCointainer -eq $false}) {]

Copy every item from the source to the destination. For the destination you have to replace the source path to the destiantion path.

Copy-Item -Path $objFile.FullName -Destination $objFile.FullName.Replace("$strSouce", "$strDestination")


For your learning, set the snippet to the correct place.



来源:https://stackoverflow.com/questions/25542608/noob-to-powershell-copying-files-within-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!