EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PowerShell Tutorial Array in PowerShell
Secondary Sidebar
PowerShell Tutorial
  • Basics
    • PowerShell Restart Service
    • PowerShell comment
    • PowerShell Map Network Drive
    • PowerShell Append to File
    • PowerShell print
    • What is PowerShell
    • Uses Of Powershell
    • PowerShell Empire
    • PowerShell Parameter
    • PowerShell Stop Service
    • PowerShell Versions
    • How To Install PowerShell
    • PowerShell uninstall module
    • How to Use PowerShell?
    • PowerShell Logging
    • PowerShell Tools
    • PowerShell Commands
    • PowerShell Version Command
    • PowerShell Administrator
    • PowerShell Modules
    • PowerShell Registry
    • PowerShell block Comment
    • PowerShell Verbs
    • PowerShell list
    • PowerShell add user to group
    • PowerShell Write to Console
    • Variable in PowerShell
    • PowerShell New Line
    • PowerShell prompt for input
    • PowerShell File Extension
    • Powershell Remotesigned
    • PowerShell Write to File
    • PowerShell Ping
    • PowerShell wget
    • PowerShell Global variable
    • PowerShell Get-ADGroup
    • Array in PowerShell
    • PowerShell Multidimensional Array
    • PowerShell Array of Strings
    • PowerShell? join array
    • Useful PowerShell Scripts
    • String in PowerShell
    • PowerShell Switch Statement
    • PowerShell Function Parameters
    • PowerShell vs PowerShell ISE
    • PowerShell test-connection
    • PowerShell Test-NetConnection
    • PowerShell GUI
    • PowerShell Variable in String
    • PowerShell Active Directory
  • Variables
    • PowerShell Variables
    • PowerShell Environment Variables
    • PowerShell set environment variable
    • Hashtable in PowerShell
    • Set Variable in PowerShell
  • Operators
    • PowerShell Operators
    • Comparison Operators in PowerShell
    • Logical Operators in PowerShell
    • PowerShell Boolean
    • PowerShell Like Operator
  • cmdlet
    • PowerShell Wait
    • PowerShell Match
    • cmdlets in PowerShell
    • Start PowerShell from cmd
    • Add-Content in PowerShell
    • Get Help in PowerShell
    • PowerShell Copy-Item
    • PowerShell Remove-Item
    • PowerShell Move-Item
    • Get Command in PowerShell
    • PowerShell Run Command
    • Windows PowerShell ISE
    • Windows Powershell Commands
    • WinRM PowerShell
    • PowerShell Date
    • Powershell Write-Host
    • PowerShell Get-ChildItem
    • PowerShell Sort-Object
    • PowerShell Where Object
    • PowerShell Set-Content
    • PowerShell Set-Location
    • PowerShell Invoke-Command
    • PowerShell Invoke-Webrequest
    • PowerShell Get-Location
    • PowerShell Get-Date
    • PowerShell Get-Service
    • PowerShell Test-Path
    • Powershell Module Path
    • PowerShell Out-File
    • PowerShell if File Exists
    • Powershell Copy File
    • PowerShell Delete File
    • PowerShell New-Item
    • PowerShell Rename-Item
    • PowerShell ComputerName
    • PowerShell Get-Content
    • PowerShell Get-Item
    • PowerShell Get-ADUser
    • PowerShell Grep
    • PowerShell Concatenate String
    • PowerShell Get-Process
    • PowerShell Count
    • PowerShell pause
  • Control Statements
    • If Statement in PowerShell
    • If Else in PowerShell
    • Else If in PowerShell
    • Loops in PowerShell
    • For loop in PowerShell
    • PowerShell While Loop
    • PowerShell do while
    • PowerShell Loop through Array
    • PowerShell add to array
    • PowerShell ForEach Loop
    • PowerShell Break
    • PowerShell Continue
    • Switch Case in PowerShell
    • PowerShell If-Not
    • Try-catch in PowerShell
  • Functions
    • PowerShell Functions
    • PowerShell String Functions
    • powershell nslookup
    • PowerShell here string
    • PowerShell Wildcards
    • Regex in PowerShell
    • PowerShell not like
    • PowerShell Filter
    • PowerShell Sleep
    • PowerShell where
    • PowerShell join string
    • PowerShell Exit
    • PowerShell null
    • PowerShell Dictionary
    • PowerShell Location
    • PowerShell Start-Service
    • PowerShell is not digitally signed
    • PowerShell Uptime
    • PowerShell Create Directory
    • PowerShell Trim
    • PowerShell Join-Path
    • PowerShell Execution Policy
    • PowerShell SubString
    • PowerShell Format Table
    • PowerShell Import Module
    • PowerShell ForEach Object
    • PowerShell Alias
    • PowerShell Scheduled Task
    • PowerShell Convert String to Date
    • PowerShell Split String
    • PowerShell Multiline String
    • PowerShell MultiLine Comment
    • PowerShell Rename Folder
    • PowerShell Delete Folder
    • PowerShell String Replace
    • PowerShell join
    • PowerShell xcopy
    • PowerShell Base64
    • PowerShell Tail
    • PowerShell User List
    • PowerShell remove User from group
    • PowerShell JSON Format
    • PowerShell Send Mail
    • PowerShell Convert to String
    • PowerShell Start-Process
    • PowerShell change directory
    • PowerShell Open File
    • PowerShell Batch File
    • PowerShell ZIP
    • PowerShell unzip
    • PowerShell XML
    • PowerShell XML Parsing
    • Remote PowerShell
    • PowerShell Escape Character
    • PowerShell scriptblock
    • PowerShell Executable Location
    • PowerShell Import-CSV?
    • PowerShell Export CSV
  • Interview Questions
    • PowerShell Interview Questions

