work.acct0929
work.acct0929

Reputation: 1

Powershell: foreach loop giving incorrect output

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

Upvotes: 0

Views: 142

Answers (1)

RetiredGeek
RetiredGeek

Reputation: 3168

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.PartitionStyle) 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.

Upvotes: 1

Related Questions