我正在使用 powershell 调用 c# 脚本。我尝试从不同的服务器复制日志,
foreach($server in $args)
{
$destination = "\\$server\$path"
if(!(Test-Path $destination))
{
New-Item -ItemType directory -Path $destination
}
foreach($log in $logsTaskAgent)
{
Write-Host "Backup $log log $server"
$filename = "{0}{1}_{2}_{3}.evt" -f $destination,$server,$log,$date
Write-Host "Filename: $filename"
if($password -and $userName)
{
$logFile = Get-WmiObject Win32_NTEventlogFile -ComputerName $server -Credential $credential -ErrorAction SilentlyContinue | where-object { $_.logfilename -eq $log }
Write-Output "continue"
if($logFile)
{
$logFile.PSBase.Scope.Options.EnablePrivileges = $true
$logFile.backupeventlog($filename)
}
else
{
Write-Output "Error on server: $server for log: $log"
}
}
}
这很完美,但是当凭证出现问题时,它会抛出异常,但我想继续,因为我说过,我有很多服务器,所以我只想忽略异常并继续使用其他服务器,知道哪里出了问题吗?据我所知 -ErrorAction Silentlycontinue 应该可以解决问题,但事实并非如此 :(
编辑:修复
我最终得到了与 Johan de Haan 的答案非常相似的答案,所以我将其作为答案......这里是修改后的代码:
foreach($server in $args)
{
try
{
$destination = "\\$server\$path"
if(!(Test-Path $destination))
{
New-Item -ItemType directory -Path $destination
}
foreach($log in $logsTaskAgent)
{
Write-Host "Backup $log log $server"
$filename = "{0}{1}_{2}_{3}.evt" -f $destination,$server,$log,$date
Write-Host "Filename: $filename"
if($password -and $userName)
{
$logFile = Get-WmiObject Win32_NTEventlogFile -ComputerName $server -Credential $credential -ErrorAction SilentlyContinue | where-object { $_.logfilename -eq $log }
Write-Output "continue"
if($logFile)
{
$logFile.PSBase.Scope.Options.EnablePrivileges = $true
$logFile.backupeventlog($filename)
}
else
{
Write-Output "Error on server: $server for log: $log"
}
}
}
}
catch
{
Write-Output "Error while retrieving log Object from server $server : $($_.Exception.Message)"
continue
}
$destination = ""
}
答案1
我将使用 try/catch 并使用 break 来继续下一个服务器:
foreach($server in $args){
$destination = "\\$server\$path"
if(!(Test-Path $destination))
{
New-Item -ItemType directory -Path $destination
}
foreach($log in $logsTaskAgent)
{
Write-Host "Backup $log log $server"
$filename = "{0}{1}_{2}_{3}.evt" -f $destination,$server,$log,$date
Write-Host "Filename: $filename"
if($password -and $userName) {
try{
$logFile = Get-WmiObject Win32_NTEventlogFile -ComputerName $server -Credential $credential -ErrorAction Stop | where-object { $_.logfilename -eq $log }
} catch {
Write-Warning "Error while retrieving WMI Object: $($_.Exception.Message)"
break #this way you break out of the first loop, continuing in the foreach ($server in args loop)
}
Write-Output "continue"
if($logFile) {
$logFile.PSBase.Scope.Options.EnablePrivileges = $true
$logFile.backupeventlog($filename)
} else {
Write-Output "Error on server: $server for log: $log"
}
}
}
}