我正在寻找将计划脚本的成功或失败写入csv文件的最简单方法。我不是在寻找一种方法来记录错误或失败的原因,只是一个简单的"成功/失败"。由于这个原因,我不想修复/log非终止错误。
我认为把每个脚本放到
最简单的方法try {
Write-Host "test"
}
catch{
Code to write to csv here
}
Catch部分写入csv文件的块。是否有更好/更简单的方法来做这件事,或者这是正确的方法?
继续我的评论…
老实说,这真的取决于情况,也就是说,你想要完成的是什么。那么,让我们编一个场景,向计算机查询一些基本信息:
Function Get-SystemInfo {
Param (
[Parameter(Mandatory=$false,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[string[]]$ComputerName = $env:COMPUTERNAME
)
Begin {
$ErrorActionPreference = 'SilentlyContinue'
}
Process {
foreach ($Computer in $ComputerName)
{
try {
# attempt cim session with -EA Stop to not allow it to go
# any further and we can calculate the results.
$CIMSession = New-CimSession -ComputerName $Computer -ErrorAction Stop
$Status = $true
# Perform the actual queries
$CS = Get-CimInstance -ClassName Win32_COmputerSystem -CimSession $CIMSession
$BS = Get-CimInstance -ClassName Win32_BIOS -CimSession $CIMSession
# evaluate against the returned objects
$UserName = if ($CS.UserName -eq $null) { 'No User Logged in' } else { $CS.UserName }
$Manufacturer = if ($CS.Manufacturer -eq $null) { 'N/a' } else { $CS.Manufacturer }
$Model = if ($CS.Model -eq $null) { 'N/a' } else { $CS.Model }
$SerialNumber = if ($BS.SerialNumber -eq $null) { 'N/a' } else { $BS.SerialNumber }
}
catch {
# Set the variables to $null
$Status = $false
$UserName = $null
$Manufacturer = $null
$Model = $null
$SerialNumber = $null
}
finally {
# Output the filled variables
[PSCustomObject] @{
ComputerName = $Computer
Connected = $Status
UserLoggedIn = $UserName
Manufacturer = $Manufacturer
Model = $Model
SerialNumber = $SerialNumber
}
}
}
}
End {
# cleanup
# some people argue this should be in the finally block
# to disconnect any machine, but looking at this from both
# sides, they both have pros/cons.
Get-CimSession | Remove-CimSession
}
}
…这个快速功能最大的缺点是-ErrorAction Stop
在尝试创建CIM会话时出错。这就是看大局发挥作用的地方。如果您无法连接到计算机,为什么还要继续呢?这包括从一个快速ping得到一个回显回复,因为这并不意味着你可以仅仅因为得到一个回复就连接到远程PC。
其余的是if
和else
语句,它们处理轻工作,对返回的对象求值,以便对输出进行更多的控制。
结果将是:
PS C:UsersAbraham> Get-SystemInfo
ComputerName : OER
Connected : True
UserLoggedIn : Abraham
Manufacturer : LENOVO
Model : 22251
SerialNumber : 55555555
PS C:UsersAbraham> Get-SystemInfo -ComputerName BogusComputerName
ComputerName : BogusComputerName
Connected : False
UserLoggedIn :
Manufacturer :
Model :
SerialNumber :