All posts by Thiyagu

How To Monitor a Folder changes using Powershell

In our environment, large numbers of users are working on a daily basis and it very difficult to track what file they have modified and which time. To handle this scenario, my team was requested to monitor a directory for any file changes and receive alerts of those changes when they trying to update/Delete/renamed/created in a specific location inside the service and this requirement made me create this post. In this post, we will discuss how to monitor changes in the folder including sub-files, and log in to the log text file.

STEP #1

To monitor a folder for new files in Windows with PowerShell, we can use a .NET class called FileSystemWatcher. This class is in the System.IO namespace and can be created with the New-Object cmdlet.

$filewatcher = New-Object System.IO.FileSystemWatcher

STEP #2

To monitoring a folder/all sub-folders we need to assign the IncludeSubdirectories property as true.

$filewatcher.IncludeSubdirectories = $true

STEP #3

Then you need to specify which folder you I’ll be monitoring and also set the EnableRaisingEvents property to $true. The component is set to watch for changes in the last write and last access time, the creation, deletion, or renaming of text files in the directory. It will not raise events unless you set EnableRaisingEvents to true.

$filewatcher.EnableRaisingEvents = $true

STEP #4

In below code we using built-in [$event] variable. This is a variable that will be present every time an event fires and contains information such as the file path and the type of event that fired. In this script block, we capturing all the events in the FileWatcher_log.txt while event is fired.

$writeaction = { $path = $Event.SourceEventArgs.FullPath
$changeType = $Event.SourceEventArgs.ChangeType
$logline = “$(Get-Date), $changeType, $path”
Add-content “C:\D_EMS Drive\Personal\LBLOG\FileWatcher_log.txt” -value $logline
}

STEP #5

Finally, we need to register for the events. To perform this you need to use the Register-ObjectEvent cmdlet and need to supply it the watcher object we created and type of action to monitor like “Created”,”Changed”,”Deleted”,”Renamed”. The Register-ObjectEvent cmdlet subscribes to events that are generated by .NET objects on the local computer or on a remote computer.

Register-ObjectEvent $filewatcher “Created” -Action $writeaction
Register-ObjectEvent $filewatcher “Changed” -Action $writeaction
Register-ObjectEvent $filewatcher “Deleted” -Action $writeaction
Register-ObjectEvent $filewatcher “Renamed” -Action $writeaction

After executing the script, it will start to monitor the folder and sub-items from the given path and log the details in the FileWatcher_log.txt file.

Full Example

### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
    $filewatcher = New-Object System.IO.FileSystemWatcher
    #Mention the folder to monitor
    $filewatcher.Path = "C:\D_EMS Drive\Personal\LBLOG\"
    $filewatcher.Filter = "*.*"
    #include subdirectories $true/$false
    $filewatcher.IncludeSubdirectories = $true
    $filewatcher.EnableRaisingEvents = $true  
### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
    $writeaction = { $path = $Event.SourceEventArgs.FullPath
                $changeType = $Event.SourceEventArgs.ChangeType
                $logline = "$(Get-Date), $changeType, $path"
                Add-content "C:\D_EMS Drive\Personal\LBLOG\FileWatcher_log.txt" -value $logline
              }    
### DECIDE WHICH EVENTS SHOULD BE WATCHED 
#The Register-ObjectEvent cmdlet subscribes to events that are generated by .NET objects on the local computer or on a remote computer.
#When the subscribed event is raised, it is added to the event queue in your session. To get events in the event queue, use the Get-Event cmdlet.
    Register-ObjectEvent $filewatcher "Created" -Action $writeaction
    Register-ObjectEvent $filewatcher "Changed" -Action $writeaction
    Register-ObjectEvent $filewatcher "Deleted" -Action $writeaction
    Register-ObjectEvent $filewatcher "Renamed" -Action $writeaction
    while ($true) {sleep 5}

OUTPUT:

What do you think?

I hope you have an idea of  Monitoring a Folder Using PowerShell Scripting with Powershell. I would like to have feedback from the readers of my post. Your valuable feedback, question, or comments about this article are always welcome.

How to encrypt and store Passwords securely in PowerShell

As a system Admin, managing automation scripts passwords in PowerShell is a tricky task. There is always risk that someone may find the password by simply taking your code from server or automation tool. To overcome this critical scenarios, in all our automation we have call for stored encrypted password somewhere and referencing it in a script for authentications.

