Home > Software design >  Powershell: foreach loop giving incorrect output
Powershell: foreach loop giving incorrect output

Time:12-03

New to scripting and powershell. Need help understanding where I went wrong here. Attempting to initialize or set a disk online testing output gives the same results no matter what the disks actual state is. with a script.

disk_stat.ps1
$hdisk =  get-disk | select number, partitionstyle
foreach ($object in $hdisk)
    {
      if ($object -ne 'MBR')
        {
         write-host = $object.number,$object.partitionstyle "Needs to be set ONLINE"
        exit
        }

     else
        {
        write-host = $object.number,$object.partitionstyle "Needs to be initialized"
        exit
        }
    
    }

from "get-disk | select number, partitionstyle" output =

number PartitionStyle
------ --------------
     0 MBR           
     1 RAW    

So my intended output should tell me which number/partition style is Raw, offlineetc..

Output: PS C:\Users\Administrator> C:\Temp\disk_stat.ps1 = 0 MBR Needs to be initialized

CodePudding user response:

You need to lose the Exit statements since you want it to process all disks on the machine, at least I'd assume so? You can also simplify the code by dropping the Select statement and the Write-Host as a string "" by itself implies this. Also, you need to Evaluate the object properties using the $() as shown.

Clear-Host
$hdisk =  get-disk 
foreach ($object in $hdisk) {

   if ($object -ne 'MBR') {
     "$($object.number) $($object.partitionstyle) Needs to be set ONLINE"
   }

   else {
     "$($object.number) $($object.partitionstyle) Needs to be initialized"
   }
    
 } #End Foreach

Sample Output:

0 GPT Needs to be set ONLINE
1 GPT Needs to be set ONLINE
2 GPT Needs to be set ONLINE

Note: I don't have any MBR disks on my machine.

  • Related