powershell script question

This topic contains 2 replies, has 2 voices, and was last updated by  Narayanan Subramanian 4 years ago.

  • Author
    Posts
  • #11142

    Hi guys
    How do i run ps script in multiple domains
    Example
    $servers = Gc c:\servers.txt
    $cred1 = get-credential

    Foreach($server in $servers {
    Try { gwmi win32_timezone }
    Try { gwmi win32_timezone -credential $cred1}
    Catch{ write-host "whatever"
    }

    I get error saying try needs a catch block

  • #11145

    Dave Wyatt
    Moderator

    Each try statement needs its own catch block; you can't chain them together like that. You can, however, put multiple statements into a single Try block. If the first statement succeeds without producing a terminating error, the next one is executed, and so on (though that logic doesn't seem quite right for what you're doing; I would assume that you want to execute the second call to Get-WmiObject only if the first one failed. For that, you can put the second call into the first one's catch block.)

    On a side note, you're not actually using the $server variable in the calls to Get-WmiObject in that code, so they would all be executing locally. You'll also want to add "-ErrorAction Stop" to each of the calls to Get-WmiObject; this ensures that if they do produce any errors, they are treated as Terminating errors (which is the only thing a try/catch block will see, in PowerShell.)

    Try this:

    foreach ($server in $servers) {
        try {
            gwmi win32_timezone -ComputerName $server -ErrorAction Stop
        } catch {
            try {
                gwmi win32_timezone -credential $cred1 -ComputerName $server -ErrorAction Stop
            } catch {
                Write-Host "Whatever"
            }
        }
    }
    
  • #11486

    after reading about 15-20 times and troubleshooting, i understood this... thanks a lot Dave

You must be logged in to reply to this topic.