Powershell脚本,用于在上次访问日期之前将文件移动到新服务器



我是Powershell的新手。我有80台服务器,我需要连接到它们,并在它们上远程运行Pshell脚本,以便在上次访问日期之前递归地在一个共享中查找文件,并将它们移动到另一个\server\share进行存档。我还需要保存文件创建、上次访问等时间戳。

我欢迎任何帮助

谢谢

在所有80台服务器上实际使用之前,您需要彻底测试

如果你想在这方面使用PowerShell,你可以在服务器上使用Invoke-Command添加管理员凭据,这样脚本既可以访问要移动的文件,也可以访问目标存档文件夹。

我建议使用ROBOCOPY来完成繁重的工作:

$servers = 'Server1', 'Server2', 'Server3'  # etcetera
$cred    = Get-Credential -Message "Please supply admin credentials for archiving"
$scriptBlock = {
$SourcePath = 'D:StuffToArchive'            # this is the LOCAL path on the server
$TargetPath = '\NewServerArchiveShare'     # this is the REMOTE path to where the files should be moved
$LogFile    = 'D:ArchivedFiles.txt'         # write a textfile with all fie fullnames that are archived
$DaysAgo    = 130
# from a cmd box, type 'robocopy /?' to see all possible switches you might want to use
# /MINAGE:days specifies the LastWriteTime
# /MINLAD:days specifies the LastAccessDate
robocopy $SourcePath $TargetPath /MOVE /MINLAD:$DaysAgo /COPYALL /E /FP /NP /XJ /XA:H /R:5 /W:5 /LOG+:$logFile
}
Invoke-Command -ComputerName $servers -ScriptBlock $scriptBlock -Credential $cred

如果你想只使用PowerShell完成所有操作,请尝试以下操作:

$servers = 'Server1', 'Server2', 'Server3'  # etcetera
$cred    = Get-Credential -Message "Please supply admin credentials for archiving"
$scriptBlock = {
$SourcePath = 'D:StuffToArchive'            # this is the LOCAL path on the server
$TargetPath = '\NewServerArchiveShare'     # this is the REMOTE path to where the files should be moved
$LogFile    = 'D:ArchivedFiles.txt'         # write a textfile with all fie fullnames that are archived
$refDate    = (Get-Date).AddDays(-130).Date  # the reference date set to midnight
# set the ErrorActionPreference to Stop, so exceptions are caught in the catch block
$OldErrorAction = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
# loop through the servers LOCAL path to find old files and move them to the remote archive
Get-ChildItem -Path $SourcePath -File -Recurse | 
Where-Object { $_.LastAccessTime -le $refDate } |
ForEach-Object {
try {
$target = Join-Path -Path $TargetPath -ChildPath $_.DirectoryName.Substring($SourcePath.Length)
# create the folder in the archive if not already exists
$null = New-Item -Path $target -ItemType Directory -Force
$_ | Move-Item -Destination $target -Force
Add-Content -Path $LogFile -Value "File '$($_.FullName)' moved to '$target'"
}
catch {
Add-Content -Path $LogFile -Value $_.Exception.Message
}
}
$ErrorActionPreference = $OldErrorAction
}
Invoke-Command -ComputerName $servers -ScriptBlock $scriptBlock -Credential $cred

最新更新