1

I'm trying to write a script which when ran, will detect an external drive I've added and then Initialize, Parition and then format it. The safety mechanism will be the 'FriendlyName' of the disk, which is the same for all disks I use. I usually bulk do this, so need to script it to save time.

I've come up with the following four lines:

1: Clear-Disk -FriendlyName 'ST3000DM 2CS' -RemoveData -Confirm:$false    
2: Initialize-Disk -FriendlyName 'ST3000DM 2CS' -PartitionStyle MBR
3: New-Partition -DiskNumber 1 -UseMaximumSize -AssignDriveLetter
4: Format-Volume -DriveLetter F -Confirm:$false

The "FriendlyName" can be seen when you run 'Get-Disk'

Cutting and pasting these is fine, the job gets done.

Two problems:

1) Lines 3 and 4 refer to a hardcoded DiskNumber and DriveLetter. DiskNumber is assigned after execution of line 2. DriveLetter is then assigned on execution of line 3. I want lines 3 and 4 to be more failsafe and want line 3 to execute New-Partition specifically on the outcome of line 2 (i.e. dependant on disk number assigned), and line 4 to execute Format-Volume based on the outcome of line 3 (i.e. dependant on drive letter assigned).

2) I want to stick all of this into a ps1 script for easy double click to run action.

Can you help?

ASR
  • 1,801
  • 5
  • 25
  • 33

1 Answers1

0

Initialize-Disk has a switch parameter -PassThru which, when specified, causes it to output an object of type MSFT_Disk which has a Number member. You could use it like this:

$disk = Initialize-Disk -FriendlyName 'ST3000DM 2CS' -PartitionStyle MBR -PassThru
New-Partition -DiskNumber $disk.Number -UseMaximumSize -AssignDriveLetter

However, New-Partition accepts as input a MSFT_Disk object, so you can just pipe the output of Initialize-Disk into New-Partition:

Initialize-Disk -FriendlyName 'ST3000DM 2CS' -PartitionStyle MBR -PassThru | New-Partition -UseMaximumSize -AssignDriveLetter

Similarly, the output of New-Partition can be piped directly into Format-Volume, so your whole script looks like this:

Clear-Disk -FriendlyName 'ST3000DM 2CS' -RemoveData -Confirm:$false    
Initialize-Disk -FriendlyName 'ST3000DM 2CS' -PartitionStyle MBR -PassThru | New-Partition -UseMaximumSize -AssignDriveLetter | Format-Volume -Confirm:$false

Just put that in a ps1 file and you're good to go.

zdan
  • 28,667
  • 7
  • 60
  • 71
  • sir you are a king, thank you! Thanks for the extensive breakdown - top man. – Amitrus Singhal Jun 30 '17 at 09:30
  • ps. I do get the dreaded; "Access to a CIM resource was not available to the client" when double clicking script. How can I elevate to administrator privilege to prevent this from happening? – Amitrus Singhal Jun 30 '17 at 09:55
  • You can add a little blurb to prompt for elevation at start of script. See https://stackoverflow.com/questions/7690994/powershell-running-a-command-as-administrator – zdan Jun 30 '17 at 16:45