2015-09-17 1 views
5

Sto cercando di registrare i computer offline in un file di testo in modo che possa essere eseguito di nuovo in un secondo momento. Non sembra che sia stato registrato o catturato.Powershell try/catch con test-connection

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 }}} 

risposta

3

try è per catch eccezioni Ing. Stai utilizzando lo switch -Quiet in modo che Test-Connection restituisca $true o $false e che non sia throw un'eccezione quando la connessione non riesce.

Basta fare:

if (Test-Connection -computername $computer -Quiet -Count 1) { 
    # succeeded do stuff 
} else { 
    # failed, log or whatever 
} 
+0

Sì che ha funzionato. Sapresti perché solo pipe nell'ultimo nome del computer nel mio file di testo? Sto cercando get-content "\\ test \ c $ \ powershell \ computers.txt" | get-computernameChange – MattMoo

+0

@ user3620584 come fai a sapere che è solo il piping nell'ultima? – briantist

+0

Come test inserisco 3 nomi di computer che non esistono e ne elenca solo l'ultimo nel file di registro. – MattMoo