I need to add a (relatively) small pause between two sets of code because the second half needs to have the first half executed successfully prior to running -- but PowerShell sometimes gets a little ahead of itself and proceeds before the previous command completed entirely.
Just for context, this is the code I'm working with:
Initialize-Disk -PassThru -PartitionStyle GPT -Confirm:$false `
| New-Partition -DriveLetter D -UseMaximumSize
Often this fails because the drive isn't completely initialized by the time PowerShell executes the New-Partition
.
Typically I'd use something like:
Initialize-Disk -PassThru -PartitionStyle GPT -Confirm:$false
Start-Sleep -Seconds 2
New-Partition -DriveLetter D -UseMaximumSize
However the problem is that the output object of Initialize-Disk
is lost and New-Partition
doesn't get an input object.
I tried putting the Start-Sleep
in the pipeline:
Initialize-Disk -PassThru -PartitionStyle GPT -Confirm:$false `
| Start-Sleep -Seconds 2 `
| New-Partition -DriveLetter D -UseMaximumSize
...but it throws an exception as Start-Sleep
doesn't know how to make sense of the input object (which is fair enough).
Start-Sleep : The input object cannot be bound to any parameters for the command either because the command does not take pipeline
input or the input and its properties do not match any of the parameters that take pipeline input.
At C:\Users\Administrator\Desktop\test.ps1:104 char:87
+ ... nfirm:$false | Start-Sleep -Seconds 2 `
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (MSFT_Disk (Obje...11E2-93F2-0...):PSObject) [Start-Sleep], ParameterBindingException
+ FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.StartSleepCommand
tl;dr: How can I add a pause in my code whilst keeping the output object of the preceding cmdlet?
Using the PowerShell Start Sleep cmdlet You can also write Start-Sleep 5 to let the script sleep for 5 seconds. But for the readability of your script is it better to define the -s or -seconds parameter. The only other parameter besides seconds is milliseconds.
The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.
The Wait-Process cmdlet waits for one or more running processes to be stopped before accepting input. In the PowerShell console, this cmdlet suppresses the command prompt until the processes are stopped. You can specify a process by process name or process ID (PID), or pipe a process object to Wait-Process .
You can try using background job:
Initialize-Disk -PassThru -PartitionStyle GPT -Confirm:$false -asjob |
wait-job | receive-job | New-Partition -DriveLetter D -UseMaximumSize
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With