Saturday, March 23, 2013

Do Until Example

If your like me, Do until can dive you nuts.  Why? Becuase its the opposite of what you think the logic should be.  Here's an example.

$mos = new-object System.Management.ManagementObjectSearcher("Select * From Win32_Process")
$mos.Scope.Path.NamespacePath = "root\cimv2"
$mos.Scope.Path.Classname = "Win32_Process"
[System.Management.ManagementObjectCollection]$moc = $mos.Get()
$mocEnum = $moc.GetEnumerator()
$iret = $mocEnum.MoveNext()
do{
    [System.Management.ManagementBaseObject]$mo = $mocEnum.Current
    [System.Management.PropertyDataCollection]$propset = $mo.Properties
    $propEnum = $propset.GetEnumerator()
    $iret = $propEnum.MoveNext()
    do{
         [System.Management.PropertyData] $prop = $propEnum.Current
         [System.String]$s = $prop.Name
         write-host $s.PadRight(30, " ") : $prop.Value   
    }
    until($propEnum.MoveNext() -eq $False)
    write-host
}

until($mocEnum.MoveNext() -eq $False)

The MoveNext returns true until there is nothing left to enumerate through. So what is being said here is while MoveNext equals true allow the routine to loop. Here's the same thing with Do While:

$mos = new-object System.Management.ManagementObjectSearcher("Select * From Win32_Process")
$mos.Scope.Path.NamespacePath = "root\cimv2"
[System.Management.ManagementObjectCollection]$moc = $mos.Get()
$mocEnum = $moc.GetEnumerator()
$iret = $mocEnum.MoveNext()
do{
[System.Management.ManagementBaseObject]$mo = $mocEnum.Current
[System.Management.PropertyDataCollection]$propset = $mo.Properties
$propEnum = $propset.GetEnumerator()
$iret = $propEnum.MoveNext()
do{
[System.Management.PropertyData] $prop = $propEnum.Current
[System.String]$s = $prop.Name
write-host $s.PadRight(30, " ") : $prop.Value
}
    while($propEnum.MoveNext())
    write-host
}

while($mocEnum.MoveNext() )


No comments:

Post a Comment