PowerShell 101 for Messaging Administrator and IT Pros (Part 5)

If you would like to read the other parts in this article series please go to:

Introduction

PowerShell is just awesome and as soon as you start getting used to it you will keep going and going. An example was this article, in my humble experience I thought I could give away some hints in two articles, but then I started linking contents to make more sense and here we go on to the 5th article of the series, and if I don’t finish right now we could go easily to 12..20 articles. There is no way to learn PowerShell by just reading, you need to practice, challenge yourself, that’s the best way to get a good understanding of PowerShell.

Importing and exporting using PowerShell…

During a script creation the process to import and export data is crucial. We saw before how to Export-CSV cmdlet which basically redirect the output to a CSV file that can be easily visualized using Notepad, Excel and etc.

The import process is really simple and for that we can use Import-CSV cmdlet. We can build our own file and define the information, and then a script can read that file and take the defined actions. A good example is when an administrator provides a list of the mailboxes to be migrated, or to be exported to a PST, or even to be hidden from Global Address List. The point here is that we will learn how to use a csv file that can be used in your PowerShell and Scripts.

The first thing is the format, basically we can start a file from scratch and each column will be separated by a comma (,). The first line is the most important because it defines the name that PowerShell will use afterwards. In Figure 01 we create a simple file (called file.txt) and we added two columns called Column1 and Column2 and in the lines below we add with our values always using comma to separate. Then after saving the file we went to the PowerShell and we ran $<variable> = Import-CSV <file-name> and finally to show the content that was loaded into that value we ran $vTemp which was the variable that we used in this example, and here we go we have all the values.


Figure 01

The column names is up to you but they are essential. Let’s create a third column that will tell us if we want to hide the guy from the Global Address List, and let’s also rename the first two columns to Name and mail. Let’s also load the same file in the same variable (Figure 02), now we can see that the new columns name show up properly.


Figure 02

When using variables that were loaded with a CSV file a good Alias to known is ForEach (ForEach-Object is the cmdlet). Basically if we just type in $vTemp we are going to have the content of the variable which is the entire file in the console output. Using ForEach we can go line by line and use If statement and any sort of code that you want to. For the sake of simplicity we are using a simple If and a single action, but we can write the same thing in a script and have the same results.

The syntax for ForEach is:

ForEach {

                <commands>

}

In our Figure 03, we basically go line by line of our variable and we check if the column Hide has the value of Yes, and if it does we display the Name and a text. In the same line we could use the Set-Mailbox $_.Name –HiddenFromAddressListsEnabled $true to define the setting. If we need to do that for 150 users and you have the names, you can finish with a single line. Cool, isn’t it?

$vTemp | ForEach { If ($_.Hide –eq ‘Yes’) {Write-Host “User” $_.Name “ will be set to $True”} }


Figure 03

Alias in PowerShell

Like *nix systems, our new friend PowerShell provides the Alias support which is pretty handy when you want to use the same long cmdlet a lot but want to save time typing it in. A good example of useful alias are FL which is Format-List and Select which is Select-Object, by the way we are going to cover both on the next section.

So, how do we know the alias? That is pretty simple, just run Get-Alias in your PowerShell and voilà you have a list of all current Alias which you can use any time. If you want to be more specific you can use Get-Alias <Alias> (example Get-Alias FL).

In some cases you may want to create your own. A good example is the nice but awful family of cmdlets related to the great feature DatabaseAvailabilityGroup. Just for fun, let’s create an Alias named Get-DAG and it will be an Alias for Get-DatabaseAvailabilityGroup, much easier, right? This task can be accomplished by running the following cmdlet and the results can be seen in Figure 04.

New-Alias –Name Get-DAG –Value Get-DatabaseAvailabilityGroup –Descripton “Get DAG info”


Figure 04

So far the Alias that we created will be good just for the current session, we have a couple of ways to keep them around, the first one is to export to a file and import when we need to. This scenario is good when you have a lot of servers and you want to import your aliases from the network when you need them. This can be accomplished by using Import/Export-Alias cmdlets; or the second one, which is to add the alias to your profile of that server, and every time that you open a Shell on that server your Alias will be available for you.

In order to find out your profile just run write-host $PROFILE using your Exchange Management Shell, and then run notepad $profile (if there is no such file you can say Yes to create it) as shown in Figure 05. After that type in your favourite Aliases and save them, close your session and open it again and here you are with all short aliases for your day to day tasks.


Figure 05

Running your scripts using Tasks

Let’s use a simple script based on what we have seen so far to build a script that generates a report of all mailbox sizes on the current server. To be a little bit fancier we use a variable $vHostName which receives the content of hostname which is the Server Name, so we can use the same script in different mailbox servers without changing anything.

Our script (Figure 06) will use a series of pipes and save the output on C:\Temp\rp.csv. We could use Send-MailMessage afterwards as well. Note: We use –NoTypeInformation option to avoid the first line that contains information and doesn’t help us with anything at this point.


Figure 06

But the thing is, we want to automate this process, and we can generate a report file or even send by e-mail if we want to. Let’s create a task first following these procedures:

  1. Open Tasks Scheduler

  2. Click on Task Scheduler Library

  3. Create a Basic Task. Let’s use the name Mailbox Report for our new task, click Next

  4. Task Trigger page. Let’s select weekly and click Next

  5. Weekly page. Let’s select Monday at 11PM and click Next

  6. In the Action page. Select Start a program and click Next

  7. In the Start a Program page. Let’s use the following string for Program/Script field

%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe

And the following string on the Add Arguments (optional)

-command “. ‘C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1’; Connect-ExchangeServer -auto;c:\temp\rpt.ps1 “

The result will be similar to the Figure 07


Figure 07

After finishing up creating the new Task, we can right click on it and click Run, and the result after a couple of minutes should be “The operation completed successfully” on the last Run Result column.

Now that we know that the Task works, we just need to set up the Security of the task to run under a user with privileges and that’s it.

Logging the activity using Transcript…

As an IT pro probably you may end it up creating scripts for some of your customers and, it’s really important and highly recommended to keep track of all your changes when using PowerShell. Fortunately, we can address this issue with just two cmdlets: Start-Transcript and Stop-Transcript.

The Start-Transcript has a couple of options and by default it rewrites the log information when it runs. A good practice, if you need to keep track of everything, is to add –Append to make sure that the log file is not rewritten. A simple script using *-Transcript cmdlet is shown in Figure 08.


Figure 08

After running the script we can check the log file generated (Figure 09) and besides the information generated by the script we have initial information containing the details of the user who ran the script and machine name as well.


Figure 09

Conclusion

In this final article we went through the process to create a task for our scripts, how to use Transcript to log activities, and also import, export and alias cmdlets. We reviewed a lot of content in just 5 articles and I hope that these articles shed some light on the topic and how you can use it to improve your time managing Exchange Server.

Leave a Comment

Your email address will not be published.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Scroll to Top