简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM