# Variables in Powershell
by Seth Kenlon

In computer science (and casual computing), a variable is a location in memory that holds arbitrary information for later use.
In other words, it's a temporary storage container for you to put data into and get data out of.
In the Bash shell, that data can be a word (a *string*, in computer lingo) or a number (an *integer*).

You may have never [knowingly] used a variable before on your computer, but you probably have used a variable in some other area of your life.
When you say things like "give me that" or "look at this", you're using grammatical variables (you think of them as *pronouns*), because the meaning of "this" and "that" depends on whatever you're picturing in your mind or whatever you're pointing to as an indicator for your audience to know what you're referring to.
When you do math, you use variables to stand in for some unknown value, even though you probably don't call it a variable.

This article addresses variables in Powershell running on Windows, Linux, or Mac.
Users of the open source [Bash](https://www.gnu.org/software/bash/) should refer to my article about [variables in Bash](LINK TO MY BASH VARIABLE ARTICLE).

The examples in this article are from a Powershell session running on the open source operating system Linux, so if you're on Windows or Mac then the file paths will differ.
However, Windows converts ``/`` to ``\`` automatically, and all examples work across all platforms, provided you substitute obvious differences (for instance, it is statistically unlikely that your username is ``seth``).


## What are variables for?

Whether you need variables in Powershell depends on what you do in a terminal.
For some users, variables are an essential means of managing data, while for others they're minor and temporary conveniences, and for still others they may as well not exist.
Ultimately, variables are a tool.
You can use them when you find a use for them, or leave them alone in the comfort of knowing they're being managed by your OS.
Knowledge is power, though, and understanding how variables work in Bash can lead you to all kinds of unexpected creative problem solving.


## How to set a variable

You don't need special permissions to create a variable.
They're free to create, free to use, and generally harmless.
In Powershell, you can create a variable by defining a variable name, and then setting its value, with the ``Set-Variable`` command.
This creates a new variable called ``FOO`` and sets the value to the string ``$HOME/Documents``:

```
PS> Set-Variable -Name FOO -Value "$HOME/Documents"
```

Success is eerily silent, so you may not feel confident that your variable got set.

You can see the results for yourself with the ``Get-Variable`` (``gv`` for short) command.
To ensure that the variable is read exactly as you defined it, you can also wrap it in quotes.
This preserves any special characters that might appear in the variable; in this example, that doesn't apply, but it's still a good habit to form.

```
PS> Get-Variable "FOO" -valueOnly
/home/seth/Documents
```

Notice that the contents of ``FOO`` aren't exactly what you set previously.
The literal string you set for the variable was ``$HOME/Documents``, but now it's showing up as ``/home/seth/Documents``.
This is because you can nest variables.
The ``$HOME`` variable points to the current user's home directory, whether it's ``C:\Users`` on Windows, ``/home`` on Linux, or ``/Users`` on Mac.
Since ``$HOME`` was embedded in ``FOO``, it gets "expanded" when recalled.
Using default variables in this way is one way to write portable scripts that operate across platforms.

Variables usually are meant to convey information from one system to another.
In this simple example, your variable is not very useful, but it can still communicate information.
For instance, because the contents of the ``FOO`` variable is a [file path](https://opensource.com/article/19/8/understanding-file-paths-linux), you can use it as a shortcut to the directory its value references.
To reference the *contents* of the variable ``FOO`` and not the variable itself,  prepend the variable with a dollar sign (``$``):

```
PS> pwd
/home/seth
PS> cd "$FOO"
PS> pwd
/home/seth/Documents
```

## How to clear a variable

You can remove a variable with the ``Remove-Variable`` command:

```
PS> Remove-Variable -Name "FOO"
PS> gv "FOO"
gv : Cannot find a variable with the name 'FOO'.
[...]
```

In practise, this is not usually necessary.
Variables are relatively "cheap", so you can create them and forget them when you don't need them any more.
However, there may be times you want to ensure a variable is empty to avoid conveying information to some other process that might read the variable.


## Creating a new variable with collision protection

Sometimes, you may have reason to believe a variable has already been set by you or some other process.
If you would rather not override it, you can either use ``New-Variable``, which is designed to fail if a variable with the same name already exists, or you can use a conditional statement to check for a variable first.
In these examples, assume ``FOO`` is set to ``/home/seth/Documents``.

Using the ``New-Variable`` command:

```
PS> New-Variable -Name FOO -Value "example"
New-Variable : A variable with name 'FOO' already exists.
```

Alternately, you can construct a simple ``if`` statement to check for an existing variable:

```
PS> if ( $FOO )
>> { gv FOO } else
>> { Set-Variable -Name "FOO" -Value "quux" }
```


## Adding to a variable

Instead of overwriting a variable, you can add to an existing one.
In Powershell, variables have diverse types: they can be typed as a string, integer, array, and more.
When choosing to create a variable with, essentially, more than one value, you must decide whether you need a character-delimited string or an array.
You may not care one way or the other, but the application meant as the recipient of the data you're storing in the variable may expect one or the other, so make your choice based on your target.

To append data to a string variable, you can use the ``=+`` syntax:

```
PS> gv FOO
foo
PS> $FOO =+ "$FOO,bar"
PS> gv FOO
foo,bar
PS> $FOO.getType().Name
String
```

Arrays are special types of variables in Powershell, and require an ArrayList object.
That's out of scope for this article, as it requires delving deeper into the .NET internals of Powershell.


## Environment variables

So far the variables you've created along with this article have been local variables.
That means that they apply only to the Powershell session you create them in.
To create variables that are accessible to other processes, you can create environment variables, which will be covered in a future article.
In the mean time, try using some variables for everyday tasks to see what they bring to your workflow.