Powershell: Sleeping Middle Tubing

I need to add a (relatively) small pause between the two sets of code, because the second half must successfully complete the first half before starting - but PowerShell sometimes is slightly ahead of itself and goes to the previous command completely completed.

For context only, 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 disk is not fully initialized by the time PowerShell is running New-Partition.

Normally I would 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 Initialize-Diskis lost and New-Partitiondoes not receive the input object.

I tried to put Start-Sleepin the pipeline:

Initialize-Disk -PassThru -PartitionStyle GPT -Confirm:$false `
      | Start-Sleep -Seconds 2 `
      | New-Partition -DriveLetter D -UseMaximumSize

... , Start-Sleep , ( ).

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: , ?

+5
4

:

Initialize-Disk -PassThru -PartitionStyle GPT -Confirm:$false -asjob |
wait-job | receive-job | New-Partition -DriveLetter D -UseMaximumSize
+6

():

Initialize-Disk -PassThru -PartitionStyle GPT -Confirm:$false |
    % { Start-Sleep -Seconds 2 | Out-Null; $_ } |
    New-Partition -DriveLetter D -UseMaximumSize
+2

If you want to sleep a given number of seconds for each element in the pipeline, you can use it ForEach-Objectas Graimer . If you want to sleep only in the specified number of seconds, regardless of the number of elements in the conveyor, you need to break the pipeline:

$disks = Initialize-Disk -PassThru -PartitionStyle GPT -Confirm:$false
sleep 2
$disks | New-Partition -DriveLetter D -UseMaximumSize
+1
source

This worked for me (similar to another answer):

New-Partition … | ForEach-Object { Start-Sleep -s 3; $_ | Format-Volume … }
0
source

All Articles