我正在尝试将脱机计算机记录在文本文件中,以便以后可以再次运行它们。似乎没有被记录或捕获。
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 }}}
最佳答案
try
用于catch
异常(exception)。您正在使用-Quiet
开关,因此Test-Connection
返回$true
或$false
,并且在连接失败时不会throw
异常。
做就是了:
if (Test-Connection -computername $computer -Quiet -Count 1) {
# succeeded do stuff
} else {
# failed, log or whatever
}
关于通过测试连接进行Powershell尝试/捕获,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32637785/