In PowerShell you can store sensitive information on disk is through secure strings. Secure strings are just like they simple strings encrypted through the logged-in user’s certificate. Creating a secure string is very easy and simple by using the ConvertTo-SecureString command from the powershell and it will still reduce the risk by a significant amount depending on the method

Step 1: Create your encrypted password file.

Method 1: Using your login credential as password.

First you need a standalone .ps1 script to generate your password file with Encryption string. Here we are encrypting your credential as password. The following code will achieve this

#Set and encrypt credentials to file using default ConvertFrom-SecureString method
(get-credential).password | ConvertFrom-SecureString | set-content “C:\D_EMS Drive\Personal\LBLOG\Encrypted_password.txt”

After executing above script, you will get a prompt for the password, then input your credentials that you want to save. In our example an encrypted password file will be saved to “C:\passwords\password.txt”. 

After executing the above code,  the prompt window will popup for getting the user name and Password like above, and script will encrypt the same password in the text file as shown below.

Method 2: Encrypt password by input value

Let’s say if you having a password and that need to encrypt by asking as input then the below script will prompt for input via the Read-Host command using the AsSecureString parameter, which will obfuscate your input and return a secure string as shown below.

$securePassword = Read-host -AsSecureString | ConvertFrom-SecureString
$securePassword | Out-File -FilePath “C:\D_EMS Drive\Personal\LBLOG\Encrypted_password.txt”

After execution of the above script, you can able to look at that variable’s value, it’s clear your input is encrypted.  Then the encrypted password will be save to the text file.

Step 2: Use the Encrypted password in the powershell script to authenticate.

Now, how do we retrieve these credentials? Easy, if we ever need to retrieve these we include the following syntax in our scripts to provide the creds.
Then just pass $credential to whatever cmdlets need a pscredential to authenticate. If we look at what’s in the $credential variable we can see our username and its encrypted password.

Now you have a password with file name “Encrypted_password” stored securely on disk as encrypted format. At this point, if you need to retrieve it from the file. To do this, you can use Get-Content to read the file and then create a PSCredential object from the secure string.

$username = “SysAdmin”
$password = Get-Content “C:\D_EMS Drive\Personal\LBLOG\Encrypted_password.txt” | ConvertTo-SecureString
$credential = New-Object System.Management.Automation.PsCredential($username,$password)

 

What do you think?

I hope you have an idea of  How to encrypt and store credentials securely for use with automation scripts with Powershell. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.

How to Get average CPU usage of a computer in last x minute with Powershell

We got the requirement to monitor the performance for few minutes before starting the activity (CPU usage of a computer in last x minute ) in the PRODUCTION server and requested this to be automate instead of getting in to the server each time. The below same we have implemented in the our build Tool to make it automatic.

How to achieve?

We can achieve the above scenario by using the Get-Counter cmdlet in Powershell. It will gets performance counter data directly from the performance monitoring instrumentation in the Windows family of operating systems. Get-Counter gets performance data from a local computer or remote computers.

STEP 1: This below line will check the CPU usage of last 5 times with 1 second intervals. as shown below.

Get-counter -Counter “\Processor(_Total)\% Processor Time” -SampleInterval 1 -MaxSamples 5

STEP 2: Selecting the Counter Samples and calculating the Average of the CPU Usage.

select -ExpandProperty countersamples | select -ExpandProperty cookedvalue | Measure-Object -Average).average

 

Full Code

The following script will return the average CPU % over a period of 5 seconds with 5 samples averaged. The $_.CookedValue is a variable for the current object in the pipeline.

###################################################################################
#Project : How to Gets CPU performance counter data from local and remote computers.
#Developer : Thiyagu S (dotnet-helpers.com)
#Tools : PowerShell 5.1.15063.1155 
#E-Mail : mail2thiyaguji@gmail.com 
###################################################################################
#-SampleInterval: parameter to increase the interval between continuous samples,
#If the SampleInterval parameter isn't specified, Get-Counter uses a one-second interval.
#-MaxSamples : Specifies the number of samples to get from each specified performance counter
#If the MaxSamples parameter isn't specified, Get-Counter only gets one sample for each specified counter.
$CPUAveragePerformance = (GET-COUNTER -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 2 -MaxSamples 5 |select -ExpandProperty countersamples | select -ExpandProperty cookedvalue | Measure-Object -Average).average
Write-Host "Average of CPU usage (calculated with 5 Sample with interval of 2 sec) :" $CPUAveragePerformance

OUTPUT:

 

What do you think?

I hope you have an idea of  How to Get average CPU usage of a computer in last x minute with Powershell. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.

