Archive for category PowerShell

RBAC and Principle of Least Privilege

Exchange 2010 introduced RBAC as a mechanism to manage access to administrative tasks at granular level which was not possible in previous versions of Exchange.

While you may know how to use RBAC to create custom roles that maps to job functions in your environment, one particular feature tends to get easily overlooked, mostly because it is least understood I believe. It is Unscoped Top Level Management Roles.

So, I wrote a blog post on it detailing what it is, and how to configure it. It went live few days ago at Hey, Scripting Guy! blog.

You can read complete article here – http://blogs.technet.com/b/heyscriptingguy/archive/2012/01/13/use-powershell-and-rbac-to-control-access-to-exchange-server-cmdlets.aspx

Enjoy!

Originally posted at http://blogs.technet.com/bshukla

Print Friendly
Share

Script to configure static ports on Exchange Server 2010

There is nothing new about this. If you have been reading about Exchange Server 2010 or have it deployed with hardware load balancer, chances are, you have read how to configure static ports on Exchange Server 2010 on TechNet Social wiki for Exchange 2010. Chances are that you have also used my script (referenced in the post above) to set static ports on your servers. Lastly, chances are that you have read all about it on my previous post here.

If so, why am I even talking about it today?

Well, if you haven’t noticed a few things already, the way you change ports is different in RTM and SP1. My script didn’t account for SP1 originally when it was written. Was SP1 even existed then?

The other reason is my nature of always learning something and making things better! I noticed how my code was inefficient now that I know a few more things about PowerShell (yeah that’s not funny). I decided to write it more efficiently and that basically meant a complete overhaul of my old script.

The new script is now more user friendly! It uses cmdletbinding and comment based help. It means, for you as a user, you can just type:

Get-Help Set-StaticPorts.ps1 –examples

or

Get-Help Set-StaticPorts.ps1 –Full

The script now validates parameters using ValidateRange and ValidateScript. I think that’s cool! It also uses 59531 and 59532 by default now. How about using recommended ports instead of random ones I used in my previous script? I think that’s even more cool!

The script uses all the right write-* cmdlets now instead of write-host. So now you can use tee-object and won’t end up with empty output file. Yes you loose cool colors I used with write-host but hey, you are trying to set ports on your Exchange Server 2010. For colors you would go see Macy’s Fireworks on New Year, right? Smile

Oh and last but probably the most important change is inclusion of –auto and –whatif functionality!

-WhatIf is obvious. Script will tell you what it is doing without actually making any changes.

-Auto will automatically find all your Exchange 2010 CAS servers and Exchange 2010 Mailbox servers that are hosting Public Folders. It will then change ports on CAS Server for RPC CA service and Exchange AB service. On Mailbox servers it will only change RPC CA ports as Exchange AB service doesn’t exist on Mailbox only role.

If you combine all this with –Force, you can also silence the script. It won’t ask you for any confirmation and will change ports you specify (or use defaults) and restart the services! Isn’t that awesome!

So go download the script from here: Set-StaticPorts.ps1 and give it a go. As always, let me know if you find any issues and I will be happy to fix it.

Originally posted at http://blogs.technet.com/bshukla

Print Friendly
Share

PowerShell script to edit remote registry

Did you ever wanted to modify your registry or add a key/value pair to registry? Wished there was a script to help you do that? Even better, wished it can run remotely without PowerShell WinRM listener configured on target server?

I had custom script that would modify certain registry entry but it was inflexible and in my recent rewrite of another script, I wanted more flexibility. So out of necessity, I decided to rewrite my registry script  and made it independent script with lot of flexibility.

Using this script, you can now run it like this:

.\Set-RemoteRegistry.ps1 -Key SYSTEM\CurrentControlSet\services\AudioSrv\Parameters -Name ServiceDllUnloadOnStop -Value 1 -Type DWord

If you want to suppress prompts, you can use –Force parameter like this:

.\Set-RemoteRegistry.ps1 -Key SYSTEM\CurrentControlSet\services\AudioSrv\Parameters -Name ServiceDllUnloadOnStop -Value 0 -Type DWord –Force

This script is also a good example of cmdletbinding and support of whatif. I still think use of Whatif in scripts has its limitations as apprarent in this script (without adding more code to it to work around that limitation).

The script is also a good example of how you can use parameter validation right in the parameter declaration. This way you can avoid if..then code blocks to validate parameter inputs. What a wonderful discovery, I gotta thank PowerShell team for this.

So go ahead, get the script Set-RemoteRegistry.ps1 here and if you find any issues, let me know. Have Fun!

Originally posted at http://blogs.technet.com/bshukla

Print Friendly
Share

Mythbusters–Exchange Server 2010 and PowerShell Remoting

A misconception that WinRM listener needs to be configured in order to be able to connect to Exchange Server 2010 had popped up a couple times in my conversations recently so I decided to clear the confusion. Guest blogging for my friends at IT Pro Africa, I have written the details on the blog post here: http://itproafrica.com/technology/exchange/exchange-server-2010-and-powershell-remoting/

Check it out and feel free to post comments either there or directly here.

Originally posted at http://blogs.technet.com/bshukla

Print Friendly
Share

Microsoft Exchange 2010 PowerShell Cookbook Review

Disclaimer: I am not paid to write about this book and the review written here is my own view.

I was recently contacted by Packt Publishing about their recently published book “Microsoft Exchange 2010 PowerShell Cookbook”. I have voluntarily reviewed books in the past (i.e. Windows Server 2003 Security: A Technical Reference by Roberta Bragg) out of my interest and curiosity. Same interest and curiosity lead me to accept the request and spend some time reading it. I am glad I did because I did find a few interesting things which while I may have known, have never tried to script either because there was no need to do so or was never asked to do so.

I figured posting the review here would give potential readers one more data point to take into their consideration. I am sure the book will benefit any reader working with Exchange Server 2010 and wants to expand on their PowerShell knowledge as it relates to Exchange Server 2010.

Without further due, here it is:

The Premise

Mike Pfeiffer is well known for his contributions to Microsoft Exchange community which has also earned him Microsoft MVP award.

Keeping him in check are the reviewers like Shey Levy, which only means one thing: it is going to be tough for Mike to make a mistake and have it go unnoticed into the book for publication.

Microsoft Exchange 2010 PowerShell Cookbook promises to show you how to automate routine tasks and solve common problems. The book is organized in logical sections walking the reader through key concepts and tasks to manage their Microsoft Exchange 2010 environment with ease.

While the book focuses on on-premise deployment of Microsoft Exchange 2010, the concepts covered should make reader comfortable in managing their Office 365 tenant.

The Content

The book dives into Exchange 2010 management tasks by starting on the right foot. While most of Exchange administrators would be familiar with PowerShell in some capacity, authors don’t just assume and start off with PowerShell key concepts. This is really helpful to novice readers just as much as experienced PowerShell users who may learn a thing or two they didn’t know before.

The book covers every aspect of Exchange 2010 management including recipient management, Database and Server roles management, High availability, Compliance and RBAC.

The book also covers scripting Exchange Web Services which was a pleasant surprise as writing scripts for EWS is difficult only due to lack of understanding on the subject. EWS API and scripting details in this book tries to address just that.

Each section is organized into different tasks reader may want to perform. The tasks have a good flow of precondition, how to perform given task and details explaining what the given cmdlet is doing or information on actual process being followed. There are also very useful tidbits in “There’s More…” sections at end of each task being performed. This will help reader not only understand the task at hand but to leverage the information to carry out other tasks that may be related but not explicitly written about in the book.

Summary

Overall Microsoft Exchange 2010 PowerShell Cookbook is a welcome addition to what’s already been written about Exchange 2010 or PowerShell. While the book doesn’t teach you Exchange 2010, it does a great job of educating the reader about PowerShell and how to get the most out of Exchange 2010 using PowerShell to manage it.

Originally posted at http://blogs.technet.com/bshukla

Print Friendly
Share

Why does catch not catch?

I ran into an interesting discussion with my customer today.  He was writing a code block that looked like the following:

Try {
Get-MailboxServer Bogus
}
Catch {
"Mailbox server doesn't exist"
}

Looking at the code, it’s very simple. Run a command in try block and if error is generated, report on it using catch. However, it didn’t work as it should. That’s why it became interesting.

I tried the following:

Try {
somestring
}
Catch {
"Error"
}

Now that worked just as you would expect!

What was going on here. I was puzzled and so was the engineer who asked me about the error in first place. So we looked at the about_Try_Catch_Finally on TechNet. As an IT Pro would usually RTFM, we went straight to examples and that looked just like our problem child. No issues when we run that example but when we run our code, it doesn’t want to work.

