DEV Community


Posted on

Quick tips for Powershell scripters

Here's some quick and dirty help if you've gotten rusty with Powershell or otherwise aren't sure quite how to do things.

1: Modules are your best friend

Chances are that whatever you're trying to do inside a Microsoft environment has a module either written or trusted by Microsoft already at Powershellgallery. Don't reinvent the wheel.

2: MS Docs are your first and best reference

Microsoft's documentation actually doesn't suck when it comes to Powershell. It's not going to hold your hand all the way, but if you've got even a mite of experience doing scripting that touches environment variables and networked services (like AD, O365, Exchange) then you'll be able to pick up on the examples and concepts the documentation offers pretty easily. Don't be afraid to dig a few links deep into your questions.

3: Powershell has two major versions

Powershell 5.1 comes installed by default on Win10, and I think it's still the default on Win11 as well. This version of Powershell is written in .NET Framework, which is Windows-native. This is by far the most common option, as opposed to Powershell 7, which is written in .NET Core. Core is inherently cross-platform. If you run Powershell on a *nix system like Linux or Mac, it's v7 running on .NET Core. This is important because not all assemblies and modules are usable on both platforms. A notable difference here is MSOnline, which depends on cryptography dependencies inside Powershell 5 that are not available in 7; and therefore MS now encourages you use the MS Graph API and other Azure-based modules as a replacement for the old MSOnline module.

4: Iterate, iterate, I T E R A T E

One of the most powerful combos in Powershell is the combination of If-Else flow control and a ForEach loop walking over every complex object inside a data container like an Array, ArrayList, or HashTable.

You can use this to:

  • Grab a specific user group using Get-ADGroupMember, put all the user objects in an array, and then grab all of their usernames. You can pipe those usernames into other commands, or just use it as a simple way to dump out a list of who's in what groups.
  • Make bulk changes to Exchange accounts by pulling out all accounts on a specific Filter, and then running a set of commands ForEach. Anyone who's spent a lot of time in the Exchange console GUI can probably agree that it takes a while to do stuff by hand.
  • Check and even change the MFA status of users in your tenant in order to fix security holes, get info for audits, and more.

I've got a handful of sample scripts at GrinnyLib on Github. I just recently started putting scripts I use regularly there, that I've written myself. You'll probably recognize that some of these examples can be used for concepts I mentioned in this post.

If any of these helped you out, leave a comment!

Top comments (0)