Author Posts

May 20, 2015 at 9:31 am


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.

May 20, 2015 at 10:12 am

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)


May 20, 2015 at 10:24 am

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)

May 21, 2015 at 9:46 am


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