Powershell

What is @() in PowerShell Script?

Being a scripting language, PowerShell does support arrays. In PowerShell, the “@” refers to an array whereas the “@()” denotes an empty array. The @() also refers to an array subexpression operator.

PowerShell has scripting support which has made it in line with other scripting languages. Keeping in view the importance of the @() and scripts, we have prepared a guide that demonstrates the usage of the @() in PowerShell scripts. The outcomes of this guide would be:

  • What is @() in PowerShell
  • Create an empty array using @()
  • Create a numeric array using @()
  • Create an array of strings using @()

What is @() in PowerShell Script?

The array @() which is called the subexpression operator is utilized to create an empty array. By default @ does not mean an array in fact @(will open an array of sub-expression and closes it).

Syntax
The syntax of the array sub-expression operator is given below.

> $array = @()

Example 1: Create an empty array using

PowerShell ISE is mainly used for creating, deleting, and editing scripts. Here, we are using the PowerShell ISE to create an empty array.

In the example code, the $array stores the value of the @() and the the count property is used to get the number of objects stored in @():

> $array = @()
> $array.GetType()

Let’s run the script:

It is observed from the output that the type of the $array variable is an array.

Example 2: Create an array of strings using @()

The array of strings can be created using the @() sub-expression array. In the below example, we have created a strings array and used GetType() command to check the type of that created array

> $a = @("ABC", "DEF")
> $a.GetType()

The script is executed by providing the complete path where the script is stored.

The output shows that an array is returned.

Example 3: Create a numeric array using @()

The array sub-expression “@()” can be used to create an array of numbers. In the below example, we have created an array of numbers and used the GetType() command to get the array type.

> $b = @(1,2,3)
> $b.GetType()

Run the script from the PowerShell console:

The output has returned that the variable type of “$b” is an array.

This article has provided information about the “@()” operator.

Conclusion

The @() operator functions like a subexpression. However, it ensures to return of an array object. The array subexpression operator @() is mainly used for creating an empty array. It takes an input inside its parentheses and produces the output. This article has all the necessary information covered about the @() operator. Additionally, a few examples are also illustrated to create arrays of numbers/strings using @().

About the author

Adnan Shabbir