Related Courses

Shell Scripting Course

All in One Data Science Courses

Data Visualization Courses

Array in PowerShell

By Priya PedamkarPriya Pedamkar

Array in PowerShell

Introduction to Array in PowerShell

The array is a type of data structure that can be used to store a collection of items, the collection of items can be either of the same datatype or different. The elements in an array can be accessed using the index. The index of the array usually starts at 0, so to access the first element you must use the index [0]. Typically, only two operations can be on an array, i.e. adding an element to the array or removing an element. In this article, we are going to learn about the Array in PowerShell.

Defining an Array in PowerShell

An array can be defined in any of the following ways,

The @ () is one of the ways of defining an array.

Example:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

$Subject = @(‘History’,’Geo’,’Maths’)

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,650 ratings)
  • An array can be created as a comma-separated list as well.

$test=’testone’,’testtwo’,’testthree’

  • An array can be created for a specific datatype element as follows,

[int[]] $numbersarray = 1,2,3,4,5

The above is an integer array and it can hold only integer values.

Accessing an Array

Let us define an array,

Example:

$test=@(‘test1’,’test2’,’test3’,’test4’)

$test [0] will return test1, $test [3] will return test4. Many languages allow only a single index to be specified, whereas in PowerShell multiple indexes can be used simultaneously.

In the above $test [1, 3] will return,

test2

test4

Operations on an Array

Adding items to an array. Let’s see an example of how to add an element to an existing array.

Example:

$test=@(‘welcome’,’home’)

To add to the above array, the ‘+=’ operator is used.

$test+=’Raj’

Running $test will return,

welcome

home

Raj

Getting the Count of an Array

Here we explain, how to use the following input to get the count of an array.

Input:

$test=@(‘test1’,’ertr’,’fgdfgfd’,’dfgfdg’,’dfdfsd’,’dfgfdgdfg’)

$test.Count will return 6 which is the count/length of the array.

1. Sorting the Elements in an Array

The sort operator can be used to sort the elements of an array if the elements are of the same datatype.

Input:

$test=@(‘oneee’,’zddsdsad’,'thraewawe')
$test |sort

The above command will sort the elements in the ascending order

Output:

sort the elements

Input:

$test |sort -Descending will sort the elements in the descending order

Output:

Array in PowerShell 1-2

2. Updating Item in an Array

The index can be used to update an element in the array

Input:

$test=@(‘oneee’,’zddsdsad’,'thraewawe')
$test[0]=’changed’

The above command will change the ‘one’ to ‘changed’. Executing $test will return

Output:

update

3. Finding an Element in an Array

To check an array for value, the like operator can be used

Input:

$test=@(‘viki’,ramu,'aravind','vikram')
$test -like "*vik*"

Output:

Array in PowerShell 1-4

Multidimensional Array in PowerShell

We can create a multidimensional array as follows,

$testMultidimensionalArrays = @(1,2,3), @(4,5,6), @(7,8,9)

Each array has one row and three columns.

Looping an Array

Like in any other languages the for loop can be used to loop items in an array.

Input:

$test=@(‘viki’,’ramu’,'aravind','vikram')
for($i=0;$i -lt $test.Length; $i++)
{
Write-Host $test[$i] }

