in reply to diskpart.exe and perl

Actually your subroutine is worthwhile if the thing you want to do in diskpart requires more than one line, for example to change drive letters.

Here's how I used it for a drive letter changing script:

&send_diskpart_command("select volume $VolNo\nremove letter=$OldLetter +\nassign letter=$NewLetter");

Works like a charm.

The send_diskpart_command subroutine does have a bug though - the textfile cleanup is inside a debug if-block so the textfile only gets cleaned up when debug is turned on. Easy to fix though.

Replies are listed 'Best First'.
Re^2: diskpart.exe and perl
by bigteks (Initiate) on Jul 29, 2010 at 12:52 UTC

    Here is my version that does drive letter changes. It has little error checking. Usage is:

    drivechange.pl x y

    where x is the current drive letter and y is the new drive letter. Here is the code:

    #! perl -sl use strict; my $Foundit = 0; my $Token = ""; my $Line = ""; my $VolNo = 0; my $VolLet = ""; my $Trash = ""; my $Vol = ""; my $Num = 0; my $Goal = uc($ARGV[0]); my $NewGoal = uc($ARGV[1]); # Find out all the drive letters my @vols = split "\n", `echo list volume | diskpart`; # Find out which volume corresponds to drive letter F foreach $Line (@vols){ next if(!defined($Line)); ($Token,$Num,$Vol,$Trash) = split(' ',$Line,4); if(($Token =~ /^Volume$/) && ($Vol =~ /^$Goal$/)){ $Foundit = 1; $VolLet = $Vol; $VolNo = $Num; } } if($Foundit == 1){ &send_diskpart_command("select volume $VolNo\nremove letter=$Goal\ +nassign letter=$NewGoal"); } else { print("Couldn't find Volume $Goal.\n"); } sub send_diskpart_command { my $debug = 0; my ($diskpart_command) = @_; if ($diskpart_command eq "") { print "\n***No command passed to the send_diskpart_command subrout +ine***\n" ; return ; } # diskpart.exe requires a textfile input # deleting the textfile if it already exists # then creating a new textfile with the diskpart_command my $file = "diskpart_cmd.txt"; if ($debug) { print "\nSearching for an existing copy of the text +file $file."; } if (unlink($file) == 1) { if ($debug) {print "\nThe file '$file' was found and deleted.";} } else { if ($debug) {print "\nThe file '$file' was not detected.";} } open (DPART, ">>$file") || die ("Could not open file. $!"); print DPART ($diskpart_command); if ( $debug ) { print "\nCreated file '$file'." ; } close (DPART); if ( $debug ) { print "\n\nSending $diskpart_command." ; } open ( FH , "diskpart /s diskpart_cmd.txt|" ) || die ("Could not o +pen file. $!"); if ($debug) { print "\nCommand '$diskpart_command' sent to the hos +t.\n"; } if ( $debug ) { print "\n"; } my @inFile = <FH> ; # read all at once into array foreach (@inFile) { if ( $debug ) { print $_."\t"; } } close (FH); if ($debug) # delete the textfile { if (unlink($file) == 1) { print "\n\nThe file '$file' was deleted successfully.\n"; } else { print "\n\nThe file '$file' was not deleted.\n"; } } }