Debugging A PowerShell String

A friend had asked for some assistance with a script that was adding objects into Active Directory. It was failing to create Active Directory groups – “Invalid DN Syntax” was the descriptive message we received.

However the DN syntax appeared to be valid:

image

And when we copied and pasted the text from $groupname it worked fine…

image

So what was the difference?

To find if the strings were different we did a compare:

image

OK, trimmed they match. But when we surrounded $groupname with exclamation points there weren’t any spaces or tabs…

To find out why we check the string at byte level. To do this we used:

[System.Text.Encoding]::Unicode.GetBytes($groupname)

Broken Working

77
0
121
0
65
0
68
0
71
0
114
0
111
0
117
0
112
0
13
0

77
0
121
0
65
0
68
0
71
0
114
0
111
0
117
0
112
0

We can see the broken one has a carriage return at the end ( In PowerShell “`r” )

The problem was a file had been retrieved split by line feed ( In PowerShell “`n”) But Windows text files usually end in Carriage Return + Line Feed (“`r`n”) It is the line feed that moves text onto the next line, so that is why we didn’t see any spaces when printing string in PowerShell. PowerShell just doesn’t display the unprintable characters.

In the days of VBScript I found similar issues with tabs in the text file. In the case of VBScript the Trim function doesn’t remove these.

About chentiangemalc

specializes in end-user computing technologies. disclaimer 1) use at your own risk. test any solution in your environment. if you do not understand the impact/consequences of what you're doing please stop, and ask advice from somebody who does. 2) views are my own at the time of posting and do not necessarily represent my current view or the view of my employer and family members/relatives. 3) over the years Microsoft/Citrix/VMWare have given me a few free shirts, pens, paper notebooks/etc. despite these gifts i will try to remain unbiased.
This entry was posted in Debugging, PowerShell and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s