Powershell将文件从源复制到目标,但保持文件夹结构 [英] Powershell copy a file from source to target but maintain folder structure

查看:113
本文介绍了Powershell将文件从源复制到目标,但保持文件夹结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何提出一个Powershell脚本,该脚本可以将文件从位置A复制到位置B,并创建新文件夹并维护子目录结构

How can I come up with a powershell script that can copy a file from a location A to location B and create new folder and maintain the sub directory structure

伪代码

$newFolder = "PackageName"
$maintainFolderStructureFrom ="Website"
$FileToCopy = "File.ascx"

Copy-Item "C:\A\B\Website\SubFolder1\SubFolder2\SubFolder3\"+$FileToCopy "C:\Client\Packages\$newFolder" -Container -Recurse

现在,它应该这样创建目标

Now it should create the target as such

C:\Client\Packages\PackageName\SubFolder1\SubFolder2\SubFolder3\File.ascx

基于@jisaak答案的代码

Code based on @jisaak answer

$newFolder = "NewFolderName"
$FileToCopy="File.ascx"                                                                                                
$pathToCopy = Join-Path 'C:\A\B\Website\SubFolder1\SubFolder2\SubFolder3\' $FileToCopy     
$destination = Join-Path 'C:\Client\Packages\' $newFolder                                                        
mkdir $destination -ErrorAction SilentlyContinue                                                                                      
Copy-Item $pathToCopy $destination  

此代码未创建文件夹结构,我希望使用此参数$ maintainFolderStructureFrom = Website

This code is not creating folder structure, I want the folder structure to be created user this param $maintainFolderStructureFrom ="Website"

推荐答案

从@jisaak&的一些答案中获取帮助@FoxDeploy,我可以满足我的需要。

taking help of few answers from @jisaak & @FoxDeploy, I could accomplish what I need.

function CreatePackage($sourcePath, $fileSelectorToCopy, $packageName) {

$maintainStructionFrom = "Website"

$files = Get-ChildItem $sourcePath | Where-Object {$_.Name -match $fileSelectorToCopy}

$files | ForEach-Object { 
    $newFolder = $packageName
    $fileSelectorToCopy = $_.Name 
    $pathToCopy = Join-Path $sourcePath  $fileSelectorToCopy                                                                                         
    $newFolder = $newFolder+'\'+$pathToCopy.Substring($pathToCopy.IndexOf($maintainStructionFrom),$pathToCopy.Length - $pathToCopy.IndexOf($maintainStructionFrom)).Replace($fileSelectorToCopy,'') 
    $destination = Join-Path 'C:\Client\Packages\' $newFolder  
    mkdir $destination -ErrorAction SilentlyContinue                                                                                      
    Copy-Item $pathToCopy ($destination+$FileToCopy)
}
}

然后将其称为

CreatePackage -packageName 'MyNewPackage' -fileSelectorToCopy 'FileNameLike.*' -sourcePath 'C:\A\B\Website\SubFolder1\SubFolder2\SubFolder3\'

这篇关于Powershell将文件从源复制到目标,但保持文件夹结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