Again, as any other IT Pro would do, we did the next “logical” thing to match the example code with ours and decided we weren’t specifying error type. While we both agreed that it wasn’t the case, we still wanted to make sure. So we looked at the error object:

$Error[0].Exception.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     RemoteException                          System.Management.Automation.RuntimeException

Then we changed out Catch statement to specify the error type. That, as you may have guess it by now, didn’t work either! Smile

This is actually when we started paying attention to TFM. If we ever read the description on the TechNet documentation, it reads “Describes how to use the Try, Catch, and Finally blocks to handle terminating errors.”

So very clearly, it says the error must be a terminating error. And the errors we were generating when executing Get-MailboxServer cmdlet, were not terminating errors! As they say it all the time, once you find the issue, fix takes only seconds. All we had to do at this point was to make the error a terminating error:

Try {
Get-MailboxServer Bogus -ErrorAction Stop
}
Catch {
"Mailbox server doesn't exist"
}

And the world was fine once again.

Originally posted at http://blogs.technet.com/bshukla

Print Friendly
Share

Exchange Team Blog Mobile and PowerShell Error Handling

I admit the two topics don’t have anything in common except both has something to do with me. That’s why they are both being talked about in same post!

So If you haven’t caught up on this yet, I created a Windows Phone App for the Exchange Team Blog. I am trying to ramp up on little bit of WP7 programming so I can create some apps for my use and possibly to publish it on marketplace for others to benefit from it. What could be better than creating one for my favorite blog? You can read more about the announcement and link to the app here. Feel free to leave feedback there or here and I will respond as time allows.

On the next topic. When I was rating scripts in 2011 Scripting Games, I noticed one common thread in almost all beginner scripts. They all were missing error handling. There was no regard to user experience or tendency to handle errors so that the script has greater chance to succeed and when it doesn’t, use has better information on what went wrong. I discussed this with Ed Wilson (That’s “The Scripting Guy” in case you didn’t know!) and he asked me if I can write an article about it. I gladly accepted. The article was published on May 12th but I didn’t get chance to let my readers know on this blog. So here it is. You can read the article on Hey, Scripting Guy blog.

I decided to make it beginner friendly as I figured they are the ones who can benefit the most from what I saw when rating the scripts. It was so much to write than can fit in a single article. So we have decided to make it a series of articles on Hey, Scripting Guy blog. Look forward to more articles in series in coming weeks.

Originally posted at http://blogs.technet.com/bshukla

Print Friendly
Share

How to revert changes made by Enable-PSRemoting?

Have you ever been in a situation where you have PowerShell Remoting enabled and you need to put the configuration back the way it was before Enable-PSRemoting was run?

While it might seem that just running Disable-PSRemoting should suffice, it turns out to be a bit more work than you would think. Let’s take a look.

When you run Disable-PSRemoting, here’s what it tells you:

PS C:\Windows\system32> Disable-PSRemoting
WARNING: Disabling the session configurations does not undo all the changes made by the Enable-PSRemoting or
Enable-PSSessionConfiguration cmdlet. You might have to manually undo the changes by following these steps.
    1. Stop and disable the WinRM service.
    2. Delete the listener that accepts requests on any IP address.
    3. Disable the firewall exceptions for WS-Management communications.
    4. Restore the value of the LocalAccountTokenFilterPolicy to 0, which restricts remote access to members of the
Administrators group on the computer.

As you see, the steps are pretty well documented. However, if you are like me, you would follow the order mentioned, and find out later that it’s a problem. Let’s see why.

  1. You stopped and disabled the WinRM service.
  2. You try to delete the listener using winrm commands only to find out the error:
WSManFault
    Message = The client cannot connect to the destination specified in the request. Verify that the service on the dest
ination is running and is accepting requests. Consult the logs and documentation for the WS-Management service running o
n the destination, most commonly IIS or WinRM. If the destination is the WinRM service, run the following command on the
 destination to analyze and configure the WinRM service: "winrm quickconfig".

Well guess what, you just disabled the service. How will winrm commands connect to delete the listener?

