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  Rob Jaudon 3 years, 1 month ago.

  • Author
  • #25466

    Rob Jaudon


    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.

  • #25469

    Rob Simmers

    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 {
        $printers = Get-WmiObject -class Win32_printer -Filter "Name Like '%foo%'" | Select Name
        Sleep -Seconds 5
    }while($printers -eq $null)

    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
    }while($printers -or $attempts -ne 5)
    • #25539

      Rob Jaudon


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


  • #25471

    Wilfredo Perez

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

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

You must be logged in to reply to this topic.