0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks you so much!!! I leaned a lot from that answer So I can use quotes instead of write-host I don't need to reference the var in the if statement Dropping the Select and statement referencing it as $object.property. Very helpfull. Thanks
I reread your comment and I did miss checking for partition style in the IF statement. It worked only because I didn't have any MBR disks in my machine! Sorry about that. Answer edited to reflect the proper IF statement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.