Mat*_*Moo 7 powershell try-catch get-eventlog
我正在尝试将离线计算机记录在文本文件中,以便我可以在以后再次运行它们.似乎没有记录或陷入捕获.
function Get-ComputerNameChange {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)]
[string[]]$computername,
[string]$logfile = 'C:\PowerShell\offline.txt'
)
PROCESS {
Foreach($computer in $computername) {
$continue = $true
try { Test-Connection -computername $computer -Quiet -Count 1 -ErrorAction stop
} catch [System.Net.NetworkInformation.PingException]
{
$continue = $false
$computer | Out-File $logfile
}
}
if($continue){
Get-EventLog -LogName System -ComputerName $computer | Where-Object {$_.EventID -eq 6011} |
select machinename, Time, EventID, Message }}}
Run Code Online (Sandbox Code Playgroud)
try
用于catch
处理异常。您正在使用-Quiet
开关,因此Test-Connection
返回$true
or $false
,并且throw
在连接失败时不会出现异常。
作为替代方案,您可以执行以下操作:
if (Test-Connection -computername $computer -Quiet -Count 1) {
# succeeded do stuff
} else {
# failed, log or whatever
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11694 次 |
最近记录: |