Can diskpart take command line parameters? Or can I fake them with powershell?

762 Views Asked by At

I understand I can use diskpart /s to script diskpart

select vdisk file=FILE_SUPPLIED_BY_COMMAND_LIME_PARAMETER
attach vdisk readonly
compact vdisk
detach vdisk
exit

And then run it with:

diskpart /s scriptname.txt /t 15

But can I add command lime parameters to diskpart? Eg so I can specify the VHDX file by the command line?

If that's not possible, faking command line parameters with a Powershell wrapper to make the diskpart script dynamically might also be an option.

1

There are 1 best solutions below

0
On BEST ANSWER

You can pipe to diskpart. I'd read the file and replace your values when the file contents are retrieved:

$diskPath = c:\disk.vhd
(Get-Content scriptname.txt) -replace 'FILE_SUPPLIED_BY_COMMAND_LIME_PARAMETER',$diskPath | diskpart 

You can use a string and bypass reading a file:

$diskPath = 'c:\disk.vhd'
@"
select vdisk file=$diskPath
attach vdisk readonly
compact vdisk
detach vdisk
"@ | diskpart

If you want to use parameters, then you will need a function or script block. Using a script block:

# scriptname.txt contents
@"
select vdisk file=$($args[0])
attach vdisk readonly
compact vdisk
detach vdisk
"@ | diskpart

# The string argument for Invoke(argument) is passed to args[0]
[Scriptblock]::Create((Get-Content scriptname.txt -Raw)).Invoke('file path') 

Using a function:

function Run-Diskpart {
    param($diskPath)

@"
select vdisk file=$diskPath
attach vdisk readonly
compact vdisk
detach vdisk
"@ | diskpart

}

Run-DiskPart 'c:\disk.vhd'