PowerShell Array – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Tue, 21 Nov 2023 15:32:45 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 PowerShell Array – Java2Blog https://java2blog.com 32 32 Merge Arrays in PowerShell https://java2blog.com/powershell-merge-arrays/?utm_source=rss&utm_medium=rss&utm_campaign=powershell-merge-arrays https://java2blog.com/powershell-merge-arrays/#respond Tue, 25 Jul 2023 13:09:00 +0000 https://java2blog.com/?p=24217 Using + Operator

Use + operator to merge arrays in PowerShell.

$array1 = @("Welcome", "to", "Java2Blog!")
$array2 = @("Let's", "learn", "together.")
$merged_array = $array1 + $array2
echo $merged_array
Welcome
to
Java2Blog!
Let's
learn
together.

We used the sub-expression operator represented by @() to create two separate arrays named $array1 and $array2 (you can also create arrays without using the sub-expression operator). Note that both arrays contained string-type values.

Next, we used the + operator to join $array1 and $array2 and assigned the merged array to the $merged_array variable, which was further used with the echo command to display on the PowerShell console.

The order of the arrays while using the concatenation operator (+) is more important. In the above example, the elements of $array1 were followed by $array2 elements because we concatenated them as $array1 + $array2.

To have the items of $array2 first, concatenate both arrays as $array2 + $array1. See the following example.

$array1 = @("Welcome", "to", "Java2Blog!")
$array2 = @("Let's", "learn", "together.")
$merged_array = $array2 + $array1
echo $merged_array
Let's
learn
together.
Welcome
to
Java2Blog!

Let’s take another use case where both arrays should have at least one duplicate element but the merged array must contain unique values. Here, we are required to remove identical items by case-sensitive check. See the below example for a clear understanding.

$array1 = @("How", "are", "You")
$array2 = @("What", "are", "you", "learning")
$merged_array = $array1 + $array2
$merged_array = $merged_array | Select-Object -Unique
$merged_array
How
are
You
What
you
learning

Again, we created two arrays, $array1 and $array2, containing string elements. We used the + operator to concatenate them and stored the merged array in the $merged_array variable. Now, the $merged_array had duplicate items ("are" and "you") that we wanted to remove by case-sensitive check.

To do that, we piped the $merged_array to the Select-Object cmdlet, which selected the unique items using -Unique parameter. This parameter specified that if the subset of the input has identical values or properties, only one member of the subset should be chosen.

As this parameter is case-sensitive, the strings differ in character-casing and would be considered a unique value; for instance, Hi and hi differ. Remember, the -Unique parameter will select items after applying other filtering parameters (if you use them). And the first instance of the duplicate value would be included in the results; see the above output.

What should you do if you want to merge two arrays and remove identical items from the merged array by case-insensitive check? For this particular use case, we will get the advantage of the Sort-Object cmdlet with -Unique parameter as demonstrated below.

$array1 = @("How", "are", "You")
$array2 = @("What", "are", "you", "learning")
$merged_array = $array1 + $array2
$merged_array = $merged_array | Sort-Object -Unique
$merged_array
are
How
learning
What
You

This code fence is similar to the last one, but we used the Sort-Object with the -Unique parameter to remove duplicates from $merged_array by case-insensitive check.

The Sort-Object cmdlet is used to sort objects in descending or ascending order; by default, it sorts in ascending order; you must mention the -Descending parameter to sort in descending order.

We used the default behaviour of the Sort-Object cmdlet, as we had string items in both arrays so that they would be sorted alphabetically from A to Z characters.

The -Unique parameter indicated the Sort-Object cmdlet to remove duplicate items and return the unique members of the given input ($merged_array). It included the first instance of the duplicate value in the sorted output.

Here, the -Unique parameter is case-insensitive, which means strings that differ in character-case will be considered the same; for example, "World" and "world" are the same strings.

Using += Operator

Use the += operator to merge arrays in PowerShell.

$array1 = @("How", "are", "You")
$array2 = @("What", "are", "you", "learning")
$array1 += $array2
$array1
How
are
You
What
are
you
learning

This example resembles the one where we used the + operator to concatenate/merge the arrays, but we used the += operator this time. The += operator is preferred where we do not want to create a new variable to hold the merged array but want to update the current array, as we modified the $array1 by merging the elements of $array2 into it.

Again, the order of specifying the variable names matters a lot. For example, the output of $array1 += $array2 and $array2 += $array1 would differ, so be careful while writing the variable names.

Here, we can use the Select-Object and Sort-Object cmdlets with the -Unique parameter to remove the identical values from the merged array by case-sensitive and case-insensitive checks. We have learned these cmdlets and parameters in the previous section; you can refer to that.

$array1 = @("How", "are", "You")
$array2 = @("What", "are", "you", "learning")
$array1 += $array2

echo "Remove Duplicates by Case-sensitive Check:"
echo $array1 | Select-Object -Unique
echo "`n"

echo "Remove Duplicates by Case-insensitive Check:"
echo $array1 | Sort-Object -Unique
Remove Duplicates by Case-sensitive Check:
How
are
You
What
you
learning

Remove Duplicates by Case-insensitive Check:
are
How
learning
What
You

-Unique parameter is case-sensitive while using it with the Select-Object cmdlet. On the other hand, it is case-insensitive while using it with the Sort-Object cmdlet.

Using a Comma

Use a comma (,) to merge two arrays in PowerShell. The merged array must be an array of arrays.

$array1 = @(3,8,5)
$array2 = @(9,8,7)
$merged_array = $array1, $array2
echo $merged_array
3
8
5
9
8
7

Alternatively, merge the arrays as follows if you want to have $array2 followed by the $array1 in the merged array.

$array1 = @(3,8,5)
$array2 = @(9,8,7)
$merged_array = $array2, $array1
echo $merged_array
9
8
7
3
8
5

As the $merged_array is an array of arrays, we can not use Select-Object or Sort-Object to remove identical elements, as both cmdlets work on individual objects. To use these commands, we need to flatten the array first. How? Let’s learn it in the following example.

$array1 = @(3,8,5)
$array2 = @(9,8,7)

$merged_array = $array2, $array1
$flattened_array = $merged_array | ForEach-Object { $_ }

echo "Remove Duplicates:"
echo $flattened_array | Select-Object -Unique
echo "`n"

echo "Remove Duplicates in Sorted Output:"
echo $flattened_array | Sort-Object -Unique
Remove Duplicates:
9
8
7
3
5

Remove Duplicates in Sorted Output:
3
5
7
8
9

Using AddRange() Method

Use the AddRange() method to merge two arrays in PowerShell, but the merged array must be an ArrayList.

$array1 = 4, 5, 3
$array2 = 4, 5, 6

$merged_array = New-Object System.Collections.ArrayList

$merged_array.AddRange($array1)
$merged_array.AddRange($array2)
$merged_array
4
5
3
4
5
6

After creating two arrays ($array1 and $array2), we used the New-Object cmdlet to instantiate the ArrayList class and assign its reference to the $merged_array variable.

Next, we chained the AddRange() method with the $merged_array variable to add elements of the specified collection (which was an array in our case) to the end of an array list. Finally, we printed the $merged_array on the PowerShell console.

We can also use Select-Object/Sort-Object cmdlets with the -Unique parameter (already learned in the first section) to eliminate duplicate items from the merged array list.

$array1 = 4, 5, 3
$array2 = 4, 5, 6

$merged_array = New-Object System.Collections.ArrayList
$merged_array.AddRange($array1)
$merged_array.AddRange($array2)

echo "Remove Duplicates:"
echo $merged_array | Select-Object -Unique
echo "`n"

echo "Remove Duplicates in Sorted Output:"
echo $merged_array | Sort-Object -Unique
Remove Duplicates:
4
5
3
6

Remove Duplicates in Sorted Output:
3
4
5
6

Until now, we have gone through various ways to merge two arrays where the elements of the second array follow the elements of the first array. What if we are supposed to merge two arrays by fetching the items from every array one by one? How can it be accomplished? Let’s see it in the following section.

Using for Loop

To merge two arrays by getting the elements from each array one by one in PowerShell:

  • Create two arrays containing string values.
  • Create an empty array to hold merged content.
  • Use the Max() method to grab the maximum size from both arrays created in the first step and assign it to a variable.
  • Use the for to loop over the arrays created in the first step.
  • In each iteration:
    • Grab the current element and append it to the array created in the second step.
  • Use echo to print the merged array.
$firstNames = @("Mehvish", "Maryam", "Christopher")
$lastNames = @("Ashiq", "Mukhtar", "Daniel")
$merged_array = @()

$MaxArraySize = [Math]::Max($firstNames.Length, $lastNames.Length)

for ($i = 0; $i -lt $MaxArraySize; $i++){ 
    $merged_array+=$firstNames[$i]
    $merged_array+=$lastNames[$i]
}

echo $merged_array
Mehvish
Ashiq
Maryam
Mukhtar
Christopher
Daniel

In the above example, we created three arrays. The first array ($firstNames) contained the first names, and the second array ($lastNames) had the last names, while the third array ($merged_array) was empty. We used the @() operator to create all these arrays; you can also create without using this operator.

Next, we used the Max() function to get the maximum value from the given length of the $firstNames and $lastNames arrays. Note that we got the length of each array using their Length property.

We stored the maximum value, returned by the Max() function, in the $MaxArraySize variable, which we further used within the for loop to iterate $MaxArraySize times over the $firstNames and $lastNames arrays.

We retrieved the current element in each iteration and appended it to the $merged_array using the += operator. Finally, we used the echo command to print the $merged_array on the console.

We can modify the above code to get the fetched elements next to each other with a header; see the following code fence.

$firstNames = @("Mehvish", "Maryam", "Christopher")
$lastNames = @("Ashiq", "Mukhtar", "Daniel")
$merged_array = @()

$MaxArraySize = [Math]::Max($firstNames.Length, $lastNames.Length)

$merged_array = for ($i = 0; $i -lt $MaxArraySize; $i++){ 
    Write-Verbose "$($firstNames[$i]),$($lastNames[$i])"
    [PSCustomObject]@{
        FirstNames = $firstNames[$i]
        LastNames = $lastNames[$i]
    }
}
echo $merged_array
FirstNames  LastNames
----------  ---------
Mehvish     Ashiq
Maryam      Mukhtar
Christopher Daniel

The above code is similar to the last one, with a few modifications. Here, inside the for loop, we used the Write-Verbose cmdlet to write a verbose message denoting the current values of the $firstNames and $lastNames arrays.

We used [PSCustomObject]@{} notation to create an object having two properties: FirstNames and LastNames, which were set to the current values of $firstNames and $lastNamesarrays. Then, the created object in each iteration was pipelined, which gathered all the objects in the $merged_array variable.

Once the for loop finished, the $merged_array would have an array of objects where every object would contain a pair of corresponding items from the $firstNames and $lastNames arrays. Finally, we used an echo command to show the $merged_array on the PowerShell console.

Until now, we have merged simple arrays, but how to merge the custom object arrays?

Merging Custom Object Arrays

To merge two custom object arrays in PowerShell:

  • Create two arrays, each having custom objects, while the custom object has two properties.
  • Use the + operator to merge both arrays created in the first step and store the merged array in a variable.
  • Use the echo command to display the merged array.
$array1 = @([PSCustomObject]@{
            FirstName = "John"
            LastName = "Christopher"
          },
          [PSCustomObject]@{
            FirstName = "Priya"
            LastName = "Mehta"
            })

$array2 = @([PSCustomObject]@{
            FirstName = "Saira"
            LastName = "Daniel"
          },
          [PSCustomObject]@{
            FirstName = "Shruti"
            LastName = "Mehta"
          })

$merged_array = $array1 + $array2
echo $merged_array
FirstName LastName
--------- --------
John      Christopher
Priya     Mehta
Saira     Daniel
Shruti    Mehta

This example is similar to the first code snippet we learned in this article, but the array creation differs. Here, we created two arrays ($array1 and $array2); each array contained custom objects that we created using [PSCustomObject]@{} notation. Each custom object had two properties called "FirstName" and "LastName".

Then, we used the + operator to merge both arrays and stored it in the $merged_array, which was further used with echo to show on the console. Note that you can use this code snippet and use different ways we learned in this article to merge $array1 and $array2.

To get unique values, let’s use the Select-Object and Sort-Object cmdlets with the -Unique parameter.

$array1 = @([PSCustomObject]@{
            FirstName = "John"
            LastName = "Christopher"
          },
          [PSCustomObject]@{
            FirstName = "Priya"
            LastName = "mehta"
            })

$array2 = @([PSCustomObject]@{
            FirstName = "Saira"
            LastName = "Daniel"
          },
          [PSCustomObject]@{
            FirstName = "Shruti"
            LastName = "Mehta"
          })

$merged_array = $array1 + $array2

echo "Remove Duplicates by Case-sensitive Check:"
echo $merged_array | Select-Object -Unique -Property LastName
echo "`n"

echo "Remove Duplicates by Case-insensitive Check:"
echo $merged_array | Sort-Object -Unique -Property LastName
Remove Duplicates by Case-sensitive Check:

LastName
--------
Christopher
mehta
Daniel
Mehta

Remove Duplicates by Case-insensitive Check:
Christopher
Daniel
Mehta

In the first section, We have already learned the Select-Object, Sort-Object cmdlets, and -Unique parameter.

That’s all about merge arrays in PowerShell.

]]>
https://java2blog.com/powershell-merge-arrays/feed/ 0
Cannot Index into a Null Array in PowerShell https://java2blog.com/cannot-index-into-null-array-powershell/?utm_source=rss&utm_medium=rss&utm_campaign=cannot-index-into-null-array-powershell https://java2blog.com/cannot-index-into-null-array-powershell/#respond Sun, 18 Jun 2023 07:31:06 +0000 https://java2blog.com/?p=24087 If you are encountering the error message Cannot index into a null array in PowerShell, this indicates that you are trying to access an index of an array that doesn’t exist or has not been initialized yet. This error may also occur if you access the array set to $null. Let’s reproduce the error before diving into the solutions.

Reproducing Error

Access the element of an array at index 0, which has not been initialized yet, to reproduce an error saying it can’t index into a null array.

$myArray
$myArray[0]
It cannot index into a null array.
At line:2 char:1
+ $myArray[0]
+ ~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray

Possible Ways to Fix Error

To fix the error, initialize the array before accessing its elements or check if array is empty or not. Use the following methods to resolve Cannot Index into a Null Array in PowerShell.

  1. Check the length of the array
  2. Using the @() Syntax
  3. Using the New-Object Command
  4. Using a comma-separated List
  5. Using the System.Collections.ArrayList Class
  6. Using the InitializeArray() Method

Check the length of the array

To check if an array is empty access its count property e.g. arr.count. If count is equal to 0, then array is empty. If count is greater than 0, then array isn’t empty. If we check if array is empty before accessing the elements, we can avoid this error.

$array = @()
if ($array.count -eq 0){
    Write-Host "The array is empty."
}
else{
    Write-Host "The array is not empty.
}
The array is empty.

Use @() Syntax

Use the @() syntax to create and initialize an array.

$myArray = @("value1", "value2", "value3")
echo $myArray[0]
value1

The array named $myarrayis created with three elements. All three elements in the array are initialized to a string value, i.e., value1, value2, and value3. The @() syntax creates an empty array and then adds the specified values to the array using commas between each value. After that, the value at index 0 of the$myArray is printed to the console using the echo command.

Use New-Object Command

Use the New-Object cmdlet to create an array and initialize each index with a value.

$myArray = New-Object string[](3)
$myArray[0] = "Element 1"
$myArray[1] = "Element 2"
$myArray[2] = "Element 3"
echo $myArray[0]
Element 1

In this approach, the New-Object command is used to create an array named $myarray. First, the type is specified as a string (as it could be int), and the size of the array is specified to three elements. Next, the values are initialized using the array index notation. Finally, the array’s element at the 0 index is displayed to the PowerShell console using the echo command.

Use Comma-Separated List

Use a comma-separated list to initialize an array in PowerShell.

$myArray = "value1", "value2", "value3"
echo $myArray[0]
value1

This approach creates the array with three elements and initializes each to a string value. We named this array $myarray. Next, the comma-separated list of strings is assigned to the array. The integer or float values can also be given to the array; in that case, do not use the double quotes for each element. For example, if you want to create an array of integers, write the code as $myArray = 1, 2, 3, 4, 5. After creating the array, the echo statement prints the array element to the PowerShell console.

Use System.Collections.ArrayList Class

Use the System.Collections.ArrayList class to create and initialize an ArrayList in PowerShell.

$myArray = New-Object System.Collections.ArrayList
$myArray.Add("value1") | Out-Null
$myArray.Add("value2") | Out-Null
echo $myArray[0]
value1

First, the $myarray array list is created using the New-Object System.Collections.ArrayList. After that, the Add() method is used to add the elements to the array. Next, the value1 and value2 elements are added to the $myarray.

Then, the Add() method redirected the output to the Out-Null cmdlet to suppress any output generated by the Add() method. Finally, the element at the index 0of the array list is printed to the console using the echo command.

Use System.Array Class

Use the System.Array class to create and initialize an array in PowerShell.

$myArray = [System.Array]::CreateInstance([int], 3)
$myArray.Initialize()
echo $myArray[0]
0

First, the $myarray array is created using System.Array. Then, the static CreateInstance() method creates a new instance of an array. Next, the type of elements and length of the array is passed as a parameter to the CreateInstance() method.

For the above example, the element type is specified to integer ([int]) and the array’s length is 3. After that, the Initialize() method initialized the array with 0 elements.

That’s all about how to fix cannot index into a null Array in PowerShell.

]]>
https://java2blog.com/cannot-index-into-null-array-powershell/feed/ 0
PowerShell Add Array to Array https://java2blog.com/powershell-add-array-to-array/?utm_source=rss&utm_medium=rss&utm_campaign=powershell-add-array-to-array https://java2blog.com/powershell-add-array-to-array/#respond Sat, 27 May 2023 10:26:09 +0000 https://java2blog.com/?p=24031 Using + Operator

Use the + operator to add an array to another array.

$array1 = @(1, 2, 3)
$array2 = @(4, 5, 6)
$newArray = $array1 + $array2
$newArray
1
2
3
4
5
6

First, we used the array operator represented by @() to declare two arrays, $array1 and $array2, containing the values 1,2,3and 4,5,6. After that + operator is used to concatenate the two arrays together into a $newArray.

In PowerShell, when you use the + operator with arrays, it creates a new array that contains all the elements from both arrays. So, $newArray contains all six elements: 1, 2, 3, 4, 5, and 6. Finally, we output the $newArray contents to the console.

Using += Operator

Use the += operator to add an array to another array.

$array1 = @(1, 2, 3)
$array2 = @(4, 5, 6)
$array1 += $array2
$array1
1
2
3
4
5
6

The above code block is similar to the previous one but uses the += operator to add $array2 to the end of $array1. The += operator is a shorthand way of writing $array1 = $array1 + $array2, where the elements of $array2 are added to the end of $array1. Finally, the code displays the contents of $array1 on the PowerShell console.

Using , Operator

Using the Comma Operator Array Type Accelerator (,) to add an array to another array.

$array1 = @(1, 2, 3)
$array2 = @(4, 5, 6)
$newArray = ,$array1 + ,$array2
$newArray
1
2
3
4
5
6

This snippet is similar to the previous two codes, but it uses the comma operator (,) to create an array of arrays by putting a comma before each array variable; for example, ,$array1 and ,$array2. This creates two single-element arrays, each containing the original array. Finally, the code uses the + operator to concatenate the two single-element arrays and assigns the resulting array to the $newArray variable. The resulting array will contain two elements, each of which is one of the original arrays.

Using Array Constructor

Use the array constructor to add an array to another array.

$array1 = @(1, 2, 3)
$array2 = @(4, 5, 6)
$newArray = [array]($array1 + $array2)
$newArray
1
2
3
4
5
6

Here, we use the array constructor to add an array to another array. First, the $newArray is created using the array constructor. Next, the + operator concatenates the two arrays $array1 and $array2, and the resulting array is enclosed in [array]() to create a new array object. Finally, the resulting array is assigned to the variable $newArray and then printed to the console using the variable name.

Using AddRange() & InsertRange() Methods

Use the AddRange() and InsertRange() methods to add an array to another array.

$array1 = @(1, 2, 3)
$array2 = @(4, 5, 6)
$newArray = New-Object System.Collections.ArrayList
$newArray.AddRange($array1)
$newArray.InsertRange($array1.Count, $array2)
$newArray
1
2
3
4
5
6

The above code snippet takes two arrays like previous code snippets; then the $newArray variable is created as an instance of the System.Collections.ArrayList class, which provides the AddRange() and InsertRange() methods to add elements to the array.

Please note that final object will be ArrayList in this method.

The AddRange() is used to add the elements of $array1 to $newArray, and the InsertRange() is used to insert the elements of $array2 after the elements of $array1. Finally, the contents of the $newArray variable are printed to the console.

So, we learned that arrays could be combined using various PowerShell methods, such as the +, +=, , operators, array constructor, and AddRange() method. These approaches provide flexibility and allow users to choose a solution that fits their requirements and preferences.

That’s all about PowerShell add array to array.

]]>
https://java2blog.com/powershell-add-array-to-array/feed/ 0
Convert Array to ArrayList in PowerShell https://java2blog.com/convert-array-to-arraylist-powershell/?utm_source=rss&utm_medium=rss&utm_campaign=convert-array-to-arraylist-powershell https://java2blog.com/convert-array-to-arraylist-powershell/#respond Sun, 16 Apr 2023 13:40:06 +0000 https://java2blog.com/?p=23543 One of the everyday tasks is converting an array to an ArrayList in PowerShell. It can be helpful when you need to work with dynamic data structures or manipulate data in memory. However, before we dive into how to convert an array to ArrayList, it’s essential to understand the difference between these two.

An array is a collection of values having the same type stored in a single variable. Arrays are fixed in size, meaning that once an array is created, its size cannot be changed.

An ArrayList, on the other hand, is a dynamic collection of values of any type that can be resized as needed. It can be helpful when adding or removing elements from a collection.

Now that you know arrays and ArrayList, let’s continue learning various approaches to convert arrays to ArrayList in PowerShell.

Using casting to System.Collections.ArrayList

Cast array object to System.Collections.ArrayList to convert array to ArrayList in PowerShell.
Here is an example:

$colours = @("Red", "Green", "Blue")
$arrayList = [System.Collections.ArrayList]$colours
Write-Host "ArrayList Contents:"
foreach ($colour in $arrayList) {
    Write-Host $colour
}
ArrayList Contents:
Red
Green
Blue

Using New ArrayList Object with AddRange() method

To convert array to ArrayList in PowerShell:

  • Create new object of type System.Collections.ArrayList using New-Object cmdlet.
  • Use AddRange() method to add array $colours to $arrayList object.
$colours = @("Red", "Green", "Blue")
$arrayList = New-Object System.Collections.ArrayList
$arrayList.AddRange($colours)
Write-Host "ArrayList Contents:"
foreach ($colour in $arrayList) {
    Write-Host $colour
}
ArrayList Contents:
Red
Green
Blue

In the above code, the $colours = @("Red", "Green", "Blue") line creates an array of colours and assigns it to the variable $colours. The @() notation creates an array in PowerShell.

The$arrayList = New-Object System.Collections.ArrayListline creates a new ArrayList object and assigns it to the variable $arrayList. The New-Object is used to create a new instance of a .NET class.

After that$arrayList.AddRange($colours) line adds the contents of the $colours array to the $arrayList ArrayList object using the AddRange() method. This method adds multiple items to the ArrayList at once.

The Write-Host cmdlets output a string ArrayList Contents: to the console to indicate that the following lines will output the contents of the ArrayList.

Finally, we used the foreach loop to iterate over each item in the $arrayList ArrayList object and output it to the console using the Write-Host cmdlet. The loop variable $colour stores the current item being processed.

Once you have an ArrayList object, you can use its methods and properties to manipulate the data. These methods are as follows:

  1. Add an Element
  2. Remove an Element
  3. Sort the Elements
  4. Get a Count of Elements

Let’s continue learning these methods.

Use Add() Method of ArrayList Object

Using the Add() to add a new element to ArrayList.

$colours = @("Red", "Green", "Blue")
$arrayList = New-Object System.Collections.ArrayList
$arrayList.AddRange($colours)
$arrayList.Add("Yellow")
Write-Host "ArrayList Contents:"
foreach ($colour in $arrayList) {
    Write-Host $colour
}
ArrayList Contents:
Red
Green
Blue
Yellow

The above code fence is similar to the previous one but added the add() method to insert an element to ArrayList.

Use Remove() Method of ArrayList Object

Use the Remove() method to remove an existing element from an ArrayList.

$colours = @("Red", "Green", "Blue", "Yellow")
$arrayList = New-Object System.Collections.ArrayList
$arrayList.AddRange($colours)
$arrayList.Remove("Blue")
Write-Host "ArrayList Contents:"
foreach ($colour in $arrayList) {
    Write-Host $colour
}
ArrayList Contents:
Red
Green
Yellow

The above code fence is similar to the previous example, but it uses the Remove() method to eliminate an element from the ArrayList and outputs the updated contents of the ArrayList to the console using the Write-Host cmdlet.

Use Sort() Method of ArrayList Object

Use the Sort() method to sort elements in an ArrayList.

$colours = @("Red", "Green", "Yellow")
$arrayList = New-Object System.Collections.ArrayList
$arrayList.AddRange($colours)
$arrayList.Sort()
Write-Host "ArrayList Contents:"
foreach ($colour in $arrayList) {
    Write-Host $colour
}
ArrayList Contents:
Green
Red
Yellow

The code above follows a similar pattern as the previous two examples, but in this case, the Sort() method is employed to arrange the items in the ArrayList in ascending order. The Write-Host cmdlet is then used to print the updated contents of the ArrayList to the console.

Use Count Property of ArrayList Object

Use the count property to retrieve the count of total elements present in ArrayList.

$colours = @("Red", "Green", "Yellow")
$arrayList = New-Object System.Collections.ArrayList
$arrayList.AddRange($colours)
$count = $arrayList.Count
Write-Host "ArrayList Contents:"
foreach ($colour in $arrayList) 
{
    Write-Host $colour
}
Write-Host "The total number of elements in the ArrayList = $count"
ArrayList Contents:
Red
Green
Yellow
The total number of elements in the ArrayList = 3

This code snippet above follows the same pattern as the previous three examples, but in this case, it uses the Count property to retrieve the total number of items in the ArrayList. The Write-Host cmdlet is then used to display the updated contents on the console.

Based on the solutions above, the ArrayList object can easily be converted from an array to an ArrayList, and its methods and properties can be used to manipulate the data. For example, we add an element to the ArrayList using the Add() method, remove the first element with the Remove() method, sort the elements using the Sort() method, and get the element count with the Count property.

That’s all about how to convert array to ArrayList in PowerShell.

]]>
https://java2blog.com/convert-array-to-arraylist-powershell/feed/ 0
PowerShell Split Path into Array https://java2blog.com/powershell-split-path-into-array/?utm_source=rss&utm_medium=rss&utm_campaign=powershell-split-path-into-array https://java2blog.com/powershell-split-path-into-array/#respond Wed, 05 Apr 2023 07:25:53 +0000 https://java2blog.com/?p=23491 Split Path into Array in PowerShell

Using Split() Method

Use the Split() method to split the path into an array in PowerShell.

$path = "C:\Users\John\Desktop\Samples\House_Prediction_Using_Two_File_Dataset.pdf"
$pathIntoArray = $path.Split("\")
$pathIntoArray
C:
Users
John
Desktop
Samples
House_Prediction_Using_Two_File_Dataset.pdf

First, we defined a $path variable and set its value to a path as demonstrated above; you can initialize it with your own path. Next, we chained the Split() method with the $path variable and passed \ as a delimiter to the Split() method to split the $path into an array. Finally, we stored this array in the $pathIntoArray variable.

We can use index operator to get elements of the array.

$path = "C:\Users\John\Desktop\Samples\House_Prediction_Using_Two_File_Dataset.pdf"
$pathIntoArray = $path.Split("\")
$last = ($pathIntoArray)[-1]
$last
House_Prediction_Using_Two_File_Dataset.pdf

For example:
To get last element in array, we can use following code:

Using -Split Operator

Use the -Split operator to split the path into an array in PowerShell.

$path = "C:\Users\John\Desktop\Samples\House_Prediction_Using_Two_File_Dataset.pdf"
$pathIntoArray = $path -Split "\\"
$pathIntoArray
C:
Users
John
Desktop
Samples
House_Prediction_Using_Two_File_Dataset.pdf

This example is similar to the previous one, but we used the -Split operator this time, which took a \ as an argument. Note that the \ must be doubled while using the -Split operator. Also, unlike the previous code fence, we stored the array in the $pathIntoArray variable.

You might wonder that if the -Split operator and Split() method perform the same thing, then why use them separately? You are correct that both split a string into an array of substrings, but some similarities and differences are listed below:

  • First, they have different syntax because Split() is a method and -Split is an operator; you can refer to the last two examples to understand it.
  • Both split the string based on the provided delimiter; however, the -Split operator can split based on the provided regular expressions, which makes it more powerful.
  • Both returns an array of strings; you can check the returned type using GetType() method. For example, $pathIntoArray.GetType().
  • Regarding performance, the Split() method is faster than the -Split operator, particularly when we split based on a single delimiter. However, -Split can be faster when splitting based on complex patterns since it allows a regular expression pattern as a delimiter.

Now, you know the similarities and differences between the -Split and Split(), so choose the one which best suits your project needs.

Until now, we learned how to split the path of the specified file into an array, but what if we are supposed to split the directory and path of the given file into separate arrays? What does it mean? Suppose we have C:\Users\John\Documents\file.txt path. Splitting the path into an array will result in C:, Users, John, Documents, and file.txt as array elements, while splitting the directory will have C:, Users, John, and Documents as array elements.

How to split the directory into an array? Let’s learn it in the following section.

Split Directory into Array in PowerShell

Using System.IO.Path Class

To split the directory and path of the specified file into separate arrays:

  • Store a path of a file in a variable.
  • Use GetDirectoryName() to retrieve the directory of the given file.
  • Chain the Split() method with the path variable created in the first step to get an array of the path.
  • Chain the Split() method with the directory variable created in the second step to get an array of the directory.
  • Use the Write-Host cmdlet to print the customized outcomes.
$path = "C:\Users\John\Desktop\Samples\House_Prediction_Using_Two_File_Dataset.pdf"
$directory = [System.IO.Path]::GetDirectoryName($path)
$pathIntoArray = $path.Split("\")
$directoryIntoArray = $directory.Split("\")
Write-Host "A path into an array:`n$pathIntoArray"
Write-Host "A directory into an array:`n$directoryIntoArray"
A path into an array:
C: Users John Desktop Samples House_Prediction_Using_Two_File_Dataset.pdf
A directory into an array:
C: Users John Desktop Samples

In the above output, the array elements are separated by a single whitespace. So how did we get these arrays? First, we stored the path of the House_Prediction_Using_Two_File_Dataset.pdf file in the $path variable. Next, we used the GetDirectoryName() method of the Path class, provided $path as a parameter to get the directory of the House_Prediction_Using_Two_File_Dataset.pdf file, which we stored in the $directory variable.

Next, we chained the Split() method with $path and $directory separately to get two different arrays stored in the $pathIntoArray and $directoryIntoArray variables. Remember, we passed \ to the Split() method as a delimiter. Finally, we used the Write-Host cmdlet to display customized output on the PowerShell terminal.

`n is a unique character in PowerShell; we used it with the Write-Host cmdlet to add a new line character.

Now, think of a situation where we want complete control over array elements. For example, we want to split the path into an array having parent, leaf, and qualifier as the array elements. What are they, and how can we do it? See the following section to learn.

Using Split-Path Cmdlet

Use the Split-Path cmdlet to retrieve various parts of the path to form an array in PowerShell.

$path = "C:\Users\John\Desktop\Samples\House_Prediction_Using_Two_File_Dataset.pdf"
$pathParent = Split-Path $path -Parent
$pathLeaf = Split-Path $path -Leaf
$pathQualifier = Split-Path $path -Qualifier
$pathIsAbsolute = Split-Path $path -IsAbsolute
$pathIntoArray = @("Parent of the path: $pathParent", 
                   "Leaf of the path: $pathLeaf",
                   "Qualifier of the path: $pathQualifier",
                   "Is the path absolute? (True/False): $pathIsAbsolute")
$pathIntoArray
Parent of the path: C:\Users\John\Desktop\Samples
Leaf of the path: House_Prediction_Using_Two_File_Dataset.pdf
Qualifier of the path: C:
Is the path absolute? (True/False): True

Again, we defined and initialized the $path variable. Then, we used Split-Path cmdlet four times; every time with a different parameter to get the specified part of the $path. These parameters include -Parent, -Leaf, -Qualifier, and -IsAbsolute. Using the -Parent parameter, retrieved the parent folder of the House_Prediction_Using_Two_File_Dataset.pdf file. It is the default parameter, which means we can get the parent folder even if we omit the -Parent parameter.

The -Leaf parameter provided us with the file name, while the -Qualifier retrieved the root directory of the specified file. Finally, the -IsAbsolute parameter returned a Boolean value, True if the path is an absolute path; otherwise, False. What is an absolute path? It is a complete file path from the root to the current file, such as C:\Users\John\Documents\file.txt.

For every parameter, we stored the returned value in a separate variable that is $pathParent, $pathLeaf, $pathQualifier, and $pathIsAbsolute that we enclosed within the array operator represented by @() to make an array from them. Finally, we stored this array in the $pathIntoArray variable.

While using the array operator (@()), we wrote a customized message to make every array element more understandable.

That’s split path into array in PowerShell.

]]>
https://java2blog.com/powershell-split-path-into-array/feed/ 0
Get Last Element of Array in PowerShell https://java2blog.com/get-last-element-of-array-powershell/?utm_source=rss&utm_medium=rss&utm_campaign=get-last-element-of-array-powershell https://java2blog.com/get-last-element-of-array-powershell/#respond Wed, 29 Mar 2023 10:18:04 +0000 https://java2blog.com/?p=23379 An array is a collection of data elements stored together under a single variable name. Unlike other programming languages, the array in PowerShell contains the values of the same or different data types. It is defined using square brackets [ ] with each element separated by a comma.

The array’s index starts with zero, meaning the array_name[1] represents the second element. One interesting fact is that if you want to retrieve the elements of the array from the last, you can use the minus sign with the index, e.g. the -1 index can be used to retrieve the last element, -2 retrieves the second last element so on and so forth.

Let’s take examples to understand the working of all the methods. For all the methods, the following steps will be followed:

  • Create an array (that is named as $array and contains the values @(1, 2, 3, 4, 5))
  • Get the last element from the array
  • Display the last element as output

Using $array[-1] Index Operator

Use the $array[-1] index operator to get last element of array in PowerShell.

$array = @(1, 2, 3, 4, 5)
$last = $array[-1]
Write-Host "Using the index operator: $last"
Using the index operator: 5

As discussed earlier, this method used the -1 index operator to get the last item in the array. This worked because in PowerShell, the index -1 represents the last item in the array.

Using $array[-1] Index Operator with Parentheses

Use the $array[-1] index operator with parentheses to get last element of array in PowerShell.

$array = @(1, 2, 3, 4, 5)
$last = ($array)[-1]
Write-Host "Using the index operator with parentheses: $last"
Using the index operator with parentheses: 5

This method used the $array[-1] index operator to get the last item in the array, but it also enclosed the array in parentheses to ensure that the index operator is applied to the array itself rather than any other expression that may be used.

Using Select-Object Cmdlet with -Last Parameter

Use the Select-Object cmdlet with the -Last parameter set to 1 to get last element of array in PowerShell.

$array = @(1, 2, 3, 4, 5)
$last = $array | Select-Object -Last 1
Write-Host "Using Select-Object: $last"
Using Select-Object: 5

In this method, the Select-Object cmdlet is used with the -Last parameter set to 1 to get the last item in the array. This cmdlet can select any number of items from an array, including the last.

Using $array.count Property & Index Operator

Use the $array.count property and index operator to get last element of array in PowerShell.

$array = @(1, 2, 3, 4, 5)
$last = $array[$array.count - 1]
Write-Host "Using the count property: $last"
Using the count property: 5

This method uses the .count property of the $array to get the total number of items, then subtracts 1 to get the index of the last item. It then used the index operator to get the last item in the array.

Using Array Class

Use the array class to get last element of array in PowerShell.

$array = @(1, 2, 3, 4, 5)
$last = $array[$array.Length - 1]
$array = $array[0..($array.Length - 2)]
Write-Host "Using an array class: $last"
Using an array class: 5

This method used the array class to access the Length property and subtracted 1 from it to get the index of the last element in the $array, which we stored in the $last variable. Next, we used the 0..($array.Length - 2) expression to create a range of indices from 0 to the second-to-last item in the $array.

The resulting range was used to select all the items of the original array, excluding the last one, which means we removed the last element from the $array using this expression. Finally, we used the Write-Host cmdlet to print the value of the $last variable.

Using Get_Item() Method

Use the Get_Item() method to get last element of array in PowerShell.

$array = @(1, 2, 3, 4, 5)
$last = $array.Get_Item($array.Length - 1)
Write-Host "Using the Get_Item() method: $last"
Using the Get_Item() method: 5

The Get_Item() method gets the item at a specified index from the array. The index, in this case, is calculated by subtracting 1 from the Length property of the $array, which gives the index of the last item.

That’s all about how to get last element of array in PowerShell.

]]>
https://java2blog.com/get-last-element-of-array-powershell/feed/ 0
Check if Array Contains Element in PowerShell https://java2blog.com/check-if-array-contains-element-powershell/?utm_source=rss&utm_medium=rss&utm_campaign=check-if-array-contains-element-powershell https://java2blog.com/check-if-array-contains-element-powershell/#respond Sun, 12 Mar 2023 18:47:47 +0000 https://java2blog.com/?p=22848 1. Overview

In this article, we will see different ways to check if array contains element in PowerShell using -contains operator, Contains() method, Where-Object cmdlet, -in operator, indexOf() method, and LINQ.

2. Introduction to Problem Statement

We are given an array and element. Our goal is to check if array contains the element.

For instance, given an array [PowerShell", "Java", "PHP"], we want to check if the string "Java" is an element of this array. This simple query opens up a range of important considerations such as case sensitivity and the ability to handle different data types.

3. Using -Contains Operator

The -contains operator performs a linear search through the array and returns $true if the element is found, $false otherwise. It is most straightforward and simple way to do it.

Let’s see -Contains operator with the help of example:

$array = @("PowerShell", "Java", "PHP")
$element= "Java"
if ($array -Contains $element) {
    Write-Host "The array contains the '$element'."
} else {
    Write-Host "The array does not contain the '$element'."
}
The array contains the 'Java'.

This operator is case-insensitive, which means Java, JAVA, and java are the same values.

Inside the if-else block, we used the Write-Hostcmdlet to print the customized message on the PowerShell console to let the user know if their specified match is found in the $array.

4. Using -in Operator

The in operator, introduced in PowerShell v3.0, is an alternative syntax to -contains.

This operation returns $true if element is in $array. It’s syntactically different but functionally similar to -contains.

$array = @("PowerShell", "Java", "PHP")
$element= "Java"
if ($element -in $array){
    Write-Host "The array contains the '$element'."
} else {
    Write-Host "The array does not contain the '$element'."
}
The array contains the 'Java'.

As this is similar to -contains operator, it is also case-insensitive, which means Java, JAVA, and java are the same values.

5. Using the IndexOf() Method with -ne Operator

The indexOf() method returns an index of the element if it exists. If specified element’s index is not -1, then it is in the array.

Let’s see with help of example:

$array = "PowerShell", "Java", "PHP"
$element= "PHP"
if ($array.IndexOf($element) -ne -1) {
    Write-Host "The array contains the '$element'."
} else {
    Write-Host "The array does not contain the '$element'."
}
The array contains the 'PHP'.

So here, the IndexOf() method takes a value and returns its index in the $array; it returns -1 if the specified element is not found.

This approach is case-sensitive means PHP and php are two different elements.

6. Using .Contains() Method

Another way to check for the presence of an element is using the .Contains() method. .Contains() method checks whether element exists in array or not.

$array = @("PowerShell", "Java", "PHP")
$element= "Java"
if ($array.Contains($element)){
    Write-Host "The array contains the '$element'."
} else {
    Write-Host "The array does not contain the '$element'."
}
The array contains the 'Java'.

Here, we used the .Contains() method, which does the same as the -Contains operator and determines if the $element exists in the $array, but it is case-sensitive.

7. Using Where-Object Cmdlet with Script Block

The Where-Object cmdlet offers a more flexible way to search arrays. It is case-insensitive by default. We can use -ceq operator for case-sensitive search.

$array = @("PowerShell", "Java", "PHP")
$element= "Java"
if ($array | Where-Object {$_ -eq $element}){
    Write-Host "The array contains the '$element'."
} else {
    Write-Host "The array does not contain the '$element'."
}
The array contains the 'Java'.

Let’s understand more about $array | Where-Object {$_ -eq $element}:

  • $array: This is the input array. It contains the elements that we want to check against the $element.
  • |: The pipe operator in PowerShell passes the output of one command as input to another command. Here, it passes each element of $array to the Where-Object cmdlet.
  • Where-Object: It’s a cmdlet used for filtering objects. It processes each object passed to it from the pipeline (in this case, each element of $array).
  • { $_ -eq $element }: This is the script block that defines the condition for filtering.
    • $_: This is a special variable in PowerShell that represents the current object in the pipeline. When used inside the script block of Where-Object, it refers to each element of $array as it’s processed.
    • -eq: This is the equality operator in PowerShell. It checks if the left-hand side (each element in $array) is equal to the right-hand side ($element).
  • The if Condition: The if statement evaluates the output of the Where-Object cmdlet. If Where-Object finds any elements in $array that match $element, it returns those elements, and the if condition is considered $true. If no elements match, the if condition is $false.

8. Using LINQ

LINQ queries offer powerful and efficient ways to work with collections in PowerShell.

[array]$array = "apple", "banana", "cherry"
$item = "banana"
if ([System.Linq.Enumerable]::Contains($array, $item)) {
    "The array contains the item."
} else {
    "The item is not in the array."
}

This method returns $true if the element is found in array. LINQ queries are known for their performance and are particularly useful for large data sets. It might be overhead to use it for small dataset.

9. Check if Element Starts with Substring in Array

We can use the -like operator to check if an array contains an element having a particular pattern.

Here is an example:

$array = @("PowerShell", "Java", "PHP")
$element= "J*"
if ($array | Where-Object {$_ -like $element}){
    Write-Host "The array contains the '$element'."
} else {
    Write-Host "The array does not contain the '$element'."
}
The array contains the 'J*'.

10. Custom Comparisons for Complex Object

When dealing with complex object, we might need to perform custom operations such as comparing the array based on property of PSCustomObject.

$person1 = [PSCustomObject]@{Name="John"; Age=30}
$person2 = [PSCustomObject]@{Name="Jane"; Age=25}
$myArray = $person1, $person2
$searchName = "Jane"
$result = $myArray | Where-Object { $_.Name -eq $searchName }

This script checks for an object with a specific Name property value in an array of custom objects.

11. Working with Different Data Types in Arrays

In PowerShell, an array is a data structure that can hold a collection of items. Unlike some programming languages that require all elements in an array to be of the same type, PowerShell arrays are versatile and can contain a mix of data types.

Example of mixed array:

$myArray = 42, "PowerShell", $true, 19.99

We can use -contains operator, .Contains() method or Where-Object cmdlet. These will work similar to what we have already discussed.

Please note that while checking if array contains any element, it also check for its datatype.

$myArray = 42, "PowerShell", $true, 19.99
$item = "42"
$result = $myArray.Contains($item)

Here, $result will be $false because "42" (string) is not the same type as 42 (integer).

If we change 42 to integer, it will return $true.

$myArray = 42, "PowerShell", $true, 19.99
$item = 42
$result = $myArray.Contains($item)

Here, $result will be $true now.

12. Conclusion

Throughout this article, we have explored a variety of methods to check if an array in PowerShell contains a specific element.

These methods range from the straightforward -contains and -in operators to the more complex Where-Object cmdlet and LINQ queries. Each method has its unique characteristics and best use cases.

The simplicity of the -contains and -in operators makes them ideal for quick checks and is particularly useful for their case-insensitive nature. For more precise, case-sensitive checks, the .Contains() method and indexOf() offer a direct approach, with the latter providing additional information about the element’s position in the array.

]]>
https://java2blog.com/check-if-array-contains-element-powershell/feed/ 0
PowerShell Array to String https://java2blog.com/convert-array-object-to-string-powershell/?utm_source=rss&utm_medium=rss&utm_campaign=convert-array-object-to-string-powershell https://java2blog.com/convert-array-object-to-string-powershell/#respond Thu, 09 Mar 2023 19:07:46 +0000 https://java2blog.com/?p=22170 Using Double Quotation Marks

Use double quotation marks to convert array object to string in PowerShell.

$arrayObject = "How", "are", "you?"
$arrayString = "$arrayObject"
$arrayObject.GetType()
$arrayString.GetType()
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                                 --------
True     True     Object[]                                 System.Array
True     True     String                                   System.Object

First, we created an array object and saved it in the $arrayObject variable; we can also create an array object using the array operator (@()), for instance, $arrayObject = @("How", "are", "you?"). Next, we enclosed the $arrayObject variable within double quotes and saved the updated value in the $arrayString variable.

Afterwards, we chained the GetType() method with $arrayObject and $arrayString to know their data types. For example, see the Name column in the above output; we have successfully converted the array object to a string. Now, we can print the value of $arrayString to see what the converted string looks like; see the following example.

$arrayString
How are you?

From now on, we will only discuss the function, variable, cmdlet, and operator that we used to convert the array object to a string; we will not explain the array creation and GetType() method as we have already covered them in this section. So, let’s continue with the remaining sections.

Using Type Casting / Explicit Conversion

Use type casting (explicit conversion) to convert an array object to a string.

$arrayObject = "How", "are", "you?"
$arrayString = [string]$arrayObject
$arrayObject.GetType()
$arrayString.GetType()
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                                  --------
True     True     Object[]                                 System.Array
True     True     String                                   System.Object

Here, we used the explicit conversion of an array object to a string. We can also call it typecasting because we are casting (changing) the data type from one to another.

We specified the [string] immediately followed by $arrayObject to cast the data type from array object to string and saved it $arrayString variable. So now, the $arrayString has the following string.

$arrayString
How are you?

Using -join Operator

Use the -join operator to convert an array object to a string.

$arrayObject = "How", "are", "you?"
$arrayString = $arrayObject -join " "
$arrayObject.GetType()
$arrayString.GetType()
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                                 --------
True     True     Object[]                                 System.Array
True     True     String                                   System.Object

For this section, we used the -join operator, which joins the array elements using the specified separator. The separator can be a letter, number, or a specific character; however, we used a single white space to join/concatenate array elements. Now, the value of $arrayString looks as follows.

$arrayString
How are you?

Using Join() Function

Use the Join() function to convert an array object to a string.

$arrayObject = "How", "are", "you?"
$arrayString = [system.String]::Join(" ", $arrayObject)
$arrayObject.GetType()
$arrayString.GetType()
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                                 --------
True     True     Object[]                                 System.Array
True     True     String                                   System.Object

This code fence is similar to the previous one, where we used the -join operator. But here, we used the Join() function, which also did the same, joining all elements of the array using the specified separator. So now, $arrayString looks like the below.

$arrayString
How are you?

Using Out-String Cmdlet

Use the Out-String cmdlet to convert an array object to a string.

$arrayObject = "How", "are", "you?"
$arrayString = $arrayObject | Out-String
$arrayObject.GetType()
$arrayString.GetType()
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                                 --------
True     True     Object[]                                 System.Array
True     True     String                                   System.Object

Here, we used Out-String cmdlet which outputs the received input objects as a string. We used pipe sign (|) to forward the data of $arrayObject to the Out-String.

This approach displays an output which differs from the previous methods. It converts every array element to a string; see the following output.

$arrayString
How
are
you?

Using $OFS Variable

Use the $OFS variable to convert an array object to a string.

$arrayObject = "How", "are", "you?"
$OFS = ','
$arrayString = "$arrayObject"
$arrayObject.GetType()
$arrayString.GetType()
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                                 --------
True     True     Object[]                                 System.Array
True     True     String                                   System.Object

This code example is similar to the first section, where we used double quotation marks to convert an array object to a string. However, with $OFS (output field separator), we can use a separator of our choice without using the -join operator or Join() function.

After using the $OFS variable, all casts will have a separator that we assigned to the $OFS variable until $OFS changes. This time, the $arrayString will look as below.

$arrayString
How,are,you?

That’s all about PowerShell Array to String,

]]>
https://java2blog.com/convert-array-object-to-string-powershell/feed/ 0
Compare Arrays in PowerShell https://java2blog.com/compare-arrays-powershell/?utm_source=rss&utm_medium=rss&utm_campaign=compare-arrays-powershell https://java2blog.com/compare-arrays-powershell/#respond Tue, 14 Feb 2023 12:34:03 +0000 https://java2blog.com/?p=22616 In this post, we will see how to compare Arrays in PowerShell.

PowerShell supports arrays with one or more dimensions and zero to many elements in each dimension. Elements inside a dimension are numbered from 0 in ascending integer order. In addition, the array subscript operator [] allows access to any particular element. PowerShell may be used in a variety of ways to compare arrays. Following are a few of them.

Compare Arrays of Strings

If you have two arrays containing strings, we may compare them with PowerShell in one of the simplest ways possible. We can compare the strings in the arrays in a few different ways when we find ourselves in this situation; below are a few methods to compare arrays of strings.

  • Using Where-Object Cmdlet with in operator
  • Using the Compare-Object Cmdlet
  • Using the -contains Operator
  • Using the -in Operator

Use Where-Object Cmdlet with in operator

Use the Where-Object cmdlet to compare arrays in PowerShell.

$array1 = "Monday", "Tuesday", "Wednesday", "Thursday"
$array2 = "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
$array1 | Where-Object -FilterScript { $_ -in $array2 }
Wednesday
Thursday

The sole purpose of the PowerShell Where-Object cmdlet was to filter a command’s output so that only the data you desire is returned. A script block is an anonymous function. Therefore, you would use the -FilterScript parameter to employ a script block as a filter. This parameter enables you to write a script block, which can then be passed to the FilterScript and performed in the where- object cmdlet.

The-in operator means the value is in a collection and returns property value if a match is found. The pipeline variable $_ is a particular variable in PowerShell used to represent the current object. So we got the output Wednesday and Thursday from both arrays where the match was found.

Use the Compare-Object Cmdlet

Use the Compare-Object cmdlet to compare arrays in PowerShell. The Compare-Object cmdlet compares two sets of objects. One set of objects is the reference, and the other set of objects is the difference.**

$array1 = "Monday", "Tuesday", "Wednesday", "Thursday"
$array2 = "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
Compare-Object -ReferenceObject $array1 -DifferenceObject $array2
InputObject SideIndicator
----------- -------------
Friday      =>
Saturday    =>
Sunday      =>
Monday      <=
Tuesday     <=

We used the Compare-Object cmdlet in PowerShell to compare the specified arrays. Using a -ReferenceObject and a DifferenceObject, this cmdlet can determine which elements are present in each array and which are not. The => is the SideIndicator property indicates that the returned InputObject property is in the DifferenceObject value rather than the ReferenceObject value, while the <= means the opposite.

Use the -Contains Operator

Use the -Contains operator to check if the specified string is part of the other array in PowerShell.

$array = @('potato', 'onion', 'peas', 'carrot')
$array -contains 'onion'
True

PowerShell’s -Contains operator enables you to determine whether an item is a part of a collection. Although the -Contains operator doesn’t, by default, understand collections, you can write code to make it perform what you want. PowerShell can use this operator to check a single item in an array. It returns True if it is present in the array; else, it returns False.

Let’s create two arrays to check the command strings of both arrays.

$array1 = @('potato', 'onion', 'carrot')
$array2 = @('peas', 'cauliflower', 'potato')
$array1 | ForEach-Object {
    if ($array2 -contains $_) {
        Write-Host "$array2 has the $array1 string [$_]"
    }
}
$array2 has the $array1 string [potato]

The ForEach-Object cmdlet operates on every item in a collection of input objects. The input objects can also be piped to the cmdlet or specified using the InputObject parameter. We used it to iterate over the array1. We used the if statement with the -contains operator for each iteration to check if array2 also has that element. If so, we used the Write-Host cmdlet to print the customized output, as shown above.

Use the -in Operator with ForEach-Object

Use the -in operator to check if the specified string is part of the other array in PowerShell.

$array1 = @('potato', 'onion', 'carrot')
$array2 = @('peas', 'cauliflower', 'potato')
$array1 | ForEach-Object {
    if ($_ -in $array2) {
        Write-Host "$array2 has the $array1 string [$_]"
    }
}
$array2 has the $array1 string [potato]

This code is similar to the previous example but uses the -in operator for this code, which is equivalent to the -contains operator but has the opposite syntax. The array was defined on the left side when the -contains operator was used. This time, the array is specified on the right side using the -in operator, as seen above.

Compare Arrays of custom object

Use Compare-Object to compare an array of custom objects. The Compare-Object cmdlet compares two sets of objects. One set of objects is the reference, and the other set of objects is the difference.

$ArrayObject1 = @(
[PSCustomObject]@{Name = "John"; Age = 30},
[PSCustomObject]@{Name = "Martin"; Age = 25}
)

$ArrayObject2 = @(
[PSCustomObject]@{Name = "John"; Age = 30},
[PSCustomObject]@{Name = "Sam"; Age = 40}
)

Compare-Object -ReferenceObject $ArrayObject1 -DifferenceObject $ArrayObject2 -Property Name, Age
Name Age SideIndicator
---- --- -------------
Name   Age SideIndicator
----   --- -------------
Sam     40 =>
Martin  25 <=

Above code will provide you difference between two arrays.
<= denotes if element is only present in ReferenceObject
=> denotes if element is only present in DifferenceObject

That’s all about how to compare Arrays in PowerShell.

]]>
https://java2blog.com/compare-arrays-powershell/feed/ 0