simple while true do cmd to run a wmi query every second

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of Rob Jaudon Rob Jaudon 1 year, 8 months ago.

  • Author
    Posts
  • #25466
    Profile photo of Rob Jaudon
    Rob Jaudon
    Participant

    All,

    I am confused on how to exactly run a while true loop. Essentially I would like to run this command repeatedly (every second) until I cancel it out.

    EX. – > get-WmiObject -class Win32_printer | select name"

    Something like this below

    while true ; do (get-WmiObject -class Win32_printer | select name) |start-sleep 5;done **** I know syntax and layout of this is wrong....I am thoroughly confused.

    Thanks for the help.
    Rob.

  • #25469
    Profile photo of Rob Simmers
    Rob Simmers
    Participant

    While is evaluating to see if something is true, if so it will continue to loop until it's false. Below I'm looking for a printer named Foo. When printers are returned, then the object will not be null, so "printers -eq $null" would be False and exit the loop.

    do {
        "Looping"
        $printers = Get-WmiObject -class Win32_printer -Filter "Name Like '%foo%'" | Select Name
        Sleep -Seconds 5
    
    }while($printers -eq $null)
    
    $printers
    

    With that said, be very careful doing a loop every second as you can bring a system to a grinding halt if you have a bad infinity loop. You should also put a timeout of some sort so that if you look for a printer for more than 20 seconds to exit the loop:

    $attempts = 1
    
    do {
        "Attempt {0}" -f $attempts
        $printers = Get-WmiObject -class Win32_printer -Filter "Name Like '%foo%'"| Select Name
        Sleep -Seconds 5
        $attempts++
    
    }while($printers -or $attempts -ne 5)
    
    $printers
    
    • #25539
      Profile photo of Rob Jaudon
      Rob Jaudon
      Participant

      Rob,

      Thank you for the info and examples. I will give these a try.

      Rob

  • #25471
    Profile photo of Wilfredo Perez
    Wilfredo Perez
    Participant

    Maybe something like this : You can change the $end variable

    $i = 0
    $end = 10
    $arr = 1..$end
    do
    { 
    Get-WmiObject -Class win32_Printer | select name
    $arr[$i]
    $i++
    } while ($i -lt $end)
    

You must be logged in to reply to this topic.