So here’s what you need to do:

  1. Delete the listener that accepts requests on any IP address, Usually this means listener with Address = * and Port = 5985 that is using Transport = HTTP. you can verify this by running
    winrm enumerate winrm/config/listener

    You can delete it by running

    winrm delete winrm/config/listener?address=*+transport=HTTP
  2. Disable firewall exceptions. This is pretty simple. Just uncheck Windows Remote Management checkbox for desired (or all) profiles. And if picture is worth thousand words, here it is:

    SNAGHTML2c896ffb

    Now if you fancy why I didn’t use PowerShell to disable firewall exceptions, I will point you to this link and let you figure out how to do that.

  3. Order doesn’t matter after step 1. So let’s disable service now. Do you need me to tell you how? Ok if you seriously want to know how, here’s how:
    Stop-Service winrm
    Set-Service -Name winrm -StartupType Disabled

    I know you will now ask why not just run:

    Set-Service -Name winrm -StartupType Disabled -Status Stopped

    that’s because if you do that you will get this error:

    Set-Service : Cannot stop service 'Windows Remote Management (WS-Management) (winrm)'
    because it is dependent on other services.
  4. Now, if you are still with me, this is last step left. Set value of LocalAccountTokenFilterPolicy to 0. You can do that by running:
    Set-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name LocalAccountTokenFilterPolicy -Value 0 -Type DWord

    This will create the value if it doesn’t exist and will change it if it does. If you are curious as to why this value and why 0, it’s documented here so I will let you read it.

Oh, and one more thing (I wonder who does that remind you of!) make sure you do all this from elevated PowerShell. But you already knew that, didn’t you?

Originally posted at http://blogs.technet.com/bshukla

Print Friendly
Share

Every good thing must come to an end…

And before you get a shock from the title, let me clarify, all I am talking about is PowerShell Scripting Games 2011.

I had a privilege of being one of the judges this year and I know I haven’t done it enough justice. I was planning to be a lot more active rating scripts as they rolled in. I have been planning to be a lot more involved in spreading wealth of knowledge, while not as much as the scripting guys do, but as much as I can from what I know. I have been planning to….

And as we all know, life sometimes isn’t what we plan and doesn’t have to cooperate with what we want to do. As long as you enjoy what comes your way which is what I did. No excuses , no regrets.

The only thing I want to mention though is for those scripts that I did rate, I commented every single one of them and hopefully the authors understands why I rated them the way I did. My intention was to be fair, clear and thorough. I hopefully have done it well. Quality over quantity. Always something I have believed in.

I also want to mention the amazing response we have got this year. I wouldn’t quote the number but I know way too many scripts that we expected (or compared to last year) for 20 events (10 beginner and 10 advanced). This is simply great! It shows how valuable scripting is in today’s world and how many people are actively doing something about addressing real world problems by using scripts and automation.

I want to thank The Scripting Guys for amazing work they do and organizing such an event. Doing it every year must take a toll on them and being a judge isn’t even a drop in their bucket. I just hope I have been a little bit of help for all you had to do for this event.

With that, I want to sign off as tomorrow is another day full of challenges as day without challenges would really be boring.

Oh and if I put you in shock with the title of this post, I am going to bed and hopefully there wasn’t anything in this post that would cause you to stay in shock, except the obvious awesomeness of PowerShell, scripting and automation!

Originally posted at http://blogs.technet.com/bshukla

Print Friendly
Share

Using PowerShell to look up USCF member info

If you are one of the chess players who play rated USCF (United States Chess Federation) games, you may have used their look up tool to find someone’s rating and other details, or may be your own after you completed a tournament.

Being a PowerShell geek, I had to figure out how can I fetch the same information using script or a function. Now that I have it, I’m sharing it here with you.

For those of you who have nothing to do with Chess, you may still want to look at the script to learn few cool thing like using objects and adding properties to a custom object, using post method to retrieve data from a webpage using values defined in a variable and using comment based help in your script file.

Here’s what the script does:

  1. Aoccepts input in form of Lastname, Firstname and wildcard. Lastname is required, firstname and wildcard are optoinal.
  2. Accepts input in form of USCF ID. Step 1 and 2 are mutually exclusive. You can only use one or the other.
  3. Checks if computer is connected to internet. We can’t fetch data from internet otherwise, can we?
  4. Validates all variables and fetches USCF member data as per the query if no errors found in validation.
  5. Allows output to be sent to csv file using –OutFile parameter. Output to console is suppressed if sent to file.

For brevity, I am not posting code in the post. You can download the file here.

Originally posted at http://blogs.technet.com/bshukla

Print Friendly
Share