How to combine the elements of two arrays using Powershell

An array is a data structure that is designed to store a collection of items. The items can be the same type or different types. PowerShell (like most other languages) stay the same length once you create them. To combine two arrays, PowerShell creates a new array large enough to hold the contents of both arrays and then copies both arrays into the destination array.

If you plan to add and remove data from an array frequently, the System. Collections.ArrayList class provides a more dynamic alternative. In this post, we are going to discuss the different way of scenarios for combining the two Array and output with a single Array

Example 1:

If you want to join arrays in Powershell, especially if you don’t know if one or more of the objects you are joining are arrays or single objects, combine them with the addition ‘+’ operator and cast the first item as an array.

Remove-Variable -Name "fullName"
$firstName = @("Rakshu","Aadharsh","Aadhira")
$lastName = @("T.A","G.K","G.K")
$fullName = $lastName + $firstName
$fullName

OUTPUT:

Example 2:

If you like to join two arrays by fetching the elements from each array one by one and not have them combined or simply merged.

Remove-Variable -Name "Result"
$Result = @()
$firstName = @("Jon","Bob","Tom")
$lastName = @("Smith","Jones","White")
$MaxLength = [Math]::Max($firstName.Length, $lastName.Length)
for ($loop_index = 0; $loop_index -lt $MaxLength; $loop_index++)
{ 
    $Result+=$firstName[$loop_index]
    $Result+=$lastName[$loop_index]
}
$Result

OUTPUT:

Example 3:

In this example, you can see how to Combine Individual Items From Separate Arrays Into a Third Array. Below example, we having two arrays, one with a list of first names and a second with a list of last names. The third Array will have the result of combining the first name and the last name that reside at the same index position in their respective arrays into a third array (combine them and output them with column headers). Example as follows:

$firstName = @("Rakshu","Aadharsh","Aadhira")
$lastName = @("T.A","G.K","G.K","max","mike","Jen","raju")
[int]$max = $firstName.Count
if ([int]$lastName.count -gt [int]$firstName.count) { $max = $lastName.Count; }
$Results = for ( $i = 0; $i -lt $max; $i++)
{
    Write-Verbose "$($firstName[$i]),$($lastName[$i])"
    [PSCustomObject]@{
        FirstName = $firstName[$i]
        LastName = $lastName[$i]
    }
}

OUTPUT:

What do you think?

I hope you have an idea of How to join the elements of two arrays using Powershell. I would like to have feedback from the readers of my post. Your valuable feedback, question, or comments about this article are always welcome.

How to Use PowerShell to Detect Logins and Alert Through Email using SendGrid

From Microsoft MSDN, The Get-WinEvent data from event logs that are generated by the Windows Event Log technology introduced in Windows Vista.And, events in log files generated by Event Tracing for Windows (ETW).By default, Get-WinEvent returns event information in the order of newest to oldest.

Get-winevent : Gets events from event logs and event tracing log files on local and remote computers. The Get-WinEvent cmdlet uses the LogName parameter to specify the Windows PowerShell event log. The event objects are stored in the $Event variable.

This script reads the event log “Microsoft-Windows-TerminalServices-LocalSessionManager/Operational” from servers and outputs the human-readable results to Mail. The -MaxEvents 1 Specifies the maximum number of events that are returned. Enter an integer such as 100. The default is to return all the events in the logs or files.

#################################################################
#Project : How to Use PowerShell to Detect Logins and Alert Through Email using SendGrid
#Developer : Thiyagu S (dotnet-helpers.com)
#Tools : PowerShell 5.1.15063.1155 
#E-Mail : mail2thiyaguji@gmail.com 
##################################################################
$Timestamp = [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'India Standard Time')
$Text = "Timelines in IST"
$EmailBody = get-winevent -filterhashtable @{logname='Microsoft-Windows-TerminalServices-LocalSessionManager/Operational';id=21} -MaxEvents 1 | Format-List -Property TimeCreated,Message
$EmailFrom = "servermonitor@dotnet-helpers.com"
$EmailTo = "dotnet-helpers@accenture.com mail2thiyaguji@gmail.com"
$EmailSubject = "Server Login Notification"
$SMTPServer = "smtp.sendgrid.net"
[string][ValidateNotNullOrEmpty()] $Username = "azure_ad8e8e784erf789.com"
[string][ValidateNotNullOrEmpty()] $pwd = "xxxxxxxxxxx"
$pwd1 = ConvertTo-SecureString -String $pwd -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $Username, $pwd1
$SMTPPort = 587
Send-MailMessage -From $EmailFrom -To $EmailTo -Subject $EmailSubject -body ($EmailBody + "($Text)" + "($Timestamp)" | Out-String) -SmtpServer $SMTPServer -Port $SMTPPort -Credential $cred 