Output:

for loop

For-each can be used to perform an action against each item in the array.

Input:

$test=@(1,4,5,6,7,8,9,10)
foreach($i in $test)
{
$i=$i+5
Write-Host $i
}

Output:

Array in PowerShell 1-6

Array List in PowerShell

One of the drawbacks with Array is adding items to it, to overcome that we have an array list.

The following is the syntax to create an Array List,

$myarray = [System.Collections.ArrayList]::new()
$myarray.Add(1)
$myarray.Add(2)
$myarray.Add(3)
$myarray

The first line is the way to initialize an Array List and the subsequent lines are to add items to the ArrayList

Array vs Array List Performance

The following examples show the difference in performance while performing an operation on an array and array list

Input:

Measure-Command -Expression { 0..250 | ForEach-Object { $arr += $_+1 }}
$arrlit = [System.Collections.ArrayList]@()
$f arrlit _performance = Measure-Command -Expression { 0..250 | ForEach-Object { $ arrlit += $_+1 }}
$ arrlit _performance

The first command performs an operation on the array and the third line does that same on an array list.

Output: 

  • Performance of Array

Array in PowerShell 1-7

  • Performance of Array List

Array in PowerShell 1-8

The performance of the array list is faster and better than that of the array.

Example of Array in PowerShell

Following is an example to find the length of an array using for loop, foreach loop and while loop.

Input:

$testlist = 5.634, 4.512323, 3.312323, 13.2213213, 4.02324, 34.3334324, 34.04324, 45.4534324, 99.993234324, 11123234234 write-host("Printing the array elements")
$testlist
write-host("length of array")
$testlist.Length
write-host("fifth element in array")
$testlist[4] write-host("partial array")
$subList = $testlist[1..3] write-host("using for loop")
for ($i = 0; $i -le ($testlist.length - 1); $i += 1) {
$testlist[$i] }
write-host("using forEach Loop")
foreach ($e in $testlist) {
$e
}
write-host("using while Loop")
$i = 0
while($i -lt 4) {
$testlist[$i];
$i++
}
write-host("Assign values")
$testlist[1] = 10
$testlist

Output:

Array in PowerShell 1-9

Hash Table

Hash table is used to implement a structured array. In the hash table, the values are stored in a key-value format. They are also known as Dictionary or Associative array.

Syntax:

$testhashtable=@{}

Or

$testhashtable=@{ key1=”test1”;key2=”test2”;key3=”test3”}

Where key1, key2, and key3 are the keys and test1, test2 and test3 are the values.

Input:

$testhashtable

Output:

hash table

The key or the values can be accessed as follows using the .dot operator

Input:

$testhashtable.keys

Output:

Array in PowerShell 1-11

Input:

$testhashtable.Values

Output:

Array in PowerShell 1-12

Example

Following is an example to find all the hashtable keys and hashtable values.

Input:

$testht = @{ English = "85"; Tamil = "100"; maths = "100"}
write-host("Printing all the hashtable keys")
$testht.keys
write-host("Printing all the hashtable values")
$testht.values
write-host("print Size")
$testht.Count
write-host("Add key-value")
$testht["Social"] = "100"
write-host("Add key-value")
$testht.Add("ss","110")
write-host("Size")
$testht.Count
write-host("Remove English")
$testht.Remove("English")
write-host("curentSize")
$testht.Count
write-host("sortinh by key")
$testht.GetEnumerator() | Sort-Object -Property key

Output:

Array in PowerShell 1-13

Conclusion – Array in PowerShell

The main advantage of an array is memory management. They can be accessed directly from the cache which helps in faster retrieval. They are reusable, once it’s declared they can be reused multiple times.

Recommended Articles

This is a guide to Array in PowerShell. Here we discuss the introduction and the implementation of an array, array list and hash table in PowerShell. You may also look at the following articles to learn more –

  1. PowerShell vs CMD
  2. Top 7 Versions of PowerShell
  3. Advantages Of Array
  4. Key Difference Between PowerShell and Bash
  5. Concept of Escape Clause with Query Examples
  6. Powershell Write-Host | Examples with Syntax
  7. Complete Guide to PowerShell Sort-Object
Popular Course in this category
Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)
  41 Online Courses |  13 Hands-on Projects |  322+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Shell Scripting Training (4 Courses, 1 Project)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
Data Visualization Training (15 Courses, 5+ Projects)4.7
2 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more