我还在学习powershell -如果我在这个论坛上错误地提出了我的问题,我提前道歉。
我的同事帮我编写了一个powershell脚本来帮助归档日志文件。看起来我们已经按预期运行了,但是由于某些原因,我们的try/catch语句不能正常工作。具体来说,我们希望脚本避免将已经存在的文件移动到我们的目录中。我已经比较了这句话在其他脚本的工作,但我还没有能够排除什么问题可能是。
任何想法吗?到目前为止,脚本看起来是这样的:
#----- Script variables
# variables with static data
$logpath = "C:templog"
$logname = "log-archive-test"
$lognameext = ".log"
# the variables below will be dynamically set later in the script
$Outputstr = ""
$DateVar = ""
$Datestr = ""
$TimeStr = ""
$logTimeStr = ""
$logfiletxt = ""
#----- Get Date and Time
$FileDate = Get-Date -format yyyy-MM-dd
$Datestr = Get-Date -Format "MM/dd/yyyy"
$TimeStr = Get-Date -Format "HH:mm"
#----- Functions
# Write-File-Host - function to write to a log file and to console
function Write-File-Host
( [String] $FileHostOutputText,
[String] $FileHostOutputFile
)
{
Process
{
Write-Output $FileHostOutputText >> $FileHostOutputFile
}
End {Write-Host $FileHostOutputText}
}
#----------------------------------------- create log destination and filename
$OutputdatafilenameTimeStr = $TimeStr -replace ":", ""
#$Outputdatafilename = $sqlfile.SubString(0,$i) + " " + $FileDate + "T" + $OutputdatafilenameTimeStr + ".csv"
#$Outputdatatext = $AppOutDataDir + $Outputdatafilename
#$logTimeStr = $TimeStr -replace ":", ""
$logfiletxt = $logpath + $logname + "_" + $FileDate + "T" + $OutputdatafilenameTimeStr + $lognameext
function Format-YearMonth ([datetime]$date) {
# simply output a string like "2021_01"
return '{0:yyyy_MM}' -f $date
}
$sourcePath = 'C:UserstestDesktoplog'
$targetPath = 'C:UserstestDesktoplogArchive'
$thisMonth = Format-YearMonth (Get-Date)
#--------------------------------------------- Announce starting of Log Archiving
$Datestr = Get-Date -Format "MM/dd/yyyy"
$TimeStr = Get-Date -Format "HH:mm"
$Outputstr = $Datestr + " " + $TimeStr + ": ==================== Starting the Archiving of Log Files"
Write-File-Host $Outputstr $logfiletxt
Get-ChildItem -Path $sourcePath -File |
# filter out the files that have a LastWriteTime for this year and month
Where-Object {(Format-YearMonth $_.LastWriteTime) -ne $thisMonth } |
ForEach-Object {
# Set destination Path
$Directory = Join-Path -Path $targetPath -ChildPath (Format-YearMonth $_.LastWriteTime)
# Create directory if it doesn't exsist
#--------------------------------------------- Announce creation of directory if it doesn't exist
$Datestr = Get-Date -Format "MM/dd/yyyy"
$TimeStr = Get-Date -Format "HH:mm"
$Outputstr = $Datestr + " " + $TimeStr + ": ----------- Create directory $Directory if it doesn't exsist"
Write-File-Host $Outputstr $logfiletxt
if (!(Test-Path $Directory)) {
$null = New-Item $Directory -type Directory
}
Write-Host "Moving file '$($_.FullName)' to '$Directory'"
# Move File to new location
#--------------------------------------------- Announce moving of files to the Directory
$Datestr = Get-Date -Format "MM/dd/yyyy"
$TimeStr = Get-Date -Format "HH:mm"
$Outputstr = $Datestr + " " + $TimeStr + ": ----------- Moving file '$($_.FullName)' to '$Directory'"
Write-File-Host $Outputstr $logfiletxt
try { $_ | Move-Item -Destination $Directory }
catch { $Datestr = Get-Date -Format "MM/dd/yyyy"
$TimeStr = Get-Date -Format "HH:mm"
$Outputstr = $Datestr + " " + $TimeStr + ": ----------- File '$($_.FullName)' already exists in '$Directory'"
Write-File-Host $Outputstr $logfiletxt }
}
#------------------------------------------------- Announce end of Log Archiving
$Datestr = Get-Date -Format "MM/dd/yyyy"
$TimeStr = Get-Date -Format "HH:mm"
$Outputstr = $Datestr + " " + $TimeStr + ": ==================== Archiving completed."
Write-File-Host $Outputstr $logfiletxt
添加-ErrorAction Stop
或-EA Stop
到Move-Item
。否则,设置为默认的Continue
,即Print error to output and generate NO exception
。因此,如果没有异常,try
块没有什么可捕获的,代码也不会到达catch
块。
当-ErrorAction
设置为Stop
时,生成ActionPreferenceStopException
,触发try
块异常捕获机制。
或者,您可以使用总是生成异常的本机。net方法[System.IO.File]::Move(...)
。
ErrorActionPreference