我正在使用PowerShell脚本,每5分钟自动将某些文件移动到远程服务器上。
日志始终嵌套在两个目录的深处。我不在乎那些目录。文件夹和文件都可以(但不总是)随机命名。在将文件穿梭到robocopy
之前,我已经使用本地temp目录完成了删除操作。
我还创建了一个新的事件日志源以进行故障排除。我可以在完成这项工作后将其削减。我相信我可以从Task Scheduler正确运行此程序(例如,使用参数C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
启动程序-WindowStyle Hidden -File "C:\PathToScript\ThisIsTheScript.ps1"
)。
这是自动化后的样子。
robocopy
到UNC名称的目标共享文件保留在临时日志目录中,不复制到目标服务器,并且任务计划程序永远不会完成-它仍在运行。但是,即使在Start-Job
行周围使用Wait-Job
和robocopy
,也会创建所有故障排除日志条目。
仅在手动运行时,第5步和第6步不会在计划时发生。为什么不复制文件,为什么在Task Scheduler中运行任务后任务无法完成?
# Source Variables
$LogSource = 'C:\Somewhat\Deeper\Directory\Log\Files\Dropped\Here'
$TempLogDir = 'C:\SomeFilesBrieflyHere'
# Destination variables
$DestHost = 'thisisthedestinationcomputername'
$DestShare = 'thisisthedestinationsharename$'
# Operating Variables
$Switches = @("/s", "/MOVE", "/zb", "/R:0", "/W:0", "/MT:8", "/NFL", "/NDL", "/NP", "/IS", "/IT")
$RoboDo = @("$TempLogDir","\\$DestHost\$DestShare","$Switches")
# Verify event log source exists and create it if it does not
if (-not ([System.Diagnostics.EventLog]::SourceExists("PowerShell Script"))) {
New-EventLog -LogName 'Application' -Source 'PowerShell Script'
Write-EventLog -LogName 'Application' -Source 'Powershell Script' -EventID 1 -EntryType Information -Message 'Created new Event Log: Application Source type: PowerShell Script'
}
# Write log for init
Write-EventLog -LogName 'Application' -Source 'Powershell Script' -EventID 1 -EntryType Information -Message 'The scheduled task to move logs to the log server has been triggered and will now execute.'
# Verify Local LogDir exists
if (!(Test-Path -Path $TempLogDir)) {
New-Item -ItemType directory -Path $TempLogDir
}
# De-nest logs to local log folder in preparation to move
Get-ChildItem -Path "$LogSource" | Get-ChildItem | Get-ChildItem | Move-Item -Destination "$TempLogDir" -Force
Write-EventLog -LogName 'Application' -Source 'Powershell Script' -EventID 1 -EntryType Information -Message "Files locally de-nested into $TempLogDir."
# Remove all empty directories with unicorn glitter
Get-ChildItem $LogSource -Recurse | Where {$_.PSIsContainer -and @(Get-ChildItem -LiteralPath:$_.FullName).Count -eq 0} | Remove-Item -Confirm:$false -Force
Get-ChildItem $TempLogDir -Recurse | Where {$_.PSIsContainer -and @(Get-ChildItem -LiteralPath:$_.FullName).Count -eq 0} | Remove-Item -Confirm:$false -Force
Write-EventLog -LogName 'Application' -Source 'Powershell Script' -EventID 1 -EntryType Information -Mes
# Begin Robocopy operation
robocopy $TempLogDir \\$DestHost\$DestShare $Switches
Write-EventLog -LogName 'Application' -Source 'Powershell Script' -EventID 1 -EntryType Information -Message "The scheduled task to move logs to the log server has been completed and the files were successfully copied to $DestHost."
答案 0 :(得分:0)
尝试将robocopy行更改为此:
& robocopy $TempLogDir \\$DestHost\$DestShare $Switches
问题可能是您的脚本在该行停止,抱怨robocopy不是cmdlet或函数,即使它在手动运行时也可以运行。