【发布时间】:2021-06-04 22:53:11
【问题描述】:
谁能告诉我,我怎样才能产生错误并在日志文件中捕获它?因为我想测试这个脚本的错误视角但无法得到它,如果你能告诉我如何手动测试这个脚本的错误视角,这将非常有帮助。
让我向您描述一下我通过这个脚本实现了什么。因为我想使用文件命名约定将文件移动到服务器上的各个文件夹并备份到现有文件(如果有的话),并且在整个过程以 CSV 格式生成日志文件并发送带有成功或错误消息的电子邮件。
$Source = 'c:\uploadtool\' # Source Location
$RetailSource = 'Retail P&C Sales Intelligence\*'
$GroupSource = 'Group P&C Sales Intelligence\*'
$UATSource = 'UAT\*'
$RetailDest = 'D:\ToolUpload\Retail-EIP' # 1st Destination Location
$GroupDest = 'D:\ToolUpload\Group-EIP' # 2nd Destination location
$UATDest ='D:\ToolUpload\UAT' # Added 3rd destination location in this version 1.7.2V
$ArchiveData = 'D:\Backup\backup_{0:yyyyMMddHHmm}' -f (Get-Date)
$LogFolder = 'D:\logs'
# because of your wish to get a Table-style log, use CSV format you can open in Excel
$LogFile = 'D:\logs\uploadlog_{0:yyyyMMdd}.csv'-f (Get-Date)
$Sourcetest = Test-Path -Path '$RetailSource','$GroupSource' -PathType Leaf
#Email Params:
$EmailParams = @{
SmtpServer ='xyz.smtp.com'
Port = '25'
Subject ='File Upload Status'
To ="xyz@xyz.com"
From ="no-xyz@xyz.com"
}
# make sure the output LogFolder exist
# by adding the -Force switch there is no need to use Test-Path first, because if
# the folder already exists, the cmdlet will return the DirectoryInfo of that,
# otherwise it will create a new folder. Since we don't want output, we use $null = ..
$null = New-Item -Path $LogFolder -ItemType Directory -Force
# loop through the files in the source folder and collect the outputted objects
$result =
Get-ChildItem -Path "$Source" -Include '*Group-EIP*', '*Retail-EIP*','*UAT*' -File -Force -Recurse |
ForEach-Object {
Write-Host "Processing file '$($_.FullName)'"
# create an object with (for now) 3 empty properties
$out = $_ |
Select-Object @{Name = 'Date'; Expression = {(Get-Date)}},
@{Name = 'Source'; Expression = {$_.FullName}},
@{Name = 'FileSize'; Expression = {$_.Length}},
Destination, # depends on the file name
@{Name = 'Archive'; Expression = {$ArchiveData}}, # initialize to Not Applicable
Result
# depending on its name, get the correct destination folder
$destFolder = if($_.Name -match "Retail-EIP") { $RetailDest } elseif($_.Name -match "Group-EIP") { $GroupDest } else {$UATDest}
# create the backup destination folder if it didn't already exist
# the first file in column 'Source' is now responsible for creating the backup folder
$null = New-Item -Path $destFolder -ItemType Directory -Force
# get the full path and filename for the destination
$existingFile = Join-Path -Path $destFolder -ChildPath $_.Name
# add the destination folder to the output object
$out.Destination = $destFolder
try
{ # if a file with that name already exists in the destination, move it to the Archive folder
if (Test-Path -Path $existingFile -PathType Leaf) {
# create the Archive folder if it didn't already exist
$null = New-Item -Path $ArchiveData -ItemType Directory -Force
Move-Item -Path $existingFile -Destination $ArchiveData -ErrorAction Stop
# add the archived file to the output object
$out.Archive = $existingFile
Write-Host "File '$existingFile' has been backed-up to '$ArchiveData'"
}
# next move the file from the source folder to its destination (either $RetailDest or $GroupDest)
$_ | Move-Item -Destination $destFolder -ErrorAction Stop
$out.Result = 'OK'
Write-Host "File '$($_.FullName)' has been moved to '$destFolder'"
$Body = " The File '$($_.FullName)' has been moved to '$destFolder' 'n Size of the file is '$($_.Length)' `n file has been backed up on the location '$ArchiveData' "
}
catch
{ # ouch.. something went horribly wrong on a Move-Item action
$Body = " Error occured trying to move the file '$($_.FullName)' to '$destFolder. `n$($_.Exception.Message)"
Write-Warning "An error occurred: $_.Exception.Message"
$out.Result = "Error: $($_.Exception.Message)" | Add-Content -Path $LogFile -Force
}
Send-MailMessage @EmailParams -Body $Body
# output the object so it gets collected in variable $result
$out
}
# now you can save the results as structured CSV file to open in Excel
$result | Export-Csv -Path $LogFile -UseCulture -NoTypeInformation -Append -Force
# and display on the screen using Out-GridView as the data will probably be too wide for Format-Table
$result | Out-GridView -Title 'Backup results'
【问题讨论】:
-
嗨 Boxdog,谢谢你在这里的建议,如果可能的话,我实际上从未使用过 Pester,你能推荐一些相同的学习材料吗?
标签: powershell