powershell 备份文件脚本

由于项目需要改写备份文件的程序.

(原来的解决方案是用vb6 去遍历文件, 不吐槽了)


需求1: 检查每个文件的修改时间, 如果小于日期参数, 则备份(和删除);

需求2:保留被备份文件的目录结构。


linux下备份文件很简单, 可惜我们只有windows Server。


百度不到。

为了性能花了2小时写了个powershell 脚本...


话说MS的东西跟开源方案比起来基本上都是垃圾。


例如C#比java, windows server 比linux, powershell比bash等等...

1个xargs解决的东西我tmd写了个循环。

mdzz.


$scriptName = "archive.ps1";
if (!($args.count -eq 3)){
  write-host("Usage - " + $scriptName + " <> <> <>");
  exit -1;
}

$pathFrom = $args[0];
$pathTo = $args[1];
$dateBefore = [datetime]::ParseExact($args[2],"yyyy-MM-dd",$null);
write-host("source path is: " + $pathFrom);
write-host("destination path is: " + $pathTo);
write-host("archive files whose modified date is before: " + $dateBefore);

if (!((Test-path -path $pathFrom) -and (Test-path -path $pathTo))){
  write-host("source path or destination path is not existed!");
  exit -1;
}

$pathCopyTo = "";
$pathFromLen = $pathFrom.Length;
$LenGap = 0;
$LenGap2 = 0;

ls -r $pathFrom | ?{$_.LastWriteTime -lt $dateBefore } | Foreach-Object{
    $lenGap = $_.FullName.Length - $pathFromLen - $_.Name.Length - 1;
    $pathCopyTo =  $PathTo + $_.FullName.Substring($pathFromLen, $lenGap);

    write-host("copying " + $_.FullName + " to " + $pathCopyTo);
    if(!(Test-path -path $pathCopyTo)){
        write-host("creating folder " + $pathCopyTo );
        mkdir -Pa $pathCopyTo;
    }
    copy-item $_.FullName $pathCopyTo -Force;
}

exit 0;


你可能感兴趣的:(Shell)