The Windows Task Scheduler can automatically send email at a specific time or in response to a specific event. The below article will help to configure the script in Windows Scheduler Task

Here i setting this script to execute the script if any user log in to the server, so it will intimate to the supervisor by triggering mail. Go to Triggers tab and add a new trigger. The trigger should be set to fire at log on, which can be selected from the drop down.

OUTPUT:

How to delete files older than 30 days automatically using PowerShell

Delete files older than 30 days:

In many scenario we will store large number of non-important files on a different location, and its very difficult to delete those huge files old files monthly wise, to handle such scenario we are here going to use PowerShell and Task Scheduler to monitor and clean up files from any folder that are older than a specified number of days.

In this post, you’ll learn the steps to automatically delete files that haven’t been modified in the last month or any number of days you specify on Windows. The below scripts will delete the files that haven’t been modified in the last 30 days.

#################################################################
#Project : How to delete the old file automatically using Powershell
#Developer : Thiyagu S (dotnet-helpers.com)
#Tools : PowerShell 5.1.15063.1155 
#E-Mail : mail2thiyaguji@gmail.com 
##################################################################
Get-ChildItem –Path "C:\PowerShell\OriginalFolder" -Recurse | 
Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30))} | Remove-Item

In the above command remember to change “C:\path\to\folder” specifying the path to the folder that you want to delete files, and change -30 to select files with a last modified date.

How to use Task Scheduler to delete files older than 30 days automatically using Powershell:

In above code we have created Powershell script for deleting the files older than 30 day, but our scenario is want to delete automatically, Most we will use the graphic interface of Taskschd.msc console to create Windows Task Scheduler jobs and Building a single scheduled task via the GUI task scheduler might not be a big deal. But if you find yourself creating scheduled tasks repeatedly it might be a good idea to use a method that scales better than a GUI like PowerShell. However, in various scripts and automated jobs, it is much more convenient to use the PowerShell features to create scheduled tasks. In this below link, we have detail description about how to create new Windows Scheduler tasks using PowerShell.

.

How to Read Multiline User Input in Powershell

Here we will discuss about reading multi line inputs from command line using PowerShell. In some time we often get requirement to enter multiple lines or paragraphs of text as input to a PowerShell script, so we are going to discuss in this article.

Here logic is very simple, the Get-MultiLineInput function will repeatedly call Read-Host till the value entered by the user with “exit”. If user enter with “exit” then immediately it will stopping the loop.

#################################################################
#Project : How to Read Multiline User Input in Powershell
#Developer : Thiyagu S (dotnet-helpers.com)
#Tools : PowerShell 5.1.15063.1155 
#E-Mail : mail2thiyaguji@gmail.com 
##################################################################
function Get-MultiLineUserInputs {
[CmdletBinding()]
param(
)
$userinputstring = @()
$userinput = $null
while($userinput -ne "exit") {
    $userinput = Read-Host
    if($userinput -eq "exit") {
        Continue
    } else {
        $userinputstring += $userinput
 
    }
}
 
return $userinputstring
 
}
Write-Host "`nEnter your inputs (type 'exit' to finish)`n"  -ForegroundColor Green
$multilines = Get-MultiLineUserInputs
Write-Host "`nOUTPUT`n"  -ForegroundColor Green
-join $multilines

OUTPUT:

How to write data to an xml file using Powershell

Recently, I came up with a requirement of updating an config file (Xml data) in our PROD environment without login in to the sever to avoid the manual error, which lead to create this post. Let we start this implementation by step by step, here I’m using the XmlDocument .Net object here but it is possible to utilize other .Net classes, e.g. XPath and/or XDocument.

Sample XML file (web.config) 

This is the sample Web.config file which is going to be use for this whole post. 

<configuration xmlns:patch="https://www.dotnet-helpers.com/xmlconfig/">
  <dotnet-helpers-tutorials>
    <tutorials name="tutorial:start">
      <Topics hint="list">
        <Topic>MVC</Topic>
        <Topic>Jquery</Topic>
        <Topic>OOPS</Topic>
      </Topics>
    </tutorials>
  </dotnet-helpers-tutorials>
</configuration>

