LIFO & FIFO with Powershell

In this Post i will explain how we can Use Stack’s & Queue’s in Powershell.
It is nothing specail but sometimes very helpfull to know !

  • Last in First out (LIFO)
LIFO is nothing more than a stack.
An example of a stack would be the back button in many programs. The previouse value we watched will be restored. 

Commands :

Microsoft Documentation about the Stack Class

https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack?view=net-5.0

  • PUSH
  • POP
  • PEEK
  • CLEAR
  • COUNT

$PS_STACK = New-Object System.Collections.Stack

# Add some items to our PS_STACK 

for($i= 0; $i -lt 10 ; $i++)
{

$PS_STACK.Push($i)  # Push add a item to the stack  

}

$PS_STACK.Peek() # Displays the last Item in the Stack

<#
Output : 9
#>


$PS_STACK.Pop() #Pop removes the last Item in the Stack
$PS_STACK.Peek() # Displays the last Item in the Stack
<#
Output : 8
#>

$PS_STACK.Count #Get count of elements in the Stack


if($PS_STACK.Count -eq 0)
{ 
    Write-Output "Stack is empty"
}
else 
{
    Write-Output "Stack is not empty"
}

# Output : Stack is not empty


# Now clear the Stack and Prove if empty

$PS_STACK.Clear()

if($PS_STACK.Count -eq 0){
    
    Write-Output "Stack is empty"
}
else {
    Write-Output "Stack is not empty"
}

#Output : Stack is empty

First in First out (FIFO)

Something that has happened to each of us. You get stuck in a traffic jam and can only continue when the person in front of you has driven away.

FIFO

Commands:

MS Documentaion About the Queue Class
https://docs.microsoft.com/en-us/dotnet/api/system.collections.queue?view=net-5.0

  • Enqueue
  • Dequeue
  • Peek
  • Count
  • Contaions
  • Clear
####FIFO   First in First Out ---> Queue


$Queue = New-Object System.Collections.Queue            


for($i= 0; $i -lt 10 ; $i++)
{
    $Queue.Enqueue($i) #Enqueue add a element to the Queue
}     

#Output: 0 1 2 3 4 5 6 7 8 9

$Queue.Peek()  # Output the First Element in the Queue          

#Output : 0 

$Queue.Dequeue() # Output and Remove the First Element in the Queue            

#Removed :  0

$Queue.Peek()  # Output the First Element in the Queue   

#Output : 1

$Queue.Count # Get Count of Elements in the Queue            
                  
$Queue.Contains(3) # Prove if the queue contains a specific value 

#Output: True

$Queue.Clear() # Clears the Queue




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: