Error Handling and Exporting Active Directory Users to CSV

Error Handling and Exporting Active Directory Users to CSV

  • Comments 1
  • Likes

 

Summary: Learn how to handle errors in Windows PowerShell and how to export user information from Microsoft Active Directory to a CSV file.

 

In this post:

 

 

Exporting Active Directory Users to CSV

Hey, Scripting Guy! QuestionHey, Scripting Guy! I was reading your TechNet blog here and I had a question. Is there a way to use the method below and export it into a .csv or .xls file?

Get-ADUser -Filter * -Properties "LastLogonDate" | 

sort-object -property lastlogondate -descending | 

Format-Table -property name, lastlogondate -AutoSize

-- DJ

 

Hey, Scripting Guy! AnswerHello, DJ. It is very easy and useful. All I had to do is add the Export-CSV command to your code. This is seen here.

Get-ADUser -Filter * -Properties "LastLogonDate" | 

sort-object -property lastlogondate -descending | 

Export-CSV -path c:\fso\adusers.csv -notypeinformation

 

You would substitute a valid path to save your CSV file to. The -notypeinformation parameter is required to prevent the first row of your file being consumed by type information. You only want the data. After you have done this, you can double-click the CSV file and open it up in Microsoft Excel.

Of course, if you run the code now, an error will display because you have not loaded the Active Directory module into your Windows PowerShell console. Use the Import-Module cmdlet to complete this task. The good thing is that you can use wildcard characters with Import-Module and therefore the command Import-Module *active* will work. After the module has loaded, the Get-ADUser Windows PowerShell cmdlet is available. I copied the three commands and pasted them into the Windows PowerShell console. Windows PowerShell recognized the pipeline character, (the | symbol at the end of each line) . This means that there was more to the command. Therefore, each line is preceded by the double arrow >> to let me know that there is more code needed. At the final >> I just pressed Enter and submitted the code. This is shown in the following figure.

 

 

After I have run the code, I can open the c:\fso\adusers.csv file directly in Microsoft Excel. This is seen in the following figure.

 

 

 

Adding Comments to a Script File

Hey, Scripting Guy! QuestionHey, Scripting Guy! Thanks for putting the great wealth of information about scripting on your website. I am not really a Scripting aficionado, but I use some simple ones occasionally. I am accustomed to using batch files were I can place text non-operative in the body of the file for future reference. Try as a might, I could not find a way to do that with a .vbs file.

This is the file I am using to create a Restore Point:

Wscript.echo "This is a script file to create a Restore Point PRESS OK TO START"
Set IRP = getobject("winmgmts:\\.\root\default:Systemrestore")
MYRP = IRP.createrestorepoint ("My Restore Point", 0, 100)

 I want to add 3 or 4 lines of text in the file that will not affect its operation, and am hoping it can be done. In addition, I guess if anyone can tell me how I think it would be you guys.

-- BC

 

Hey, Scripting Guy! AnswerHello, BC. In VBScript there are two ways to add comments, or remarks, to a script file. The first way is to use the REM command. This command has actually been used in multiple languages, and it is an abbreviation for "remark." In practice, it would look like the following:

REM "This is a remark or a comment"

Wscript.Echo "Hello World"

 

A better way to do a comment in VBScript, better because it takes less typing, is to use the single quotation mark. Be aware that Microsoft Word uses "smart quotes" by default. Smart quotes differ from the straight quotation mark, and will make VBScript throw an error.

' This is a comment. Note it does not need double quotes for the string.

Wscript.Echo "Hello World"

 

In Windows PowerShell the comment character is the number sign. This is seen here.

# This is a comment

write-host "Hello World"

 

Windows PowerShell 2.0 added the capability to have a comment that spans multiple lines.

It uses a combination of tags that open the comment <# and the close the comment #> characters as

seen here.

<# This is a comment

   That spans multiple lines

#>

write-host "Hello World"

 

 

Error Handling in Windows PowerShell

Hey, Scripting Guy! QuestionHey, Scripting Guy! Do you know the reasoning behind Windows PowerShell not having a fully functional equivalent to VBScript Option Explicit? Seems like a feature I would expect in any industrial strength scripting language. I've seen the limited functionality that is provided, but I do not believe that the following error seen here would be caught.

 $myVariable = 42

$myVairable = 50

$myVariable

(Obviously simplified -- if somewhere I wanted to reset the value of $myVariable to 50, but I fumblefinger the spelling, I end up with 42 and a really tough bit of debugging; in vbscript, option explicit would have thrown an error with an undeclared variable (the alternative spelling: $myVairable)).

-- MM

 

Hey, Scripting Guy! AnswerHello, MM. In VBScript, if I use the following, the value 50 is displayed.

variable = 50

varable = 52

WScript.Echo variable

 

When I set Option Explicit I now have to dim each variable. This is seen here.

Option Explicit

Dim variable

variable = 50

varable = 52

WScript.Echo variable

 

When I run this code, an error message is displayed.

Microsoft VBScript runtime error: Variable is undefined: 'varable'

 

Windows PowerShell has a similar command: Set-PSDebug -Strict

Here is an example of how to use it in a script.

Set-PSDebug -Strict

$myvariable = 50

$myvar

When I run this, I get the following error (because $myvar is not initialized.)

The variable '$myvar' cannot be retrieved because it has not been set.

At line:3 char:7

+ $myvar <<<<

    + CategoryInfo          : InvalidOperation: (myvar:Token) [], RuntimeExcep

   tion

    + FullyQualifiedErrorId : VariableIsUndefined

To turn off PSDebug, then I use the -off switch. This is seen here.

Set-PSDebug -Off

$myvariable = 50

$myvar

 

When I run this, I get no output whatsoever because I am not displaying the contents of the $myvariable, and I have not set any contents for the $myvar variable.

If on the other hand, I reassign a new value to $myvar, Instead of $myvariable, as you implied in your question, that is an allowed command. All the strict mode does is throw an error if a variable is referenced before a value is assigned to the variable.

In Windows PowerShell 2.0 the Set-StrictMode Windows PowerShell cmdlet is used to catch additional errors. When you use it, you must tell it what mode that you want for it to use. You can make it behave like Windows PowerShell 1.0's Set-PSDebug -strict and it will only check for uninitialized variables. It does not check for uninitialized variables inside a string. This is illustrated here.

PS C:\> Set-StrictMode -Version 1

PS C:\> $a = "string"

PS C:\> $b

The variable '$b' cannot be retrieved because it has not been set.

At line:1 char:3

+ $b <<<<

    + CategoryInfo          : InvalidOperation: (b:Token) [], RuntimeException

    + FullyQualifiedErrorId : VariableIsUndefined

 

PS C:\> "This is $b"

This is

PS C:\>

 

This behavior is the same as the Set-PSDebug -Strict command seen earlier.

PS C:\> Set-PSDebug -Strict

PS C:\> $a = "string"

PS C:\> $b

The variable '$b' cannot be retrieved because it has not been set.

At line:1 char:3

+ $b <<<<

    + CategoryInfo          : InvalidOperation: (b:Token) [], RuntimeException

    + FullyQualifiedErrorId : VariableIsUndefined

 

PS C:\> "This is $b"

This is

PS C:\>

 

If I use Set-StrictMode with either -version 2 or -version latest, it will catch uninitialized variables inside strings also. This is seen here.

PS C:\> Set-StrictMode -Version latest

PS C:\> $a = "string"

PS C:\> $b

The variable '$b' cannot be retrieved because it has not been set.

At line:1 char:3

+ $b <<<<

    + CategoryInfo          : InvalidOperation: (b:Token) [], RuntimeException

    + FullyQualifiedErrorId : VariableIsUndefined

 

PS C:\> "This is $b"

The variable '$b' cannot be retrieved because it has not been set.

At line:1 char:11

+ "This is $ <<<< b"

    + CategoryInfo          : InvalidOperation: (b:Token) [], RuntimeException

    + FullyQualifiedErrorId : VariableIsUndefined

 

PS C:\>

 

On the other hand, it does not catch the situation when you misspell a variable while assigning a value to it. This is seen here.

PS C:\> $myvariable = 50

PS C:\> $myvar

The variable '$myvar' cannot be retrieved because it has not been set.

At line:1 char:7

+ $myvar <<<<

    + CategoryInfo          : InvalidOperation: (myvar:Token) [], RuntimeException

    + FullyQualifiedErrorId : VariableIsUndefined

 

PS C:\> $myvar = 12

PS C:\> $myvariable

50

PS C:\>

 

There are a couple of additional things that the Set-StrictMode cmdlet does that make it a great addition to a script. It will throw an error when you try to access a nonexistent property. This is illustrated here where I reference the bogusProperty of a string object.

PS C:\> Set-StrictMode -Version latest

PS C:\> $a = "string"

PS C:\> $a.Length

6

PS C:\> $a.bogusProperty

Property 'bogusProperty' cannot be found on this object. Make sure that it exists.

At line:1 char:4

+ $a. <<<< bogusProperty

    + CategoryInfo          : InvalidOperation: (.:OperatorToken) [], RuntimeExcept

   ion

    + FullyQualifiedErrorId : PropertyNotFoundStrict

 

PS C:\> Set-StrictMode -Version 1

PS C:\> $a = "string"

PS C:\> $a.Length

6

PS C:\> $a.bogusProperty

PS C:\>

 

In addition, when the Set-StrictMode cmdlet sets the version to latest (or 2 which is the latest version of Windows PowerShell) it will also prevent you from calling a function as if it were a method. If your function only has a single input, you can still call it as if it were a method. This check only applies to functions that accept multiple inputs. This is seen here.

PS C:\> Set-StrictMode -Version 2

PS C:\> Function AddOne { Param ($i) $i + 1 }

PS C:\> AddOne(5)

6

PS C:\> Function AddTwo { Param ($i,$j) $i + $j + 1 }

PS C:\> AddTwo(4,5)

The function or command was called as if it were a method. Parameters should be sepa

rated by spaces. For information about parameters, see the about_Parameters Help top

ic.

At line:1 char:7

+ AddTwo <<<< (4,5)

    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException

    + FullyQualifiedErrorId : StrictModeFunctionCallWithParens

 

PS C:\> AddTwo 4 5

10

PS C:\> AddTwo -i 4 -j 5

10

PS C:\>

 

Well, this concludes another edition of Quick Hits Friday. Join me tomorrow for the Weekend Scripter when I have a fascinating guest blog by Dennis Whitney. He will be talking about how to use Windows PowerShell to work with a huge query completion system. It is really cool stuff.

I would love you to follow me on Twitter or Facebook. If you have any questions, send email to me at scripter@microsoft.com or post them on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

 

Ed Wilson, Microsoft Scripting Guy

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment