[英]Powershell - Copy directory and files from source folder to destination folder
I am working out a scenario using PowerShell.我正在使用 PowerShell 制定一个方案。
As of now, I am trying to workout a scenario where I have a batch job which upon successful execution first creates a date folder for that particular day and then creates a .CSV file under.截至目前,我正在尝试解决一个场景,其中我有一个批处理作业,该作业在成功执行后首先为该特定日期创建一个日期文件夹,然后在其下创建一个 .CSV 文件。 The folder structure than look like below.
文件夹结构如下所示。
\\\\Server\\SourceA\\Processed\\20200120\\TestA.CSV
when the job runs next day, it will create another folder and file like below.当作业在第二天运行时,它将创建另一个文件夹和文件,如下所示。
\\\\Server\\SourceA\\Processed\\20200121\\TestB.CSV
This is how there have been so many folders already created in past.这就是过去已经创建了这么多文件夹的方式。
My PS script is good to run daily after the batch job is completed.批处理作业完成后,我的 PS 脚本可以每天运行。 I read a date, append to path and it copies file from source to destination folder.
我读取了一个日期,附加到路径并将文件从源文件夹复制到目标文件夹。 But I want to enable my PS script to read all previous date folders created under
但我想让我的 PS 脚本读取在下创建的所有以前的日期文件夹
\\\\Server\\SourceA\\Processed\\
Another tricky part is - under the date folder there is few other sub folders.另一个棘手的部分是 - 在日期文件夹下几乎没有其他子文件夹。 Ie
IE
\\Server\SourceA\Processed\20191010\Log
\\Server\SourceA\Processed\20191010\Charlie
\\Server\SourceA\Processed\20191010\Alpha
\\Server\SourceA\Processed\20191010\Delta
among them, I only need to read files from Log
folder only.其中,我只需要从
Log
文件夹中读取文件。 Hence, my actual source path becomes like因此,我的实际源路径变得像
\\\\Server\\SourceA\\Processed\\20191010\\Log\\TestA.CSV
Here is my script (which is static right now and unable to read past existing date folders).这是我的脚本(现在是静态的,无法读取过去的现有日期文件夹)。
$fullSourceFileName = "\\Server\SourceA\Processed\"
$date = Get-Date -format "yyyyMMdd"
$fullSourceFileName = "$($fullSourceFileName)$($date)\Log
$destination = "\\Server\DestA\Processed\"
$destination = "$($destination)$($date)\"
get-childitem -path $fullSourceFileName -recurse | copy-item -destination "$($destinationFolder)$($date)\"
Your help is highly appreciated.非常感谢您的帮助。
I did not know I can use foreach loop in Powershell.我不知道我可以在 Powershell 中使用 foreach 循环。 So, here is the answer to read all dynamic date folder under my given path.
因此,这是读取给定路径下所有动态日期文件夹的答案。 I hope this helps the community.
我希望这对社区有所帮助。
$fullSourceFileName = "\\Server\SourceA\Processed\"
$DirToRead = "\Log\"
$dates = Get-ChildItem -Path $fullSourceFileName -Directory
$destination = "\\Server\DestA\Processed\"
foreach ($date in $dates){
$ActualPath = "$($fullSourceFileName)$($date)$($DirToRead)"
if(!(Test-Path $ActualPath))
{
Write-Output $($ActualPath)$(" source path does not exist")
}
else
{
get-childitem -path $ActualPath -recurse | copy-item -destination "$($destinationFolder)$($date)\"
}
$ActualPath = ""
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.