Elements may be removed from the stack using the Pop method:
$stack.Pop() # This returns Under the bridge
If the stack is empty and the Pop method is called, an error will be thrown, as shown here:
PS> $stack.Pop()
Exception calling "Pop" with "0" argument(s): "Stack empty."
At line:1 char:1
+ $stack.Pop()
+ ~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : InvalidOperationException
To avoid this, the Count property of the stack may be inspected, for example:
# Set-up the stack $stack = New-Object System.Collections.Generic.Stack[String] "Up the road", "Over the gate", "Under the bridge" | ForEach-Object { $stack.Push($_) } # Pop from the stack until the stack is empty while ($stack.Count -gt 0) { Write-Host $stack.Pop() }