STEP: #1 Creating XML Elements

Here my goal is to add the “Powershell” tutorial topic at end of all other topic (ie., after OOPS) in the above xml file (extension is .config file). First we need to load the XML document (physical location of web.config) as like below,

[xml]$XmlDocument = Get-Content -Path $FilePath

STEP: #2 Searching the XML Element in the XmlDocument:

Next we need to search for the element for updating our value in the .config file. Based on the input parameter $Selector, it applies the specified pattern-matching operation to this node’s context and returns the first matching node. If no nodes match the expression, the method returns a null value.

#$Selector : //tutorials[@name=’tutorial:start’]
$events = $XmlDocument.SelectSingleNode($Selector)
$topic = $events.Topics

After execution of the first line of code, the $events variable will hold the below elements (filtered based on the input value $Selector). In the next execution it filter with Topics and sassing to the @sites variable.

<tutorials name="tutorial:start">
<Topics hint="list">
<Topic>MVC</Topic>
<Topic>Jquery</Topic>
<Topic>OOPS</Topic>
</Topics></tutorials>

STEP: #3 Creating New XML Elements

Now we can create our new element/node (ie., <Topic>Powershell</Topic>) and append it to the parent reference. Then you an append the value for the New Element with help of InnerText.

$child = $XmlDocument.CreateElement(“Topic”)
$child.InnerText = $NewTutorialTopic

STEP: #4 Adding Nested XML Elements

Finally we need to add elements by appending and save to the loaded XML file

$topic.AppendChild($child)
$XmlDocument.Save($FilePath)

Final Code

#################################################################
#Project : How to write xml data to an xml file using powershell 
#Developer : Thiyagu S (dotnet-helpers.com)
#Tools : PowerShell 5.1.15063.1155 
#E-Mail : mail2thiyaguji@gmail.com 
##################################################################
function AddEntryInConfig($Selector, $FilePath , $NewTutorialTopic)
   {
      #Get the content of the file using the path
      [xml]$XmlDocument = Get-Content -Path $FilePath
      #Selecting all the childs by finding its parent with $Selector value
      $events = $XmlDocument.SelectSingleNode($Selector)
      #Assigning the chilld elements to variable
      $topics = $events.Topics
      #creating new Element with heading as "Topic"
      $child = $XmlDocument.CreateElement("Topic")
      #Assinging the value to the Element "Topic"
      $child.InnerText = $NewTutorialTopic
      #The appendChild method is used to add the data in the newly created XmlElement to the XmlDocument.
      $topics.AppendChild($child)
      #Save in to the file
      $XmlDocument.Save($FilePath)
      Write-Host "Saved into " $Selector -ForegroundColor Green        
   }
#Calling the Function and passing the required parameter
AddEntryInConfig  "//tutorials[@name='tutorial:start']"  'C:\PowerShell\web.config' "PowerShell"

OUTPUT 

Use PowerShell to create compressed ZIP files

In many scenarios, we will have a requirements for handling to create zip archives or extract files from existing archives with programmatically .  From PowerShell 5.0, it provided two cmdlet for creating and extracting zip files. The Compress-Archive cmdlet enables you to create new archives from folders or individual files to add files to archives; Extract-Archive can be used to unzip files. Let we get in to this with very two simple example.

Example #1 : Create an Simple archive file

The below command will zip the Dotnethelpers_PowershellArticles folder and create an archive called PowershellArticles.zip in the Archives folder:

–Path : Parameter to specify the folder/file path which you want to compress.
–DestinationPath : Parameter to specify the name of the archive.

############################################################ 
#Project : Simple Compress example
#Developer : Thiyagu S (dotnet-helpers.com) 
#Tools : PowerShell 5.1.15063.1155 
#E-Mail : mail2thiyaguji@gmail.com 
############################################################
Compress-Archive -Path C:\PowerShell\ZipTest\Dotnethelpers_PowershellArticles -DestinationPath C:\PowerShell\ZipTest\PowershellArticles.zip

Example: 2 : Create an archive file using -LiteralPath

The below command creates PowerShellMVCArticles.Zip file by compressing two folders that is Dotnethelpers_PowershellArticles and PowerShellMVCArticles.Zip specified by the LiteralPath parameter instead of -path cmdlet.

############################################################ 
#Project : Create an archive file using -LiteralPath and -Update 
#Developer : Thiyagu S (dotnet-helpers.com) 
#Tools : PowerShell 5.1.15063.1155 
#E-Mail : mail2thiyaguji@gmail.com 
############################################################
Compress-Archive -LiteralPath 'C:\PowerShell\ZipTest\Dotnethelpers_PowershellArticles', 'C:\PowerShell\ZipTest\Dotnet-helpers_MVC_Articles' -CompressionLevel Optimal -Update -DestinationPath CPowerShellMVCArticles.Zip
  • -LiteralPath: Instead of -Path cmdlet, here we can use multiple paths, and include files in multiple locations in your output zipped file
  • -Update : If you are not using the -update cmdlet for compressing the existing zip files, which having same name then poweshell will throw the below error. In this scenario we need to use -Update which will command the script to overwrite, if file is already existing in the same destination location and update compression with newer versions of existing files.
Compress-Archive : The archive file C:\PowerShell\ZipTest\PowerShellMVCArticles.Zip already exists. Use the -Update parameter to update the existing archive file or use the -Force 
parameter to overwrite the existing archive file.
At line:2 char:1
+ Compress-Archive -LiteralPath 'C:\PowerShell\ZipTest\Dotnethelpers_Po ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (C:\PowerShell\Z...MVCArticles.Zip:String) [Compress-Archive], IOException
    + FullyQualifiedErrorId : ArchiveFileExists,Compress-Archive
  • -CompressionLevel : Here i had mentioned the compression level as Optimal, this indicate how much compression to apply when you are creating the archive file. If compression level parameter is not specified in our script the the command uses the default value as Optimal.

Fastest: This method available to decrease processing time; this can result in larger file sizes.
NoCompression: Do not compress the source files.
Optimal: Processing time is dependent on file size.

OUTPUT

What do you think?

I hope you have an idea of  How to Use PowerShell to create compressed ZIP files. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.

How to Use Multidimensional arrays in Powershell

Before I show you how multi-dimensional arrays work, let we start what is an array. By default, PowerShell assumes that the elements of an array are of the type variant. This means that you can mix different data types—that is, combine numerical values, dates, or strings in a single variable. The data elements of a PowerShell array need not be of the same type, unless the data type is declared (strongly typed). However, if you think to restrict an array to a certain data type then you can declare the array as like below:

In simpler as like other languages, PowerShell arrays store one or more items. An item can be any data type like string, integer, another array or a generic object.

Multidimensional arrays are one of the complex data types supported by PowerShell. In simple let you imagine a multidimensional array like a table, with columns and rows, where each cell has its own index like [1,16). Each time we put a comma, we are like telling Powershell to start a new row in the multidimensional array

Here let we discuss about the Two dimensional array with example. As shown above, the Elements in two-dimensional arrays are commonly referred by x[i][j] where i is the row number and ‘j’ is the column number. A two-dimensional array can be seen as a table with ‘x’ rows and ‘y’ columns where the row number ranges from 0 to (x-1) and column number ranges from 0 to (y-1). A two – dimensional array ‘x’ with 3 rows and 3 columns is shown below:

Note:

The Powershell start a new row in the multidimensional array when we apply the comma in starting of new row as shown below.

$scoreDetails = @( @(‘Aadharsh’, ‘200’), @(‘Rakshu’, ‘199’) )
$scoreDetails+= ,(@(“Anitha”,150))

Example

############################################################
#Project : How to Use Multidimensional arrays in Powershell
#Developer : Thiyagu S (dotnet-helpers.com)
#Tools : PowerShell 5.1.15063.1155 
#E-Mail : mail2thiyaguji@gmail.com 
############################################################
#For working with a large collection of items i would recommend using the ArrayList type from .NET as this is not a fixed size array so PowerShell will not destroy it every time you add an item to it and i've found this to work better in my projects.
System.Collections.ArrayList]$scoreDetails = @()
$scoreDetails = @( @('Aadharsh', '200'), @('Rakshu', '199') )
#Get user input and ADD to multi-dimensional array
Write-Host "Enter NEXT person score details"
$name = Read-Host "Name"
$score = Read-host "Score"
#Each time we put a comma, we are like telling Powershell to start a new row in the multidimensional array
$scoreDetails+= ,(@($name,$score))
for($parentLoop=0; $parentLoop -lt 3; $parentLoop++)
{
for($childLoop=0; $childLoop -lt 2 ; $childLoop++)
{
"The value of [$parentLoop][$childLoop] ---> " +$scoreDetails[$parentLoop][$childLoop]
}
}

OUTPUT:

What do you think?

I hope you have an idea of  How to Use Multidimensional arrays in Powershell. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.