【问题标题】:How I can use a Powershell Script for copy data from position A to position B?如何使用 Powershell 脚本将数据从位置 A 复制到位置 B?
【发布时间】:2015-03-02 10:14:20
【问题描述】:
我想使用 Powershell 脚本将文件夹递归复制到其他位置。这必须是 Powershell 要做的事情:
- 将文件和文件夹从位置 A 复制到位置 B
- UNC 路径必须有(例如 \net.local\Files\EDV)
- 位置 B 必须全部清空文件夹
- 位置B的结构必须等于位置A
- 应在 B 上创建缺少的文件夹。
- 它应该只复制超过 180 天的文件
- 脚本必须创建一个日志文件,其中包含有关文件名和路径、文件大小、文件日期的信息
我从这个脚本开始:
$a = '\\serverA\folderA'
$b = '\\serverB\folderB'
#This copies the files
Get-ChildItem $a -Recurse -File | Foreach_Object {Copy-Item $_ -Destination $b}
#Removes empty files
Get-ChildItem $b -File | Foreach-Object {IF($_.Length -eq 0) {Remove-Item $_}}
我需要帮助..
【问题讨论】:
标签:
powershell
unc
get-childitem
copy-item
【解决方案1】:
这段代码将一个目录复制到另一个目录,其余的应该是直截了当的。在$toreplace 中,每个反斜杠都应使用额外的反斜杠进行转义。
$a = [System.IO.DirectoryInfo]'C:\Users\oudou\Desktop\dir'
$b = [System.IO.DirectoryInfo]'C:\Users\oudou\Desktop\dir_copy'
function recursive($a,$b)
{
foreach ($item in @(Get-ChildItem $a.FullName))
{
if($item -is [System.IO.DirectoryInfo])
{
if ( -not (Test-Path $item.FullName.Replace($a.FullName,$b.FullName)))
{
New-Item -ItemType Directory $item.FullName.Replace($a.FullName,$b.FullName)
}
$dest = Get-ChildItem $item.FullName.Replace($a.FullName,$b.FullName)
$dest
recursive($item, $dest)
}
else
{
[string]$y = $item.FullName
$toreplace = "C:\\Users\\oudou\\Desktop\\dir"
$replace = "C:\Users\oudou\Desktop\dir_copy"
$y -replace $toreplace , $replace
Copy-Item $item.FullName ($item.FullName -replace $toreplace , $replace)
}
}
}
recursive $a $b