PowerShell


Video: Automatically Migrate your Scripts from AzureRM to the Az PowerShell Module

As many of you know, I’m a Senior Content Developer for Azure PowerShell at Microsoft. Today we announced the Az.Tools.Migration PowerShell module which is a toolkit for automatically migrating your PowerShell scripts and modules from AzureRM to the Az PowerShell module. The video shown below demonstrates how to use this module: For more information, see the official announcement that I wrote on the Microsoft Tech Community blog site. In addition to the PowerShell module, there is also a VS Code extension for performing the migration.

How many Services does Microsoft Azure Offer?

I’ve recently wondered how many service offerings Azure has. I’ve read anywhere from 150 to 600 and I even went so far as to ask an Azure Product Manager but still didn’t receive a clear answer. What I did find out is that Microsoft maintains an Azure services directory on their Azure products website. I figured that was a good place to start looking and while the website is informative, it didn’t provide a count of the service offerings.

AzureRM PowerShell Commands that Don’t Exist when Enabling Compatibility Aliases in the Az Module

On Twitter, I recently asked if anyone was still using the AzureRM PowerShell module and what was keeping them from transitioning to the Az PowerShell module. One of the responses I received was due to the amount of work and time invested in scripts based on the AzureRM module. The Az PowerShell module includes compatibility aliases for scripts written using the AzureRM PowerShell module. The compatibility aliases are enabled using the Enable-AzureRmAlias command.

How to Install the Azure Az PowerShell Module

The Az PowerShell module was released in December of 2018 and is now the recommended module for managing Microsoft Azure. AzureRM is the previous PowerShell module for managing Azure which has been deprecated but will continue to be supported until December of 2020. Windows PowerShell 5.1, PowerShell Core 6, PowerShell 7, and higher are supported by the Az PowerShell module. Windows 10 version 1607 and higher has Windows PowerShell 5.1 installed by default.

Setting Dependencies on the Azure PowerShell Module

I recently saw a tweet from Joel Bennett about the Az (Azure) PowerShell module being nothing more than an empty module that imports all of the modules for each Azure product. I decided to investigate. Get-Content -Path (Get-Module -Name az).Path | Select-String -SimpleMatch 'Import-Module' Joel’s statement is 100% accurate. Off-Topic: The searched for term is highlighted in each result when the previous command is run in PowerShell 7.

Using PowerShell to Retrieve Exchange Mailbox Statistics for Office 365 Migrations

Recently, I’ve been working on trying to finish up a migration from Exchange Server 2010 to Office 365. There are potentially numerous mailboxes that aren’t used and those won’t be migrated to Office 365 because there’s no sense in paying for licensing for them. How do you determine what mailboxes are in use? First, use implicit remoting to load the Exchange cmdlets locally. Years ago, I would install the Exchange cmdlets locally, but it was brought to my attention that it’s unsupported, at least according to this article: Directly Loading Exchange 2010 or 2013 SnapIn Is Not Supported.

PowerShell Productivity Hacks: How I use Get-Command

If you’ve been using PowerShell for very long at all, then you should already be familiar with Get-Command and Get-Help. While I like to say that Get-Command is for finding commands and Get-Help is for learning how to use those commands once you’ve found them, there is overlap between these two commands depending on how you use them. I believe in following the best practice of not using aliases or positional parameters in any code that I save or share with others, but in this blog article, I’m going to show how things work in the real world.

Parallel and ThrottleLimit Parameters added to ForEach-Object in PowerShell 7 Preview 3

Preview 3 of PowerShell 7 was released yesterday. It can be downloaded from the PowerShell repository on GitHub. Be sure to choose the preview version for the appropriate operating system. It should go without saying that anything with preview in its name should NOT be installed on a mission-critical production system. The examples shown in this blog article are being run on a system running Windows 10 (x64). Your mileage may vary with other operating systems and/or versions.

PowerShell Function to Find Parameter Aliases

While sitting through Jeff Hicks' Advanced PowerShell Scripting Workshop at PowerShell on the River in Chattanooga today, he mentioned there being a “Cn” alias for the ComputerName parameter of commands in PowerShell. I’ve previously written a one-liner to find parameter aliases and at one time Microsoft had starting adding parameter aliases to the help for commands as referenced in that same blog article, but it appears that they’ve discontinued adding them to the help and removed the ones they previously added to it.

Where are Untitled Tabs in VSCode Saved on a Windows System?

Ever wonder how VSCode (Visual Studio Code) maintains those untitled tabs between sessions? They’re stored as files underneath your user’s profile in appdata on Windows based systems as shown in the following example. Get-ChildItem -Path $env:APPDATA\Code\Backups\*\untitled -Recurse The previous command could be piped to Get-Content to view the contents of all of code in the open untitled tabs of VSCode. You could also use Select-String to find something specific. I can see that three of my open tabs contain ‘mikefrobbins’.

What’s in your PowerShell $PSDefaultParameterValues Preference Variable?

The $PSDefaultParameterValues preference variable, which was introduced in Windows PowerShell version 3.0, provides a mechanism for specifying default values for parameters. I thought I would share what I’ve added to mine and ask the community to share theirs. $PSDefaultParameterValues = @{ 'Out-Default:OutVariable' = 'LastResult' 'Out-File:Encoding' = 'utf8' 'Export-Csv:NoTypeInformation' = $true 'ConvertTo-Csv:NoTypeInformation' = $true 'Receive-Job:Keep' = $true 'Install-Module:AllowClobber' = $true 'Install-Module:Force' = $true 'Install-Module:SkipPublisherCheck' = $true } The first one in the list ('Out-Default:OutVariable' = 'LastResult') is one I picked up from Joel Bennett to store the results of the last command in a variable named $LastResult.

Install PowerShell 7 with Jeff Hicks’ PSReleaseTools Module

PowerShell version 7 is currently in preview and while it can be installed on Windows, Linux, and macOS, the examples shown in this blog article focus on installing it on a Windows based system, specifically Windows 10 using Windows PowerShell version 5 or higher which ships by default with Windows 10. Your mileage may vary with other operating systems, other versions of Windows, and/or other versions of Windows PowerShell. The easiest way that I’ve found to install the preview of PowerShell version 7 is to first install Jeff Hicks' PSReleaseTools PowerShell module from the PowerShell Gallery using Windows PowerShell.

Import a Hyper-V Virtual Machine with PowerShell

I recently ran into a problem where an exported VM from Windows Server 2016 running Hyper-V wasn’t able to be imported on Windows Server 2019 running Hyper-V. When attempting to perform the import, the GUI stated “No virtual machines files found” as shown in the following image. This problem may have been due to using Hyper-V manager on a remote system running Windows Server 2012 R2, although the same system was used for the export.

Determine the Generation of a Hyper-V VM with PowerShell

Ever need to determine what generation all of the virtual machines are on your Hyper-V servers? This is simple using the Get-VM command that installs as part of the Hyper-V module for Windows PowerShell. Get-WindowsOptionalFeature -FeatureName *hyper*powershell -Online While the previous command will work on both clients and servers, the following command could also be used on a Windows server. Get-WindowsFeature -Name *hyper*powershell The generation of the VM is one of the properties from the results of Get-VM.

Mitigating BlueKeep with PowerShell

When it comes to security, most people normally approach it at one extreme or the other. Some people do nothing and don’t worry about it. All I can say for those folks is good luck with that and I hope your resume is updated. Others go into full blown panic mode, especially those who don’t take the time to understand vulnerabilities. Many security folks and articles on the Internet don’t help much either because they often blow things out of proportion which puts many of the people in the second category into panic mode.

Find an Application that runs as a Service in your Environment with PowerShell

I recently worked with a vendor to remove an old application that was no longer being used from a server in one of my customer’s environments. While many applications may be left to die on the server long after they’re needed, this particular one transmitted data to a partner company so it definitely needed to be removed. The problem is the application was so old that no one knew which server of the hundreds of servers it was running on.

Video: Finding Performance Bottlenecks of Windows Based Systems with PowerShell

Earlier this month, I presented a session on Finding Performance Bottlenecks with PowerShell at the PowerShell + DevOps Global Summit 2019 in Bellevue, Washington. The session seemed to be well received by the audience based on the feedback that I received from the attendees. The video from this presentation is now available. The code and slides used during the demonstration can be found in my presentations repository on GitHub.

Using the AST to Find Module Dependencies in PowerShell Functions and Scripts

Earlier this week, Chris Gardner presented a session on Managing dependencies in PowerShell for the Mississippi PowerShell User Group. I mentioned that I had written a function to retrieve PowerShell module dependencies that’s part of my ModuleBuildTools module. Get-MrAST is one of the primary functions that numerous other functions in the module are built on. #Requires -Version 3.0 function Get-MrAst { <# .SYNOPSISExplores the Abstract Syntax Tree (AST). .DESCRIPTIONGet-MrAST is an advanced function that provides a mechanism for exploring the Abstract Syntax Tree (AST).

Sort PowerShell Results in both Ascending and Descending Order

A few weeks ago I was trying to figure out how to sort something in PowerShell with one property sorted descending and another one ascending. How to accomplish this was hiding in plain sight in the help examples for Sort-Object, but I thought I would documented it here for future reference. Use the Property parameter with a hash table to specify the property names and their sort orders. Get-Service -Name Win* | Sort-Object -Property @{ expression = 'Status' descending = $true }, @{ expression = 'DisplayName' descending = $false } This same command can be written on one line.

Use PowerShell to Identify the Process ID for SQL Server Services

I recently saw a blog article on How to Identify Process ID for SQL Server Services? – Interview Question of the Week #185 written by Pinal Dave. While his answer is simple with TSQL, what if you’re not a SQL guy? You can also retrieve this information with PowerShell from Windows itself. When it comes to retrieving information about Windows services with PowerShell, the first command that comes to mind is Get-Service.

Enable Tab Completion in VSCode for a PowerShell ISE like Experience

I’m using VSCode for all of my PowerShell development at this point. I reloaded my system from scratch on March 13th of this year. Yesterday was the first time I’ve opened the PowerShell ISE since then and it was only to determine if something worked differently between the two (I tweeted this out yesterday). One of the common problems I hear about and have experienced myself with VSCode (Visual Studio Code) is that tabbed expansion of command and parameter names doesn’t work like it does in the ISE (Integrated Scripting Environment).

Run SQL Server PowerShell Cmdlets as a Different User

One of the ways I practice the principal of least privilege is by logging into my computer as a domain user who is also a standard local user. I typically run PowerShell as a domain user who is a local admin and elevate on a per command basis using a domain account with more access only when absolutely necessary. The problem I’ve run into is neither the account I’m logged into my computer as or the one I’m running PowerShell as has the ability to execute SQL queries that I need to run against various SQL servers in my environment.

Audit Membership of the Local Admins Group with PowerShell

Recently, I needed to make sure that specific accounts were members of the local administrators group on several servers along with making sure that no other users were members of it. PowerShell version 5.1 introduced a module named Microsoft.PowerShell.LocalAccounts that contains the following commands for managing local users and groups. Get-Command -Module Microsoft.PowerShell.LocalAccounts Checking the group membership is as easy as running Get-LocalGroupMember within the script block of Invoke-Command and targeting remote systems.

Backup and Synchronize VSCode Settings with a GitHub Gist

Earlier this year, I watched a recording of the January 2019 Arizona PowerShell User Group meeting where Tim Warner presented a session on Easing your transition from the PowerShell ISE to Visual Studio Code. One of the things Tim demonstrated was a VSCode extension named Settings Sync where you can synchronize your VSCode settings to and from a GitHub Gist. While it seems to be designed to synchronize your settings between multiple computers, I recently found out that it can also be a lifesaver even if you only use it on one computer.

PowerShell Tokenizer more Accurate than AST in Certain Scenarios

As many of you know, I’ve been working on some module building tools. One of the things I needed was to retrieve a list of PowerShell modules that each function required (a list of dependencies). This seemed simple enough through PowerShell’s AST (Abstract Syntax Tree) as shown in the following example. $File = 'U:\GitHub\PowerShell\MrToolkit\Public\Find-MrModuleUpdate.ps1' $AST = [System.Management.Automation.Language.Parser]::ParseFile($File, [ref]$null, [ref]$null) $AST.ScriptRequirements.RequiredModules.Name The modules that are retrieved by the AST are simply the ones specified in a functions Requires statement.

My Solution to Iron Scripter 2019 Preparatory Challenge 1

Anyone who has competed in the scripting games before knows that I’m always looking for a challenge when it comes to writing PowerShell code. While the scripting games haven’t been held in the last several years, they’ve somewhat been replaced by the Iron Scripter competition at the PowerShell + DevOps Global Summit and 2019 is shaping up to be no different. Think you’ve got skills? Bring them on! and Get-Involved.

Unexpected Results when Comparing Different Datatypes in PowerShell

Earlier this week, I saw a tweet from a fellow PowerShell community member who mentioned PowerShell was returning inaccurate results. The command shown in the tweet was similar to the one in the following example. Get-AppxPackage | Where-Object -Property IsFramework -eq 'False' | Select-Object -Property Name, SignatureKind, IsFramework Why would results be returned where IsFramework is true when the command is filtering them down to only the ones that are false?

What’s a PowerShell One-Liner & NOT a PowerShell One-Liner?

Lately, I’ve seen a few examples of commands that aren’t PowerShell one-liners being passed off as such by people in the PowerShell community who “should” know better. If I were interviewing someone who claimed to be a PowerShell expert with more than five years of experience, I would definitely ask these types of questions. Example 1 - The following command is a PowerShell one-liner? (True or False) $Process = 'notepad.exe'; Start-Process $Process -PassThru -OutVariable NoteProc; Stop-Process -Id $NoteProc.

Return a List of the Private Functions in a PowerShell Module

In my quest to build a PowerShell module to convert a non-monolithic PowerShell module from development to a monolithic one for production, I wanted some way to validate that all of the functions were indeed migrated. While I’m pointing my tools to the public and private sub-folders within my development module and that should get them all, how can you be sure especially when a module may not have any private functions?

Resolving Microsoft SQL Server Error 4064 with PowerShell

Recently, a fellow IT Pro contacted me and stated they were unable to login to one of their SQL Servers using Windows Authentication. The following error was generated when attempting to login to SQL Server Management Studio (SSMS). Their exact words were “I think we have a permissions problem”. Clicking on the “Show technical details” icon at the bottom of that error message showed the following information. You can work around this problem by clicking on the “Options »” button:

Use PowerShell to Install a DHCP Server on a Windows Server 2019 (Server Core) Active Directory Domain Controller

You need to have an Active Directory domain in place. I’m picking up where I left off in my previous blog article Use PowerShell to Create a New Active Directory Forest on Windows 2019 Server Core Installation (no-GUI). The procedure shown in this blog article is for demonstration purposes only. Install the DHCP server feature. Install-WindowsFeature -Name DHCP Add the DHCP scope to the server. Add-DhcpServerv4Scope -Name '192.168.129.x' -StartRange 192.

Use PowerShell to Create a New Active Directory Forest on Windows 2019 Server Core Installation (no-GUI)

You have a fresh installation of Windows Server 2019 that was installed using the default installation type of server core installation (no-GUI). This server will be the first domain controller in a brand new Active Directory forest. You’ve completed the following configuration prior to attempting to turn this server into a domain controller: Install all the available Windows Updates Set the time zone Set the computer name Set a static IP address Log into the server and launch PowerShell by typing powershell.

What’s the Recommended Editor for PowerShell Scripts?

You’ve probably heard, as I have, that Visual Studio Code (VSCode) is the latest whiz-bang editor that you should be using for PowerShell (and I am for development of PowerShell code on my primary workstation). One word of caution though is to make sure to put things into perspective and not be so quick to shun people away from using the PowerShell Integrated Scripting Environment (ISE), depending on how they’re using it.

Managing the Hyper-V Default Switch in Windows 10 version 1709 and higher with PowerShell

Windows 10 version 1709 introduced a default Hyper-V virtual switch which is installed when the Hyper-V role is added. As you can see in the following example, by default on Windows 10, the default virtual switch does not exist because the Hyper-V role hasn’t been added. Get-NetAdapter Now that the Hyper-V role has been added, you can see that a new network adapter named “vEthernet (Default Switch)” exists. Get-NetAdapter | Format-Table -AutoSize While you wouldn’t think this would be a problem, I’ve seen some latency problems on the host operating system once this default switch is added.

PowerShell Script Module Design: Building Tools to Automate the Process

As I previously mentioned a little over a month ago in my blog article PowerShell Script Module Design Philosophy, I’m transitioning my module build process to a non-monolithic design in development and a monolithic design for production to take advantage of the best of both worlds. Be sure to read the previously referenced blog article for more details on the subject. My goal is to write a reusable tool to retrieve the necessary information from a non-monolithic script module that’s necessary to create a monolithic version of the same module.

Learn about the PowerShell Abstract Syntax Tree (AST) – Part 3

This blog article is the third in a series of learning about the PowerShell Abstract Syntax Tree (AST). Be sure to read the other two if you haven’t already. Learning about the PowerShell Abstract Syntax Tree (AST) Learn about the PowerShell Abstract Syntax Tree (AST) – Part 2 Learn about the PowerShell Abstract Syntax Tree (AST) – Part 3 In this blog article, I’ll be specifically focusing on finding the AST recursively.

Learn about the PowerShell Abstract Syntax Tree (AST) – Part 2

In my previous blog article a few weeks ago on Learning about the PowerShell Abstract Syntax Tree (AST), I mentioned there was an easier way to retrieve the AST so that you didn’t have to cast everything to a script block. There are two .NET static methods, ParseFile and ParseInput, that are part of the Parser Class in the System.Management.Automation.Language namespace which can be used to retrieve the AST. First, I’ll store the content of one of my functions in a variable.

Use PowerShell to Monitor IIS Websites and Application Pools

I recently received a request to write a script for monitoring IIS websites and their application pools on a specific Windows 2012 R2 server and start them if they were stopped. This is something I created fairly quickly and thought I would share. I always try to centralize any scripts I write and have them run on a job server instead of the actual server they’re querying. That way I don’t have multiple versions of the same script floating around on different servers.

Use PowerShell to Install the Remote Server Administration Tools (RSAT) on Windows 10 version 1809

My computer recently updated to Windows 10 version 1809 and as with all previous major updates of Windows 10, this wipes out the Remote Server Administration Tools (RSAT). However, unlike previous versions, Microsoft has now made RSAT available via Features on Demand and while you’re supposed to be able to install them from the GUI, they never showed up as being an option for me. That’s not really a problem though since they can now be installed via PowerShell.

Learning about the PowerShell Abstract Syntax Tree (AST)

This week, I’ll continue where I left off in my previous blog article PowerShell Script Module Design Philosophy. Moving forward, the development versions of my PowerShell script modules will use a non-monolithic design where each function is dot-sourced from the PSM1 file. When I move them to production, I’ll convert them to using a monolithic design where all functions reside in the PSM1 file. In development, each PS1 file uses a Requires statement which specifies the requirements from a PowerShell version and required modules standpoint.

PowerShell Script Module Design Philosophy

Years ago, when I first learned how to create PowerShell script modules, I built them with all the functions in one huge monolithic PSM1 file. I like the monolithic script module design from a performance and security standpoint along with the ease of signing fewer files if you’re taking advantage of code signing to digitally sign your scripts and modules (there are fewer files to sign). What I don’t like is that collaborating with others using one huge file is a merge conflict waiting for a place to happen and if someone only wants one of my functions instead of the entire module, they’re out of luck unless they want to copy and paste it.

PowerShell Script Module Design: Don’t Use Asterisks (*) in your Module Manifest

Using asterisks (*) in your module manifest is a bad idea no matter how you look at it. First, your module will be slower because it will have to figure out what to export. More importantly, if you use a “#Requires -Modules” statement in your functions and they’re in separate PS1 files, all of the specified module’s commands will show as being part of your module. I’ll pick up where I left off in one of my previous blog articles PowerShell Script Module Design: Plaster Template for Creating Modules.

Indentation and Formatting Style for PowerShell Code

My preferred indentation style when writing PowerShell code is Stroustrup style because I don’t like my code to cuddle (there’s no cuddled else in Stroustrup style). I occasionally hear from others that they don’t like this style because it doesn’t work from the PowerShell console. if ($plasterParams.Git) { $ModulePath = "$($plasterParams.DestinationPath)\$($plasterParams.GitRepoName)\$($plasterParams.Name)" } else { $ModulePath = "$($plasterParams.DestinationPath)\$($plasterParams.Name)" } While it doesn’t work by default, there’s a trick to making that style work from the PowerShell console.

PowerShell Script Module Design: Plaster Template for Creating Modules

I recently began updating my PowerShell script module build process. Updating my Plaster template was one of the first things I needed to do. If you haven’t already read my blog article about Using Plaster to create a PowerShell Script Module template, I’d recommend beginning there as this blog article assumes you already have a basic understanding of how to use Plaster. All of the information from my previous Plaster template is still there with the exception of the required PowerShell version as I plan to obtain that information and update it a different way.

PowerShell Script Module Design: Public/Private versus Functions/Internal folders for Functions

There’s been a lot of debate about script module design as of lately and instead of tweeting something out asking for responses, I thought I would post it here via a blog article. Back when I first started creating PowerShell script modules, I placed all of my functions in the PSM1 file and later started placing each function in a separate PS1 file that was dot-sourced from the PSM1 file.

Determine the Day of the Week in 11 Days from Now with PowerShell

A couple of days ago, one of my kids asked me “What day of the week will it be in 11 days from now?”. My response was “I’m not sure, but I can tell you how to figure out the answer for yourself”. Open up PowerShell, wrap Get-Date in parentheses, place a dot or period afterwards, followed by AddDays, then 11 in another set of parentheses, and finally another dot or period followed by DayOfWeek.

Determine if a Mailbox is On-Premises or in Office 365 with PowerShell

One of the companies that I support is currently in the process of migrating from an on-premises Exchange Server environment to Office 365. They’re currently running in hybrid mode. While it seems like wanting to know what mailboxes still exist onsite versus which ones are in the cloud would be an all too common task, there doesn’t seem to be an easy way to get that information with PowerShell. You would think that you’d be able to run a PowerShell command and it would return the results.

Displaying Toast Notifications for a Different User when PowerShell Module Updates are Available

A couple of months ago, Josh King presented a session on Using BurntToast to Display Timely Notifications for our June 2018 Mississippi PowerShell User Group virtual meeting. I was previously planning to write something to display balloon notifications in Windows and I learned that they’re now called toast notifications. I also learned that Josh had created a module named BurntToast which performs most of the heavy lifting so I could simply take advantage of it instead of writing my own code.

Use PowerShell to Determine What Your System is Talking to

Recently, while troubleshooting a problem with a newly installed application, I wanted to see what it was communicating with. My only requirement was that I wanted to use PowerShell if at all possible. I couldn’t remember if there was a PowerShell command for accomplishing this task or not, but I remembered seeing something about it in Patrick Gruenauer’s chapter (PowerShell as an Enterprise Network Tool) in The PowerShell Conference Book.

Use PowerShell to Install Windows Features and Reboot

Recently, I installed the Windows Subsystem for Linux (WSL) feature on my Windows 10 computer. Microsoft has an installation guide that walks you through the entire process, but I thought I’d share a few PowerShell tricks when it comes to installing Windows features. The system used throughout this blog article runs Windows 10 version 1803 which ships with Windows PowerShell version 5.1. Your mileage may vary if you’re using a different version of Windows and/or PowerShell.

Convert Scientific Notation to Decimal with PowerShell

Have you ever run into a problem where the results from a PowerShell command are returned in scientific notation? I’ve recently been working with performance counters in PowerShell and I’ve run into several scenarios where this occurs such as the one shown in the following example. (Get-Counter -Counter '\PhysicalDisk(*c:)\Avg. Disk sec/Read' -OutVariable Results).CounterSamples In addition to returning the results in the previous example, they were also stored in a variable so the same value could be used throughout this blog article.

Configuring “Send As” Permission in Office 365 using PowerShell

You’re the administrator of an on-premises Exchange Server 2010 environment that’s in Hybrid mode. After migrating a few users to Office 365, you start receiving complaints that they’re no longer able to send emails as their departments group. First, follow the instructions in one of my previous blog articles to Connect to Office 365 using PowerShell. The following command grants John Doe the ability to send as the Facility Services group in Office 365.

Assign a License to an Office 365 User with PowerShell

There are several scenarios where you might need to assign an Office 365 license to a user. The specific scenario in this blog article is that you’re migrating an Exchange Server 2010 on-premises environment to Office 365. The Exchange Server is already in hybrid mode. Users have been automatically created in Office 365 by synchronizing them from your on-premises Active Directory environment using Azure AD Connect. Users who haven’t already had their mailbox moved to Office 365 will first need an Office 365 license assigned to them, and before a license can be assigned to them, a usage location must be set on their individual account.

Connect to Office 365 with PowerShell

I’ve recently been working on a project to migrate an Exchange Server 2010 environment to Office 365. As with Exchange, there are several things that simply can’t be done from the GUI in Office 365. This means that if you’re the Office 365 administrator for your company, you’ll need a certain level of proficiency with PowerShell to effectively do your job . While not requirements, this blog article is written using Windows 10 Enterprise Edition version 1803 and PowerShell Core version 6.

Video: Recreate MOF based DSC resources as Class based DSC resources

Last month I presented a session on how to Recreate MOF based DSC resources as Class based DSC resources at the PowerShell + DevOps Global Summit in Seattle, Washington. The session seemed to be well received by the audience based on the feedback that I received from the attendees. The video from this presentation is now available. The code and slides used during the demonstration can be found in my presentations repository on GitHub.

Video: Writing Award Winning PowerShell Functions and Script Modules

Last month I presented a session on Writing Award Winning PowerShell Functions and Script Modules at the PowerShell + DevOps Global Summit in Seattle, Washington. The session seemed to be well received by the audience based on the feedback that I received from the attendees. The session was also completely full. I’m glad it was recorded so anyone who was unable to attend can watch it. The video from this presentation is now available.

PowerShell Core 6: ValidatePattern Custom Error Messages

Last week, I received a comment on my previous blog article from fellow Microsoft MVP Joel Bennett which referenced using an ErrorMessage parameter similar to how ValidatePattern works in PowerShell Core version 6. I knew I’d seen some discussion about this on GitHub, but I wasn’t aware that it had made it into the production release. Joel’s message is shown in the following image. I had to figure out how to use custom error messages with ValidatePattern.

Simplifying Parameter Validation in PowerShell with Private Functions

In my previous blog article, I described how to move code from ValidateScript to a private function for parameter validation in PowerShell. This all came about from a question I received in one of my sessions at the PowerShell + DevOps Global Summit a couple of weeks ago. I enjoy following up with attendees of my presentations when they have questions so I sent a message and a link to my previous blog article to the person who asked if that was possible.

Moving Parameter Validation in PowerShell to Private Functions

While presenting one of my presentations at the PowerShell + DevOps Global Summit last week, I demonstrated why you wouldn’t want to use ValidatePattern for parameter validation because of the useless error message that it returns when the input doesn’t match the regular expression that’s being used for validation. function Test-ValidatePattern { [CmdletBinding()] param ( [ValidatePattern('^(?!^(PRN|AUX|CLOCK\$|NUL|CON|COM\d|LPT\d|\..*)(\..+)?$)[^\x00-\x1f\\?*:\"";|/]+$')] [string]$FileName ) Write-Output $FileName } I then demonstrated how ValidateScript could be used to build a better ValidatePattern.

Remotely Uninstall ESET Antivirus with PowerShell

Recently, one of the companies that I provide support for switched from using ESET to a new antivirus vendor. The problem is that all of their servers had both ESET File Security and the ESET Remote Administrator Agent installed which needed to be uninstalled before installing the new antivirus agent. I determined that the following commands could be used to uninstall the applications. #Uninstall Eset Remote Administrator Agent sc.exe delete eraagentsvc msiexec.

Adding Multiple Parameter Sets to a PowerShell Function

Sometimes you need to add more than one parameter set to a function you’re creating. If that’s not something you’re familiar with, it can be a little confusing at first. In the following example, I want to either specify the Name or Module parameter, but not both at the same time. I also want the Path parameter to be available when using either of the parameter sets. function Test-MrMultiParamSet { [CmdletBinding(DefaultParameterSetName='Name')] param ( [Parameter(Mandatory, ParameterSetName='Name')] [string[]]$Name, [Parameter(Mandatory, ParameterSetName='Module')] [string[]]$Module, [string]$Path ) $PSCmdlet.

Using Plaster to create a PowerShell Script Module template

I have a function in my MrToolkit module named New-MrScriptModule that creates the scaffolding for a new PowerShell script module. It creates a PSM1 file and a module manifest (PSD1 file) along with the folder structure for a script module. To reduce the learning curve of Plaster as much as possible, I’m simply going to replace that existing functionality with Plaster in this blog article. Then moving forward, I’ll add additional functionality.

Temporarily Disable the Azure AD Connect Accidental Deletion Protection Feature with PowerShell

You’ve implemented Azure AD Connect to synchronize accounts in your on-premises Active Directory environment to Azure AD. If you took the defaults while running the setup wizard for Azure AD Connect, then everything in your Active Directory environment is synchronized. If you decided to filter the synchronization later to only specific OU’s (Organizational Units) in your Active Directory environment, you could run into a scenario where the number of deletions exceeds the default threshold of 500 objects.

The PowerShell Iron Scripter: My solution to prequel puzzle 3

I’ve been working through the Iron Scripter 2018 prequel puzzles which can be found on PowerShell.org’s website. In puzzle 3, you’re asked to create a “reusable PowerShell artifact”. To me, that almost always means a PowerShell function. One requirement is to pull information from the PowerShell.org RSS feed. Invoke-RestMethod which was introduced in PowerShell version 3.0 is the easiest way to accomplish that task. You’re also asked to display the returned information in a way that allows the user to select an item from the feed.

Help in PowerShell Core is independent of help in Windows PowerShell

You’ve decided to install PowerShell Core on your Windows system. First of all, keep in mind that PowerShell Core version 6.0 is not an upgrade or replacement to Windows PowerShell version 5.1. It installs side by side on Windows systems. Being aware of this makes what is shown in this blog article make more sense, otherwise it can be confusing. Based on the response to a tweet of mine from Don Jones, it appears that I’m not the only one who thought PowerShell Core should have been version 1.

The PowerShell Iron Scripter: My solution to prequel puzzle 2

As I mentioned in my previous blog article, each week leading up to the PowerShell + DevOps Global Summit 2018, PowerShell.org will be posting an iron scripter prequel puzzle on their website. As their website states, think of the iron scripter as the successor to the scripting games. If you haven’t done so already, I recommend reading my solution to the Iron Scripter prequel puzzle 1 because some things are glossed over in this blog article that were covered in detail in that previous one.

The PowerShell Iron Scripter: My solution to prequel puzzle 1

Each week leading up to the PowerShell + DevOps Global Summit 2018, PowerShell.org will be posting an iron scripter prequel puzzle on their website. As their website states, think of the iron scripter as the successor to the scripting games. I’ve taken a look at the different factions and it was a difficult choice for me to choose between the Daybreak and Flawless faction. While I try to write code that’s flawless, perfection is in the eye of the beholder and it’s also a never-ending moving target.

Use PowerShell to create a bootable USB drive from a Windows 10 or Windows Server 2016 ISO

It seems as if every time I need to reload a physical system, I’m searching the Internet to find a way to create a bootable USB drive from a Windows 10 or Windows Server 2016 ISO. I always seem to find tutorials that are using a process that’s almost 20 years old. They have me using the diskpart command line utility. Diskpart which initially shipped with Windows 2000, reminds me way too much of its predecessor, the fdisk command line utility.

PowerShell Compare-Object doesn’t handle null values

I thought I’d run into a bug with the Compare-Object cmdlet in PowerShell version 5.1 earlier today. $DriveLetters = (Get-Volume).DriveLetter $DriveLetters Compare-Object -ReferenceObject $DriveLetters -DifferenceObject $DriveLetters Compare-Object : Cannot bind argument to parameter ‘ReferenceObject’ because it is null. At line:1 char:33 + Compare-Object -ReferenceObject $DriveLetters -DifferenceObject $Driv … + ~~~~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [Compare-Object], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.CompareObjectCommand Running the same commands on a VM with PowerShell version 5.

Using PowerShell to Check Remote Windows Systems for CVE-2017-5754 (Meltdown) and CVE-2017-5715 (Spectre)

The Microsoft Security Response Center has released a PowerShell module named SpeculationControl that can be used to check for the CVE-2017-5754 (Meltdown) and CVE-2017-5715 (Spectre) vulnerabilities. The SpeculationControl module can be installed from the PowerShell Gallery with Install-Module which is part of the PowerShellGet module that ships natively with PowerShell version 5.0, but can be installed on PowerShell version 3.0 and higher. Install-Module -Name SpeculationControl -Force Running the one function Get-SpeculationControlSettings contained in the SpeculationControl module is simple enough, although it does require the script execution policy to be set to remote signed or less restrictive.

Generate a Secret Santa List with PowerShell

It’s supposed to be the most wonderful time of the year and while you might buy multiple Christmas gifts for everyone in your immediate family, often times buying for everyone in your extended family or for all of your co-workers is cost prohibitive. I originally started out with a simple idea to create a PowerShell script to take a list of names and generate a second random list of names based off of the first one while making sure the corresponding name on the second list doesn’t match the first one.

Retrieve Basic Operating System Information with PowerShell

PowerShell version 5.1 added a new cmdlet named Get-ComputerInfo which retrieves lots of information from the local computer. It can be wrapped inside of the PowerShell remoting Invoke-Command cmdlet to retrieve that same information from remote computers. My biggest complaint with Get-ComputerInfo is that it takes forever to return the information and then when it does finally complete, it’s missing values for most of its properties. Also, if you’re going to wrap it inside of Invoke-Command, then all of your remote machines would need PowerShell 5.

Determine the Start Time of a Windows Service with PowerShell

Recently, I was asked to setup a scheduled task or job to restart specific services on certain servers each night and while that’s simple, how do you know for sure the services were indeed restarted? One way is to determine how long a service has been running or when they were started. The dilemma is the necessary information isn’t available using the Get-Service cmdlet or with CIM or WMI using the Get-CimInstance or Get-WmiObject cmdlets with the Win32_Service class.

An Uncommon Cause for IIS 503 Service Unavailable Errors

Recently, while migrating IIS websites to a new server, I encountered “Service Unavailable HTTP Error 503. The service is unavailable.” errors, but only for HTTPS, while HTTP worked fine. Depending on the scenario, the problem could have just as easily impacted HTTP. The server was listening on port 443: Get-NetTCPConnection -LocalPort 443 -State Listen If you ever encounter a problem like this, stop the web publishing service: Stop-Service -Name w3svc -PassThru Then check to see if the server is still listening on port 443:

Access Local Variables in a Remote Session with PowerShell

Occasionally I’ll come across a system with PowerShell version 2.0 on it that I need to run a remote command against which needs access to local variables. I can never remember how to accomplish that task so I thought I would write a blog about it as a reminder for myself and others who may find themselves in the same scenario. I’ll demonstrate each of the available options and whether or not they work on PowerShell version 5.

Safety to prevent entire script from running in the PowerShell ISE

I recently watched fellow Microsoft MVP Thomas Rayner present a session on regular expressions for the MVP Days virtual conference. Sometimes it’s the little things that are the biggest takeaways for me when I’m watching others present. One thing that wasn’t related to regular expressions that I noticed was Thomas’s way of preventing his entire script from running if F5 was accidentally pressed instead of F8 in the PowerShell ISE (Integrated Scripting Environment).

Configure Internet Connection Sharing with PowerShell

My test environment runs as Hyper-V VM’s on my IBM Thinkpad P50. I use ICS (Internet Connection Sharing) to shield my Hyper-V test environment virtual network from my production network connection. ICS allows me to temporarily give my test VM’s Internet access when needed without putting them directly on the production network. You might ask why? Because my test environment VM’s run things like DHCP servers that would cause havoc on the production network.

Not Specifying a Verb in PowerShell is an Expensive Shortcut

When working with PowerShell, there are lots of shortcuts that can be taken and while some of them may seem like a good idea at first, they usually end up costing you more trouble than they’re worth in the long run. I recently saw a Tweet that a fellow PowerShell enthusiast Tore Groneng‏ responded to which referenced running commands in PowerShell without specifying a verb. Such as “Service” for Get-Service.

Detect the presence of and remove CCleaner with PowerShell

Based on the news today, I thought I would share a couple of PowerShell code snippets to detect the presence of and silently uninstall CCleaner. You can detect the presence of CCleaner along with the version of it you have installed via the registry. Get-ItemProperty -Path HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Where-Object DisplayName -eq CCleaner You can use a similar command to run its uninstaller silently if it’s detected. if (Get-ItemProperty -Path HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Where-Object DisplayName -eq CCleaner -OutVariable Results) { & "$($Results.

PowerShell Version 2 Compatible Function to Determine Windows Firewall State

I recently had a need to perform some security auditing on an environment that still has some servers running PowerShell version 2 (PowerShell version 2 is deprecated). One of the things I needed to determine was whether or not the Windows firewall was enabled on each of the servers in the environment. Luckily, all of the servers at least had PowerShell remoting enabled. #Requires -Version 2.0 function Get-MrNetFirewallState { <# .

Remotely cleanup log and temp files from your Windows based servers with PowerShell

Setting up a scheduled task or job on individual servers to cleanup log and temp files just doesn’t scale very well because you have scheduled tasks or jobs setup on lots of individual servers that need to be maintained. Today it’s this server and tomorrow it’s two or three more. It’s much easier to setup one scheduled task or job on a server that’s designed for management to remotely cleanup the desired files on all of your servers.

Using Out-GridView to simplify selecting the region when managing Microsoft Azure with PowerShell

You’ve signed up for a Microsoft Azure account and you’ve installed the Azure Resource Manager PowerShell cmdlets on your computer. Install-Module -Name AzureRM -Force You login to Azure from PowerShell. You’ll normally see most people use Login-AzureRmAccount, but that command is an alias (Login isn’t an approved verb). Get-Alias -Definition Add-AzureRmAccount Login to Azure and provide the account login information when prompted: Add-AzureRmAccount Several of the cmdlets in the Azure Resource Manager PowerShell module require a location (a region) to be specified when creating things.

How to install Visual Studio Code and configure it as a replacement for the PowerShell ISE

If you follow me on Twitter, then I’m sure you’re aware that I’ve been using nothing but VS Code (Visual Studio Code) as a replacement for the PowerShell ISE (Integrated Scripting Environment) for the past couple of weeks and while I had tried it in the past, I didn’t previously think it was ready for prime time. That’s now changed with all of the updates and work that has gone into it.

PowerShell One-Liner to Audit Print Jobs on a Windows based Print Server

You’ve been tasked with auditing print jobs on your company’s Windows based print server to determine who is wasting so much paper, toner, and causing excessive wear and tear on printers. No budget exists for this task and you need to have something to show by the end of the day. You would probably start off by searching the Internet, but most of the results you’ll find to accomplish this task are over-complicated or simply don’t work.

PowerShell PackageManagement and PowerShellGet Module Changes in Windows 10 Version 1511, 1607, and 1703

Recently, I reloaded my computer and noticed a problem when I tried to install the latest version of the Pester PowerShell module using PowerShellGet. I loaded Windows 10 version 1703 (the creators update) which has PowerShell version 5.1 installed by default: Get-CimInstance -ClassName Win32_OperatingSystem -Property Caption, BuildNumber, OSArchitecture | Select-Object -Property @{label='Operating System';expression={$_.Caption}}, @{label='Version';expression={Get-ItemPropertyValue -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name ReleaseId}}, BuildNumber, OSArchitecture $PSVersionTable.PSVersion Pester version 3.4.0 ships with both Windows 10 version 1607 and 1703.

Remove all user defined variables without restarting the PowerShell Console or ISE

Recently, fellow Microsoft MVP Mickey Gousset asked me how to remove existing user defined variables from the PowerShell ISE (Integrated Scripting Environment) before running a script a second time without having to restart the ISE. While you could keep track of the variables you’ve used within your script to remove them once the script completes with the Remove-Variable cmdlet or by deleting them from the variable PSDrive, that can be a less than desirable solution for long and complicated scripts that define lots of variables.


Simple Obfuscation with PowerShell using Base64 Encoding

I recently received a question from someone wanting to know how I encoded a string of text on my blog site. Back in January of 2013, I competed in Jeff Hicks PowerShell Challenge that was held by TrainSignal. One of the questions had an encoded command which you were to decode. I figured out that the EncodedCommand parameter of PowerShell.exe could not only be used to run commands that are encoded with Base64, that it could also be used to easily decode a string of text that was encoded with Base64.

What is this Module Scope in PowerShell that you Speak of?

Last week I posted a blog article about a PowerShell script module that I had written with a few proof of concept commands to manage a Nimble Storage Area Network using their REST API. That module used a command to connect and authenticate to the storage device which needed to share a token with other commands in the module otherwise authentication would have to be performed for each command. I initially placed the token in a global variable even though I mentioned in the blog article that I’m not a big fan of globally scoping variables unless absolutely necessary (which I thought it was at the time).

PowerShell and the Nimble Storage REST API

If you read my previous blog article on PowerShell Function to Determine the Installed VSS Providers then you’re already aware that I recently migrated one of my customers to a Nimble Storage Area Network. While Nimble does have a PowerShell module and it’s decent, I wanted to see how difficult it is to work with their REST API directly with PowerShell. Their REST API documentation also seems to be decent.

PowerShell Function to Determine the Installed VSS Providers

I’ve been migrating one of my customers from some older EqualLogic storage area networks to a Nimble SAN. It has all been good with the exception of some problems with VSS (Volume Shadow Copy Service). They use Altaro for backups and from what I’ve found, Nimble and Altaro don’t play well together when it comes to VSS. Nimble’s software was installed on the Hyper-V hosts and all three vendors (Nimble, EqualLogic, and Altaro) VSS providers seemed to play well together until volumes were actually moved to the Nimble SAN.

Use PowerShell to Determine if Specific Windows Updates are Installed on Remote Servers

It has been a crazy week to say the least. If you’re like me, you wanted to make sure that the specific Windows updates that patch the WannaCry ransomware vulnerability have been installed on all of your servers. I’ve seen a lot of functions and scripts this week to accomplish that task, but most of them seem too complicated in my opinion. While it’s personal preference, I also always think about whether I should use a PowerShell one-liner, script, or function.

Retrieve Information about your Favorite Podcast with PowerShell

This past weekend, I attended the 2017 Atlanta MVP Community Connection. While there, I met fellow Microsoft MVP Allen Underwood who is one of the co-host of the {CodingBlocks}.NET podcast. I listened to their podcast on my trip back home from Atlanta and later discovered that their podcast has an RSS feed for episodes. A simple PowerShell one-liner can be used to retrieve information about each episode of their podcast:

PowerShell Function to Determine PSSessions to your Servers

This past week, I needed to determine if anyone had a PSSession connected to any of the servers that I support. This is fairly easy to accomplish with a PowerShell one-liner, but I can never remember the syntax so I decided to create a reusable function to accomplish the task. #Requires -Version 3.0 function Get-MrRemotePSSession { <# .SYNOPSISRetrieves a list of the Windows PowerShell sessions that are connected to the specified remote computer(s).

PowerShell One-Liner to Query multiple WMI Classes with a CIM Session

Today I thought I would share a one-liner that I recently wrote to query the Manufacturer, Model, and Serial Number information from numerous remote servers. Sounds simple enough, right? This one-liner starts out by using my New-MrCimSession function to create a CIM session to each of the specified servers. This function automatically determines if the remote server supports the WSMan protocol and falls back to DCom if it doesn’t: Get-CimSession | Select-Object -Property Name, ComputerName, Protocol Two different WMI classes are needed to retrieve the necessary information.

Determine the Default Password Policy for an Active Directory Domain with PowerShell

I’ve been working with PowerShell since the version 1.0 days and I’m still amazed that I find cmdlets that I didn’t know existed. Back in 2003, I had written some PowerShell code to query group policy for the lockout policy of an Active Directory domain. It used code similar to what’s shown in the following example which requires the GroupPolicy PowerShell module that installs as part of the RSAT (Remote Server Administration Tools).

Test Active Directory User Accounts for a Default Password with PowerShell

How do you control password resets in your environment? I’ve worked for numerous companies where their forgotten password reset process was all over the board. Hopefully you have a process in place that allows you to sleep at night. Even with the best policies and procedures in place, what happens when someone on your help desk staff resets a users password to some default password and forgets to set the account so the password has to be changed at next logon?

Video: PowerShell Non-Monolithic Script Module Design

This past Tuesday night, I presented a session on “PowerShell Non-Monolithic Script Module Design” for the Arizona PowerShell Users Group. The video from that presentation is now available. The presentation begins at 10 minutes and 30 seconds seconds into the video. The presentation materials to include the slide deck and code can be found in my presentations repository on GitHub. µ

PowerShell Function to Determine the Hyper-V Host for a VM

This week, I thought I would share a PowerShell function that I wrote to determine what Hyper-V host server a VM (virtual machine) resides on. In this scenario, you have no idea which Hyper-V host a VM resides on. #Requires -Version 3.0 function Get-MrVmHost { <# .SYNOPSISDetermines the HyperV host virtualization server for the specified virtual machines. .DESCRIPTIONGet-MrVmHost is an advanced function for determining the HyperV host virtualiztion server for one or more VMs (virtual machines).

Convert, Resize, and Optimize VHD and VHDX files with PowerShell

I recently received an email from someone who attended one of my presentations asking if I had a blog article on using PowerShell to compact and optimize VHD files. Since I didn’t have a blog article on that subject, I decided to create one. The process itself is fairly simple. The examples shown in this blog article are being run on a Windows 10 computer which has Hyper-V enabled on it.

How to add your PowerShell blog to Planet PowerShell

Do you blog about PowerShell? If so, consider adding your blog site to Planet PowerShell which is an aggregator of content from PowerShell Community members. There are some guidelines for submission on their GitHub page so be sure to take a look at it before continuing. Instructions for adding your blog also exists on that page, but I’ve recently seen a number of tweets about it being too difficult or too much work.

PowerShell One-Liner to Disable Active Directory Accounts and Log the Results to a SQL Server Database

The new PowerShell cmdlets that are part of the SQLServer PowerShell module that’s distributed as part of SSMS (SQL Server Management Studio) 2016 make it super easy to write the output of PowerShell commands to a SQL Server database. The ActiveDirectory PowerShell module that’s part of the RSAT (Remote Server Administration Tools) is also required by the code shown in this blog article. This PowerShell one-liner retrieves a list of Active Directory users who have not logged in within the past 120 days, are enabled, and exist in the Adventure Works OU (Organizational Unit).

Managing Altaro VM Backup with PowerShell

Recently, I decided to try to determine if there was a way to manage Altaro VM Backup with PowerShell. I figured there must be some database, files, or something that I could at least query with PowerShell. What I found is Altaro has a RESTful API and they have numerous PowerShell scripts for working with it. In Altaro version 7, there are 33 PowerShell scripts located in the “C:\Program Files\Altaro\Altaro Backup\Cmdlets” folder if you took the defaults during the installation, otherwise they’re wherever you installed Altaro.

Video: PowerShell 101 – The No-Nonsense Beginner’s Guide to PowerShell

Last week, I announced a new book for PowerShell beginners that I’m self-publishing. I decided to create a short video about the book and cover the topics from Chapter 1. The video can also be found on YouTube.com. The book (PowerShell 101: The No-Nonsense Beginner’s Guide to PowerShell) can be found on Leanpub.com. µ

Beware of the PowerShell Update-ModuleManifest Function

I recently presented a session for the Mississippi PowerShell User Group on PowerShell Non-Monolithic Script Module Design. While preparing for that session, I discovered that a problem I had previously experienced with Update-ModuleManifest when trying to update the FunctionsToExport section when FormatsToProcess is specified appeared to be resolved in PowerShell version 5.1 (I’m running build 14393). The details of this bug can be found here. I also noticed that Nicholas Getchell had written about this problem being resolved on his blog.

Using PowerShell to Audit Antivirus Updates on your Servers

How often do you check to make sure that things like antivirus has received the latest definition files on all of your servers? There’s probably some centralized GUI interface somewhere that you could log into and check. The antivirus product itself may even have some sort of notification system that sends alerts if the updates fail. Both of those options provide data in a format that can’t be worked with and what happens if something falls through the cracks?

No PowerShell Cmdlet to Start or Stop Something? Don’t Forget to Check for Methods on the Get Cmdlets

Many PowerShell commands return output in the form of objects (some return nothing at all). An example of this is shown in the following example where properties and their corresponding values are returned. CommandType is a property and Cmdlet is the value for that particular property for each of the results: Get-Command -Noun Service -Module Microsoft.PowerShell.Management Keep in mind that what is shown in the default output may not be the actual property names (compare the default output from Get-Process to the properties listed from Get-Process | Get-Member for an example of this).

Loop through a collection of items with the Pester TestCases parameter instead of using a foreach loop

One of the huge benefits of attending in-person technology events is getting to network with others. While at the MVP Summit last month I had a chance to demonstrate some of my PowerShell code and Pester tests to Jim Truher. I was developing the code and tests for a session to present for the PowerShell Virtual Chapter of SQL PASS (the code and a video of that presentation can be found here).

Locations for Comment-based Help in PowerShell Functions

One of the first things you’ll learn when beginning with PowerShell is how to use the help system. When working from the PowerShell console, I use the help function and omit the Name parameter since it’s positional and then specify the name of the cmdlet that I’m looking for help on as shown in the following example. help Get-HotFix This same type of standardized help can be added to your PowerShell functions and scripts which makes it easy for others to learn how to use them.

Write a GUI on Top of Existing PowerShell Functions with SAPIEN PowerShell Studio 2016

This blog article will demonstrate how to write a GUI on top of your existing PowerShell functions using SAPIEN PowerShell Studio 2016. I’ve previously written a couple of functions for managing SQL Server agent jobs. These two functions, Get-MrSqlAgentJobStatus and Start-MrSqlAgentJob can be found in my SQL repository on GitHub. Launch PowerShell Studio. Select file, the arrow next to new, and new form: For this particular GUI, I’ll select the “Dialog Style Template” since I want a fixed border without any minimize or maximize buttons:

PowerShell Function to Check the Status of a SQL Agent Job using the .NET Framework

My previous blog article demonstrated how to start a SQL agent job using the .NET Framework from PowerShell to eliminate the dependency of needing the SQL Server PowerShell module or snap-in on the machine where the command is being run from. There’s not much use of blindly starting a SQL agent job without being able to check the status of it so I decided to write another function to accomplish that task.

Start a SQL Agent Job with the .NET Framework from PowerShell

As of this writing, the most recent version of the SQLServer PowerShell module (which installs as part of SQL Server Management Studio) includes cmdlets for retrieving information about SQL agent jobs, but no cmdlets for starting them. Get-Command -Module SQLServer -Name *job* I recently ran into a situation where I needed to start a SQL agent job from PowerShell. The solution needed to be a tool that others could use who may or may not have the SQLServer module, SQLPS module or older SQL Server snap-in installed.


PowerShell Function to Validate Both IPv4 and IPv6 Addresses

Last week, I wrote a blog article about the IP address type accelerator in PowerShell not being 100% accurate and I demonstrated using it for parameter validation. If you want to simply validate an IP Address and return a Boolean, that’s a little more complicated so I decided to write a function to perform that task along with providing detailed information about the IP address when an optional detailed parameter is specified:

PowerShell IP Address Type Accelerator Not 100% Accurate

Testing whether or not an IP Address is valid with PowerShell is a fairly simple process with the [ipaddress] type accelerator if your goal is to validate input for a script or function as shown in the following code example: function Test-ValidInput { [CmdletBinding()] param ( [ipaddress]$IpAddress ) Write-Output $true } When a valid IP address is specified, the function continues and when an invalid IP address is specified, the function terminates immediately and returns an error message:

PowerShell Function to Determine Available Drive Letters

I’ve recently been working on some file server drive migrations. One of the steps I needed to perform was to change the drive letter of a current drive to a different available drive letter so I decided to write a PowerShell function to accomplish the task of determining what drive letters are available. The Get-MrAvailableDriveLetter function shown in the following code example will run on systems with PowerShell version 2.0 or higher (I tested it all the way down to version 1.

Create a Certificate to Encrypt MOF Passwords that’s Compatible with DSC in PowerShell version 5.0

I’ve previously written a blog article titled Use a certificate with PowerShell DSC to add a server to Active Directory without hard coding a password where I had created a certificate that was used to encrypt the password in a PowerShell version 4 DSC (Desired State Configuration) MOF file. The same procedure in PowerShell v5 generates an error stating the certificate cannot be used for encryption: ConvertTo-MOFInstance : System.ArgumentException error processing property ‘Password’ OF TYPE ‘MSFT_Credential’: Certificate ‘6EBFB5C88AB4B8C9E3B8E30E88A5D071D6735464’ cannot be used for encryption.

Simplifying my PowerShell version 5 Class Based DSC Resource for Configuring Remote Desktop

Last week I wrote a blog article about a PowerShell Desired State Configuration Class Based Resource for Configuring Remote Desktop. Since then I’ve discovered and learned a couple of new things about enumerations in PowerShell that can be used to simply the code even further. My original code used a couple of enumerations which I’ve removed to show how they can be used to further simply the code: class RemoteDesktop { [DscProperty(Key)] [string]$UserAuthenication [DscProperty(Mandatory)] [string]$Ensure [RemoteDesktop]Get() { $this.

PowerShell Desired State Configuration Class Based Resource for Configuring Remote Desktop

Prior to PowerShell version 5 being released, I had written a PowerShell version 4 compatible DSC (Desired State Configuration) resource named cMrRDP for configuring Remote Desktop. It can be found in my DSC respository on GitHub. The recommendation at that point was to use the letter “c” as the prefix for community created DSC resources. The current recommendation is to no longer use the “c” prefix for DSC resources. Steven Murawski wrote a blog article titled DSC People - Let’s Stop Using ‘c’ Now that I recommend taking a look at.

Store and Retrieve PowerShell Hash Tables in a SQL Server Database with Write-SqlTableData and Read-SqlTableData

In my blog article from last week, I demonstrated using several older open source PowerShell functions to store the environmental portion of the code from operational validation tests in a SQL Server database and then later retrieve it and re-hydrate it back into a PowerShell hash table. Earlier this week, a new release of the SQLServer PowerShell module was released as part of SSMS (SQL Server Management Studio): It includes three new cmdlets, two of which can be used to store and retrieve data in a SQL Server database from PowerShell instead of the older open source ones that I demonstrated in the previously referenced blog article from last week.

Store Environmental Code in a SQL Server Database for PowerShell Operational Validation Tests

I’ve previously published articles on separating environmental code from structural code for both DSC (Desired State Configuration) and Operational Validation or Readiness Tests. This article picks up where I left off last week in Separating Environmental Code from Structural Code in PowerShell Operational Validation Tests. As many existing open source PowerShell functions as possible have been used in the examples shown in this blog article instead of re-inventing the wheel and rewriting everything from scratch.

Separating Environmental Code from Structural Code in PowerShell Operational Validation Tests

Do you ever feel like you’re writing the same operational validation or readiness test over and over again? I’m not sure about you, but I don’t like repeating myself by rewriting the same code because it creates a lot of technical debt. There has to be a better way . Why not take the same thought process from DSC (Desired State Configuration) and separate the environmental portion of the code from the structural portion and apply it to operational tests so the same or similar code isn’t repeated over and over again?

Use PowerShell and Pester for Operational Readiness Testing of Altaro VM Backup

I’ve recently been working with Altaro VM Backup and I must say that I’ve been very impressed with the ease and simplicity of the product. The back-end portion of the product can run on a virtual or physical server with or without the GUI (Server Core is supported). It can backup to just about any type of drive (local disk, UNC path, USB drive, etc). It doesn’t require SQL Server. In my environment, adding a Hyper-V server (running Windows Server 2012 R2) installed a service on the Hypervisor, but did not require a reboot.

Learning Existing and Setting Up New Keyboard Shortcuts in Visual Studio Code for the PowerShell Enthusiast

I’ve recently made myself start using Visual Studio Code for writing some of my PowerShell code and I thought I would share a few of the tips that I’ve learned. If you haven’t read my blog article titled Use the PowerShell Console from within Visual Studio Code, I definitely recommend taking a look at it as today’s blog article assumes that you’ve already made those modifications to your Visual Studio Code environment.

Use the PowerShell Console from within Visual Studio Code

I recently revisited Visual Studio Code. I was looking for a markdown editor and remembered seeing a tweet a few weeks ago saying that VS Code could be used to edit markdown. It supports markdown by default, although I would recommend adding a spell check extension to it. I thought that it would be convenient if I could write my PowerShell code right from within the same interface that I’m writing other things such as markdown.

Something to -notlike about the -like operator in PowerShell

I recently ran into a problem with the PowerShell like operator that I wanted to share since what’s occurring may not be immediately apparent. The like operator allows for comparison tests of strings using wildcard characters instead of exact matches. I think of it being similar to the match operator except like uses simple wildcards instead of regular expressions. 'Microsoft Windows 10 Enterprise' -like '*Windows 10*' Easy enough, right? A string on the left and another string with wildcards on the right.

PowerShell function for creating a PowerShell function template

A couple of weeks ago I published a blog article PowerShell function for creating a script module template and I thought I would follow-up that article with the same type of function for creating a PowerShell function template. Instead of having to remember things like checking to make sure an approved verb is used, that a Pester test is created, and comment based help is entered in the right format, a template such as the one shown in the following code example can make your life much simpler.

PowerShell function for creating a script module template

I’m curious to know what process others use to create new PowerShell script modules? Since the initial process of creating a PowerShell script module seems redundant and tedious, I decided to create a function that creates a template for new script modules that I create which includes creating both the script module PSM1 and manifest PSD1 files and filling in the information that I would normally include: function New-MrScriptModule { <# .

PowerShell function to find information about module updates

I decided to update the one liner from my blog article last week and take it a step further by turning it into a reusable tool that displays information about module updates that are available regardless of where they were installed from. #Requires -Version 3.0 -Modules PowerShellGet function Find-MrModuleUpdate { <# .SYNOPSISFinds updates for installed modules from an online gallery that matches the specified criteria. .DESCRIPTIONFind-MrModuleUpdate is a PowerShell advanced function that finds updates from an online gallery for locally installed modules regardless of whether or not they were originally installed from an online gallery or from the same online gallery where the update is found.

Update Manually Installed PowerShell Modules from the PowerShell Gallery

There are PowerShell modules that ship with Windows 10 that weren’t installed from the PowerShell Gallery using PowerShellGet so they can’t be updated using the Update-Module cmdlet. This also applies for any modules that you’ve installed manually yourself. The following PowerShell script retrieves a list of the most recent version of the modules in the all users path for PowerShell modules. It determines which ones weren’t installed using PowerShellGet based on the hidden xml file that would exist in the module directory and then it determines if a newer version exists in one of the PowerShell Galleries that’s registered on your computer:

Video: PowerShell Toolmaking with Advanced Functions and Script Modules

I presented a session on PowerShell Toolmaking with Advanced Functions and Script Modules this past weekend at SQL Saturday #521 in Atlanta. I decided to make an attempt to record my session which was presented live in front of a packed room full of attendees: The recording turned out very well considering I used the built-in laptop microphone and I moved around during my presentation. The audio levels have been tweaked because they were often too low depending on how far away I was from the computer at any given point in time during the presentation.

Why isn’t Test Driven Development more widely adopted and accepted by the PowerShell community?

We’ve all heard that TDD (Test Driven Development) means that you write unit tests before writing any code. Most of us are probably writing functional or acceptance tests after the fact because the idea of Test Driven Development isn’t clearly defined, at least not in my opinion. I originally thought it meant to write thorough unit tests to test all functionality for a specific piece of code such as a PowerShell function from start to finish before writing any of the production code for the function itself.

Don’t use Default Manifest Settings when Dot-Sourcing Functions in PS1 Files from a PowerShell Script Module

I briefly mentioned and demonstrated something similar to this at the end of one of my sessions at the PowerShell and DevOps Global Summit 2016. Since then, I’ve tested more which has led to a better solution. We’ve all been taught that it’s best practice to use a Requires statement in our functions that specifies the required PowerShell version along with any module dependencies, but following this best practice has one unexpected side effect when dot-sourcing functions in PS1 files from a PSM1 script module.

Be Mindful of Object Types when Writing Unit Tests and Performing Operational Validation in PowerShell with Pester

I recently wrote a Pester test that performs some basic operational validation (smoke tests) of SQL Servers. I’ve previously written similar tests as functions as shown in my Write Dynamic Unit Tests for your PowerShell Code with Pester blog article, but I decided to write this one as a script with the naming convention that seems to be recommended. The name of this particular test is Validate-MrSQLServer.Tests.ps1. You’re probably thinking Validate isn’t an approved verb and you’re right, but this isn’t a function, it’s a script.

Keeping Track of PowerShell Functions in Script Modules when Dot-Sourcing PS1 Files

I’m picking up where I left off in a previous blog article Write Dynamic Unit Tests for your PowerShell Code with Pester. I’m using the dynamic Test-MrFunctionsToExport Pester test that I wrote about in that previous blog article. Currently, the test is failing for my MrToolkit module that’s part of my PowerShell repository on GitHub: Test-MrFunctionsToExport -ManifestPath .\GitHub\PowerShell\MrToolkit\MrToolkit.psd1 Based on the previous results, I can easily determine that more functions exist in the module folder than are specified in the FunctionsToExport section of the module manifest.

Video: Creating a Custom PowerShell Toolkit to Demystify DSC

Last week, on Monday (April 4th, 2016), I presented a session at the PowerShell and DevOps Global Summit 2016 on “Creating a Custom PowerShell Toolkit to Demystify the Intricacies of Desired State Configuration”. The video from that presentation is now available: Here’s the abstract or synopsis for this presentation: “DSC (Desired State Configuration) can be very complicated when working in an environment where nodes are set to retrieve their configuration from a pull server.

Video: Building Unconventional SQL Server Tools in PowerShell

Last week, on Wednesday (April 6th, 2016), I presented a session at the PowerShell and DevOps Global Summit 2016 on “Building Unconventional SQL Server Tools in PowerShell with Functions and Script Modules”. The video from that presentation is now available: Here’s the abstract or synopsis for this presentation: “Have you ever had records from a SQL Server database table come up missing? Maybe someone or some process deleted them, but who really knows what happened to them?

Write Dynamic Unit Tests for your PowerShell Code with Pester

I wrote a blog article on: PowerShell Script Module Design: Placing functions directly in the PSM1 file versus dot-sourcing separate PS1 files earlier this year and I’ve moved all of my PowerShell script modules to that design and while today’s blog article isn’t part of a series, that previous one is recommended reading so you’re not lost when trying to understand what I’m attempting to accomplish. Most unit tests that I’ve seen created with Pester for testing PowerShell code are very specific, the tests generally have hard coded values in them, and live in source control along with the code that they’re designed to test.

Converting a SQL Server Log Sequence Number with PowerShell

As demonstrated in one of my previous blog articles Determine who deleted SQL Server database records by querying the transaction log with PowerShell, someone or something has deleted records from a SQL Server database. You’ve used my Find-MrSqlDatabaseChange function to determine when the delete operation occurred based on information contained in either transaction log backups or the active transaction log: Find-MrSqlDatabaseChange -ServerInstance SQL01 -Database pubs -StartTime (Get-Date -Date '03/28/2016 14:55 PM') You’re ready to perform point in time recovery of the database to the LSN (Log Sequence Number) just before the delete occurred but the LSN provided from the transaction log is in a different format than what’s required to perform a restore of the database.

Pro Tips from the Trenches: The Resolve-Path PowerShell cmdlet

You’re designing a reusable tool in PowerShell and decide a function is the most appropriate type of command to accomplish the task at hand. It will accept a FilePath parameter which will be used to specify both the path and filename to a destination file. The path should already exist, but the file may or may not already exist. For simplicity, I’ve stripped away the complexity so the problem is more apparent.

Run 350 Nano Server Virtual Machines on a Lenovo ThinkPad P50 with Hyper-V in Windows 10

If you’re a frequent reader of my blog articles on this site, then you’re already aware that I recently purchased a Lenovo ThinkPad P50 with a Xeon CPU, 64 GB of RAM, and upgraded it to SSD hard drives. I tweeted that it wouldn’t be complete without a few PowerShell stickers: I received a response from Jeffrey Snover wanting to know how many Nano server VM’s could be run on it:

Use PowerShell to Add Active Directory Users to Specific Groups based on a CSV file

I recently responded to a post in a forum about adding Active Directory users to groups with PowerShell based on information contained in a CSV (Comma Separated Values file format). I thought I would not only share the scenario and solution that I came up with but also elaborate on adding additional functionality that may be desired. In this scenario, you’ve been provided with a CSV file that contains a list of Active Directory users and the groups that they should be a member of as shown in the following image:

Configuring the PowerShell ISE for use with Git and GitHub

The goal of this blog article is to configure the PowerShell ISE (Integrated Scripting Environment) so the management of Git version control can be performed from it. Most tutorials you’ll find will attempt to lead you down the path of using SSH instead of HTTPS to synchronize your repositories to GitHub from the command-line but that’s really over-complicated and unnecessary if you’re using a Windows based machine. The client machine used in this blog article runs the 64 bit version of Windows 10 Enterprise Edition.


#PowerShell Script Module Design: Placing functions directly in the PSM1 file versus dot-sourcing separate PS1 files

So you’ve transitioned from writing PowerShell one-liners and scripts to creating reusable tools with functions and script modules. You may have started off by simply placing your functions in a PS1 file and dot-sourcing it. That leaves a lot to be desired though since it’s a manual process and even if you’ve added some code to your profile to accomplish that task, the experience still isn’t as good as it could be.

Building logic into PowerShell functions to nag users before their Active Directory password expires

This week I’m sharing a couple of PowerShell functions that are a work in progress to nag those users who seem to never want to change their passwords. I can’t tell you how many times the help desk staff at one of the companies that I provide support for receives a call from a user who is unable to access email or other resources on the intranet. The problem? They have run their password down to the point where they arrive in the morning, log into their computer without issue, and during the day while they’re working their password expires which cuts them off from Intranet resources such as email and websites that require authentication.

Video: Demystifying Active Directory User Account Lockouts with PowerShell

A few months ago I created an audition video for Pluralsight on “Demystifying Active Directory User Account Lockouts with PowerShell” and I thought I would share that video with you, the readers of my blog site: You can also find this video on my YouTube channel. µ

Use PowerShell to Determine Services with a StartType of Automatic or Manual with Trigger Start

Newer Windows operating systems have numerous services that are set to start automatically or manually with a triggered start. The following image is from a machine that’s running Windows 10 Enterprise Edition (version 1511): The problem is when you’re trying to determine whether or not all of the services that are set to start automatically are running or not. These trigger start services can’t be filtered out using the Get-Service cmdlet or with WMI and they aren’t necessarily suppose to be running.

StartType property added to Get-Service in PowerShell version 5 build 10586 on Windows 10 version 1511

If you’ve used PowerShell for more than 5 minutes, then you probably have some experience with the Get-Service cmdlet. As you could have guessed if you didn’t already know, the Get-Service cmdlet retrieves information about Windows services. Depending on what you’re trying to accomplish, that particular cmdlet could leave a lot to be desired. Want to know if a service is running? No problem. Want to know what the startup type is for one or more services?


Installing Visual Studio Code and the PowerShell Extension

Last week Microsoft released a new version of Visual Studio Code along with an extension for writing PowerShell in it. Visit code.visualstudio.com to download Visual Studio Code. There’s also an update link on that page if you happen to have a version prior to 0.10.1. The PowerShell extension for Visual Studio Code only works with PowerShell version 5. Either Windows 8.1 with the WMF 5 Production Preview installed or Windows 10 is sufficient.

Using PSScriptAnalyzer to check your PowerShell code for best practices

Are you interested in learning if your PowerShell code follows what the community considers to be best practices? Well, you’re in luck because Microsoft has a new open source PowerShell module named PSScriptAnalyzer that does just that. According to the GitHub page for PSScriptAnalyzer, it’s a static code checker for PowerShell modules and scripts that checks the quality of PowerShell code by running a set of rules that are based on best practices identified by the PowerShell team and community.

Using Pester and the Operation Validation Framework to Verify a System is Working

If you haven’t seen the Operation Validation Framework on GitHub, it’s definitely something worth taking a look at. This framework allows you to write Pester tests to perform end-to-end validation that a system is operating properly. Pester is typically used to perform test driven development or unit testing on your PowerShell code, but in this scenario it’s used for operational testing. You need to have Pester installed, but if you’re running Windows 10 then you already have Pester.

Solving DSC Problems on Windows 10 & Writing PowerShell Code that writes PowerShell Code for you

I recently ran into a problem with DSC on Windows 10 when trying to create MOF files with DSC configurations that work on other operating systems. An error is generated when the friendly name for a DSC resource contains a dash and that friendly name is specified as a dependency for another resource. I know that only certain characters are allowed in the name that’s specified for DependsOn and I’ve run into similar problems with things such as IP addresses due to the dot or period, but the dash works in other operating systems at least with the production preview of PowerShell version 5, but not with the version of PowerShell version 5 that ships with Windows 10:

Video & Presentation Materials: October Omaha PowerShell User Group Meeting

This past Tuesday, I presented a session on Using PowerShell Desired State Configuration in your On-Premises Datacenter for the Omaha PowerShell User Group. During that presentation I demonstrated tips and tricks that I’ve learned while implementing systems in multiple data-centers using DSC. The meeting was recorded and the video is now available: µ

Using Pester to Test PowerShell Code with Other Cultures

I recently published a blog article on unexpected case sensitivity in PowerShell. An example in that blog article uses the contains method which is indeed case sensitive. One of the workarounds that I demonstrated was to convert whatever the user entered to upper case using the ToUpper() method. One of the reasons I like blogging is that many times there are things that I may not have considered and sometimes things that I wasn’t even aware of so in addition to sharing my knowledge with others, I often times learn in the process based on the feedback I receive about my blog articles and this was one of those times.

Some Cases of Unexpected Case Sensitivity in PowerShell

I’m sure that you’ve all heard that PowerShell is case insensitive, right? Most things in PowerShell are indeed case insensitive and what is case sensitive is normally expected behavior, but I’ve come across a number of things in PowerShell that are case sensitive that don’t work as I would expect them to which are listed in this blog article. One of the first things that I discovered in PowerShell that is case sensitive that you wouldn’t have thought would be is the Region keyword that was introduced in PowerShell version 3:

Announcing the Winner of the PowerShell TFM Book Contest

Two weeks ago, I started a PowerShell contest which required the participants to convert a string of text to title case. I didn’t specifically say title case but I explained that the first letter of each word should be converted to upper case and all remaining letters in each word should be converted to lower case. This was because a search on how to convert to title case with PowerShell gave away a good portion of the answer.

PowerShell: Filter by User when Querying the Security Event Log with Get-WinEvent and the FilterHashTable Parameter

I recently ran across something interesting that I thought I would share. The help for the FilterHashTable parameter of Get-WinEvent says that you can filter by UserID using an Active Directory user account’s SID or domain account name: help Get-WinEvent -Parameter filterhashtable Notice that the help also says the data key can be used for unnamed fields in classic event logs. I often hear the question wanting to know what the valid key pairs are for the hash table.

Windows PowerShell TFM Book Contest and Giveaway

Today is the first day of Autumn also known as fall here in North America and it’s my favorite time of the year. If nothing else, you’ve got to love the cooler weather and the changing of tree leaf colors. Last fall, a new version of the Windows PowerShell TFM book that I co-authored along with Jason Helmick was published and strangely enough, its design is remarkably similar to the colors that are associated with Autumn.

Working around UAC (User Access Control) without running PowerShell elevated

We’ve all heard it and experienced the problem where you can’t perform tasks such as stopping a service on the local machine with PowerShell unless your running PowerShell elevated. If the title bar doesn’t say “Administrator” then you’ll end up with these types of error messages: Stop-Service -Name BITS -PassThru If PowerShell remoting is enabled on the local machine, you can simply remote back into it to perform the task without having to run PowerShell elevated:

Video & Presentation Materials: September 2015 PowerShell.org Advanced Functions TechSession Webinar

Last week I presented a session titled The Top 10 Considerations When Writing PowerShell Advanced Functions for the September 2015 PowerShell.org TechSession Webinar. The video from that presentation is now available: I received a question during the presentation about how to determine what the type accelerators are and the answer to that question can be found in this Hey, Scripting Guy! Blog article (thanks to Nicholas Getchell for the link to that article).

#PowerShell: DelayedAutoStart Property added to the Win32_Service WMI Class in Windows 10 RTM

I recently discovered that Windows 10 adds a DelayedAutoStart property to the Win32_Service WMI Class: Get-CimInstance -ClassName Win32_Service -Filter "Name = 'MapsBroker'" | Format-List -Property * I’ve verified that this property does not exist on prior operating systems such as Windows 8.1 even when they’re updated to the production preview version of PowerShell version 5. I had written a Hey, Scripting Guy! Blog article on how to query the registry of remote machines to Exclude Delayed Start Services when Checking Status with PowerShell that shows how to retrieve the necessary information to accomplish this task on other OS’s, but it’s nice to see that Microsoft has finally made this information easier to retrieve.

#PowerShell: Splatting a Local Hash Table in a Remote Session

I’m sure that most people who use PowerShell on a regular basis are familiar with the Using variable scope modifier which allows for the use of local variables in a remote session. This functionality was introduced with PowerShell version 3: $MyVar = 'Bits', 'W32time' Invoke-Command -ComputerName DC01 { Get-Service -Name $Using:MyVar } A fairly simple concept, right? But wait a minute, did you know that you can also define a local hash table to be used with splatting in a remote session using this same concept?

My Solution: August 2015 PowerShell Scripting Games Puzzle

A couple of months ago, PowerShell.org announced that the PowerShell Scripting Games had been re-imagined as a monthly puzzle. In August, the second puzzle was published. The instructions stated that a one-liner could be used if you were using a newer version of PowerShell. A public JSON endpoint can be found at https://www.telize.com/geoip and your goal is to write some PowerShell code to display output similar to the following: longitude latitude continent_code timezone --------- -------- -------------- -------- -115.

Video from Atlanta TechStravaganza 2015: Using PowerShell Desired State Configuration in your On-Premises Datacenter

This past Friday, I presented a session titled Using PowerShell Desired State Configuration in your On-Premises Datacenter at Atlanta TechStravaganza 2015. Fellow PowerShell MVP Stephen Owen took this photo as I was preparing for my session: Another fellow PowerShell MVP, Jonathan Walz of the PowerScripting Podcast, recorded all of the sessions in the PowerShell track which can be found on their YouTube channel. Several presentations are included in each of the videos and mine is approximately the first 43 minutes of this video:

Change a Machine’s Subnet Mask with PowerShell Version 2

I recently worked on a project that required me to change the subnet mask on multiple servers at a remote location. The main problem was that many of the servers were still running PowerShell version 2, but luckily PowerShell remoting was enabled on all of them. Invoke-Command -ComputerName (Get-Content -Path C:\MyServers.txt) { $NICs = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "IPEnabled = 'true' and DHCPEnabled = 'False'" | Where-Object {$_.ipaddress -like '192.168.0.*'} foreach ($NIC in $NICs){ $ip = $NIC.

My Solution: July 2015 PowerShell Scripting Games Puzzle

Last month, PowerShell.org announced that the PowerShell Scripting Games had been re-imagined as a monthly puzzle and the first puzzle was published. The instructions stated to use a PowerShell one-liner that produces the following output. No more than one semicolon should be used, do not use the ForEach-Object cmdlet or one of its aliases. The one-liner should be able to target more than one computer and feel free to go crazy with a really short one-liner with aliases and whatever else.

Using PowerShell for Remote Server Administration in Windows 10 RTM without the RSAT tools

You’ve updated to the RTM version of Windows 10 only to learn that the remote server administration tools aren’t available as of yet: Get-ADUser -Identity mikefrobbins Let’s say for example the Active Directory PowerShell module is something that you use on a daily basis and it’s necessary to perform your day to day responsibilities. Well, you’re out of luck because the RSAT tools aren’t available yet, but before you consider using RDP or the GUI to perform your duties, let’s take a look at a viable solution in PowerShell.

The PowerShell return keyword

The return keyword is probably the most over used keyword in PowerShell that’s used in unnecessary scenarios. You’ll often find it used to simply return the output of a function: function New-MrGuid { $Guid = [System.Guid]::NewGuid() Return $Guid } In that scenario, using the return keyword is totally unnecessary. If you do want to return the value of the variable, simply let PowerShell take care of returning the output: function New-MrGuid { $Guid = [System.

Determine who deleted SQL Server database records by querying the transaction log with PowerShell

Have you ever had a scenario where records from one or more SQL server database tables mysteriously came up missing and no one owned up to deleting them? Maybe it was an honest mistake or maybe a scheduled job deleted them. How do you figure out what happened without spending thousands of dollars on a third party product? You need to determine what happened so this doesn’t occur again, but the immediate crisis is to get those records back from a restored copy of the database.

Query SQL Server from PowerShell without the SQL module or snapin

There are several different ways to query a SQL Server from PowerShell but most often you’ll find that they’re dependent on the SQL PowerShell module or snapin. To eliminate that dependency, you can query a SQL Server from PowerShell using the .NET framework. There are several different options to accomplish this including using a DataReader or a DataSet and there are plenty of tutorials on those topics already on the Internet so there’s no reason to duplicate that information here.

PowerShell $Profile: The six options and their precedence

There are a total of six different profiles than can be created in PowerShell by default. Four of them can exist that are applied to the PowerShell console: $PROFILE | Format-List -Force And four of them can also exist that are applied to the PowerShell ISE (Integrated Scripting Environment): $profile | Format-List -Force Two of the profiles are the same between the PowerShell console and ISE which gives you a total of six possible profile combinations that can be used to load items when you start PowerShell depending on if you want it to load for all users or for the current user and for all hosts or for the current host.

Function to Import the SQLPS PowerShell Module or Snap-in

The SQL Server 2014 basic management tools have been installed on the Windows 8.1 workstation that’s being used in this blog article. When attempting to import the SQLPS (SQL Server PowerShell) module on your workstation, you’ll be unable to import it and you’ll receive the following error message if the PowerShell script execution policy is set to the default of restricted: Import-Module -Name SQLPS Import-Module : File C:\Program Files (x86)\Microsoft SQL Server\120\Tools\PowerShell\Modules\SQLPS\Sqlps.

Walkthrough: An example of how I write PowerShell functions

A couple of days ago I posted a blog article titled PowerShell function: Test-ConsoleColor provides a visual demonstration of the foreach scripting construct and today I thought I would walk you through that function step by step since it’s what I consider to be a well written PowerShell function. It starts out by using the Requires statement to require at least PowerShell version 3 or it won’t run. It also requires that the PowerShell Community Extensions module be installed since it uses a function from that module and continuing without it only leads to errors:

Video: PS C:\> Get-Started -With ‘PowerShell for SQL Server’

I presented a beginner level session for the PowerShell Virtual Chapter of PASS yesterday titled “PS C:> Get-Started -With ‘PowerShell for SQL Server’”. The session is entry level PowerShell and designed for those people who haven’t yet embraced PowerShell because I often hear “How do I get started with PowerShell”? My new answer: Watch this video. The first two thirds or so of the presentation is more or less generic because the basics for someone who is just getting started with PowerShell are the same regardless of what product you’re using it with.

PowerShell function: Test-ConsoleColor provides a visual demonstration of the foreach scripting construct

Test-ConsoleColor is a PowerShell function that I recently wrote to provide a visual demonstration of how to loop through a series of objects in PowerShell using the foreach scripting construct, not to be confused with the ForEach-Object cmdlet. #Requires -Version 3.0 -Modules Pscx function Test-ConsoleColor { <# .SYNOPSISTests all the different color combinations for the PowerShell console. .DESCRIPTIONTest-ConsoleColor is a PowerShell function that by default iterates through all of the possible color combinations for the PowerShell console.

Using a .NET Enumeration for PowerShell Parameter Validation

I recently ran into an issue where I wanted to use the values from a .NET enumeration as the default values for a parameter. That was easy enough: function Test-ConsoleColorValidation { [CmdletBinding()] param ( [ValidateNotNullOrEmpty()] [string[]]$Color = [System.Enum]::GetValues([System.ConsoleColor]) ) $Color } Although the previous code met my initial requirements, I decided that I also wanted the user to be able to tab expand the values and to validate the values based on the list of colors found in the enumeration without a requirement of having to hard code the values.

Deploy Desired State Configuration Resources with an SMB based Pull Server

So you’ve either downloaded DSC resources from GitHub or you’ve created some DSC resources of your own and the LCM (Local Configuration Manager) on the servers in your environment is set to use an SMB based DSC pull server. To automatically deploy those custom resources with an SMB pull server, they need to be zipped up including their base directory and named ResourceName\_Version.zip. For example, the xSmbShare DSC resource that can be download from GitHub would be named xSmbShare\_1.

Create a DSC SMB Pull Server with DSC and separate the Environmental Config from the Structural Config

The machines used in this blog article are running Windows 8.1 and Windows Server 2012 R2. Both have the default version of PowerShell installed that shipped with those operating systems which is PowerShell version 4. The following configuration uses the xSmbShare and the PowerShellAccessControl DSC resources which can be downloaded from GitHub. These resources must exist on the machine where you’re authoring the DSC configuration and on the node that the configuration is being applied to.

Change the Recovery Model of a SQL Server database with the PowerShell SQL PSProvider

I recently set out to change the recovery model of a SQL Server database with PowerShell. There seems to be lots of information available on how to accomplish this task with PowerShell through SMO (SQL Server Management Objects) and using T-SQL wrapped inside the Invoke-Sqlcmd cmdlet. I even found lots of information about how to view the recovery model with the PowerShell SQL Server PSProvider, but when it came to actually changing the recovery model via the PSProvider, there was little if any information about how to accomplish that task.


Filtering by StartTime with the AWS PowerShell Cmdlets

I was recently trying to figure out how to return an AWS Storage Gateway snapshot by providing a value for the StartTime property and it wasn’t easy to say the least so I thought I would share my experience to save others the headache of figuring it out. Most of the tutorials you’ll find online show filtering something similar to this: $filter1 = New-Object Amazon.EC2.Model.Filter $filter1.Name = 'volume-id' $filter1.Value.Add('myvolumeid') $filter2 = New-Object Amazon.

PowerShell Advanced Functions: Can we build them better? With parameter validation, yes we can!

This blog article is the second in a series of blog articles that is being written on PowerShell advanced functions for PowerShell blogging week. If you haven’t already read the first article in this series: Standard and Advanced PowerShell functions written by PowerShell MVP Francois-Xavier Cat I recommend reading it also. What is parameter validation? In PowerShell, parameter validation is the automated testing to validate the accuracy of parameter values passed to a command.

Create a New Empty File with the PowerShell Out-File Cmdlet

A few weeks ago I was setting up OpenSSL on a Windows machine and I was following a Linux tutorial which used the touch command to create a new empty file. To accomplish the task of creating a new empty file with PowerShell, the most straight forward way is to use the New-Item cmdlet: New-Item -Name EmptyFile.txt -ItemType File I inadvertently discovered another way to create a new empty file with PowerShell which I thought I would share with you guys, the readers of my blog.

Use PowerShell to Create a Linux VM in Azure

In a couple of my previous blog articles, I’ve demonstrated how to create a storage account in Azure and how to create a reserved virtual IP address in Azure. Both of those items will be used in today’s blog article so I recommend reading through those previous blog articles if you haven’t already done so. The goal in this blog article is to build a CentOS based OpenLogic 7.0 VM in Azure except using PowerShell instead using the Azure portal website (GUI):

Automatically create a checksum and publish DSC MOF configuration files to an SMB pull server

You’ve configured one or more DSC (Desired State Configuration) SMB pull servers in your environment. You’ve also configured the target nodes appropriately. One problem that seems to be a constant problem in your environment when authoring and updating DSC configuration files (MOF files) is keeping track of what GUID belongs to which machine and it’s also a common problem to forget to update the corresponding checksum when a configuration file is updated.

Use PowerShell to Create a Reserved Virtual IP Address (VIP) in Azure

By default, the VM’s that you create in Azure will have a dynamic virtual IP address (VIP). Based on this article on Azure, you could simply create a DNS CNAME record for your custom domain and point it to the DNS name that you chose during the creation of your azure VM which should prevent any problems if the virtual IP address happens to change. Maybe you want a reserved virtual IP address for your Azure instance though?

Use PowerShell to create a Storage Account in Azure

You’ll need to sign up for an Azure account if you don’t already have one: https://azure.microsoft.com. There’s a free trial if you want to try it out. One thing I would suggest if you’ve never used Azure is to spend a little time in the GUI (your Azure account’s portal website) learning about it before you start trying to manage it with PowerShell. That’s the same advice I would give to anyone wanting to do something with PowerShell.

Using PowerShell Desired State Configuration to build the first domain controller in your Active Directory forest

If you’re a frequent reader of the blog articles on this site, then you know that I’ve been working on using Desired State Configuration to build my test lab environment that runs as Hyper-V VM’s on my Windows 8.1 computer. If you would like to know the current state of my test environment, see the previous blog article: Creating a Desired State Configuration Resource for Self Signed Certificates. The certificate created in last week’s blog has been exported and copied to the Windows 8.

Creating a Desired State Configuration Resource for Self Signed Certificates

For those of you who follow my blog, you know that I’ve been working on using DSC (Desired State Configuration) to fully automate the build of my test environment that runs as Hyper-V VM’s on my Windows 8.1 computer. Last week in my blog article titled Automate the installation of DSC Resource Kit Wave 9 resources with PowerShell Desired State Configuration, I demonstrated how to do just that, automate the installation of the Microsoft created DSC resources that are part of the most recent DSC resource kit (wave 9).

Automate the installation of DSC Resource Kit Wave 9 resources with PowerShell Desired State Configuration

Last week, in my blog article titled Creating Hyper-V VM’s with Desired State Configuration I left off with a newly created Hyper-V VM named Test01 that was created with DSC and the specific IP address of that VM was added to my trusted host list. For more details on the current state of this test environment, see that previous blog article. Today I’ll begin configuring the Test01 VM with DSC. This virtual machine will become the first Active Directory domain controller in my test environment.

Creating Hyper-V VM’s with Desired State Configuration

I’m looking to automate the build of my test environment that runs as Hyper-V virtual machines on my Windows 8.1 Laptop computer. To get started, I thought I would take a look at the xHyper-V DSC resource to create the actual VM’s. There’s also no reason this shouldn’t work on a Windows Server that’s running the Hyper-V role. The Hyper-V role has already been added to my Windows 8.1 computer. I also have a previously created virtual hard drive (vhdx) file that has been loaded with the Windows Server 2012 R2 operating system and all of the available Windows updates.

How to check the PowerShell version & install a new version

In my last blog article I demonstrated Where to Find & How to Launch PowerShell. Today I’ll continue on to the next step which is determining what version of PowerShell you have installed. PowerShell version information is contained in the $PSVersionTable automatic variable. You can type out $PSVersionTable in the console window that you opened in the last blog article or you can type $psv and press tab to take advantage of what’s called tabbed expansion:

Where to Find & How to Launch PowerShell

Happy New Year! What better way to start the new year out than by setting some goals and what better goal to set than to learn PowerShell this year. Let’s start out at ground zero by learning how to launch PowerShell. On Windows 8 or 8.1, simply start typing the word PowerShell on the Metro interface screen: Maybe you’re still running Windows 7? If so, the shortcuts for PowerShell are located in the start menu under All Programs > Accessories > Windows PowerShell:

Mount an ISO on a Physical Server running Server Core

So you need to mount an ISO on a physical server that is running Windows Server 2012 R2 Server Core? If so, how would you accomplish that task without a graphical user interface? With PowerShell of course, specifically the Mount-DiskImage PowerShell cmdlet: Mount-DiskImage -ImagePath 'D:\ISO\Windows Server 2012 Trial\9200.16384.WIN8_RTM.120725-1247_X64FRE_SERVER_EVAL_EN-US-HRM_SSS_X64FREE_EN-US_DV5.ISO' -StorageType ISO -PassThru By default nothing is returned when using the Mount-DiskImage cmdlet and the ISO is mounted using the next available drive letter.

PowerShell One-Liner: Create a new Hyper-V VM

My test environment resides on a workstation that runs Windows 8.1 Enterprise Edition with the Hyper-V role enabled. I need to create a new VM that will be used as a second domain controller in my test environment. I’ll use a PowerShell one-liner to create this new VM which will use a differencing disk based on a Windows Server 2012 R2 vhdx that has been fully patched and syspreped: New-VM -Name 'DC02' -VHDPath ( New-VHD -Differencing -ParentPath 'D:\Hyper-V\Virtual Hard Disks\template\Server2012R2Core-Template.

Use a certificate with PowerShell DSC to add a server to Active Directory without hard coding a password

A new Windows Server 2012 R2 machine has been brought online and needs to be joined to your Active Directory domain. All machines used in this demonstration are running either Windows Server 2012 R2 or Windows 8.1 with PowerShell version 4. You’ve decided to use DSC (Desired State Configuration) to join this new server to the domain because it’s a prototype for many more servers to come. You plan to automate their deployment along with the majority of their configuration with DSC.

Using PowerShell to add the necessary vWorkspace Firewall Exceptions on a Hyper-V Host Virtualization Server

Recently while adding a Windows Server 2012 R2 Hyper-V server as a host virtualization server in a vWorkspace 8.0.1 environment, I received the following error message: Connect to DC service timed out. Overlapped I/O operation is in progress. (997) Retry will occur automatically if necessary. That error message lead me to a Dell support article which stated that I needed to either disable the firewall <which is not going to happen on my watch> or open port 5203.

Use PowerShell to Install Active Directory Certificate Services

In this blog article, I’ll use PowerShell to install Active Directory Certificate Services in my test environment. The domain controller that’s being used is running Windows Server 2012 R2 Server Core Installation (no-GUI). The workstation that I’m using is running Windows 8.1 and it is a member of the same Active Directory domain. Many times when I’m prototyping something on a single remote server, I’ll use one to one remoting so that it’s an interactive session.

PowerShell: When Best Practices and Accurate Results Collide

I’m a big believer in trying to write my PowerShell code to what the industry considers to be the best practices as most are common sense anyway, although as one person once told me: “Common sense isn’t all that common anymore”. I would hope that even the most diehard best practices person would realize that if you run into a scenario where following best practices causes the results to be skewed, that at least in that scenario it’s worth taking a step back so you can see the bigger picture.

PowerShell Desired State Configuration Error: Undefined Property ConfigurationName

The scenario in this blog article is that you’ve created a DSC configuration on a computer that’s running a preview of PowerShell version 5. The machine itself could be running Windows 8.1, Server 2012 R2, or the Windows Technical Preview version of Windows 10. Here’s a simple configuration that I’ll use to demonstrate the problem. This DSC configuration uses a custom DSC resource to rename a computer. This configuration is being created on a machine running the Windows Technical Preview version of Windows 10 with PowerShell version 5 build 9860 (the most recent build as of this writing).

Use PowerShell to Determine the Uptime of an EqualLogic SAN

Recently, I received notification from EqualLogic support that there could be issues with their storage area networks running firmware version 7.0.x at 248 consecutive days of uninterrupted operation and they recommend updating to firmware version 7.0.9 to correct (and prevent) the problem. While I know that I have EqualLogic storage area networks running in some of the data-centers I support, I’m not sure what version of firmware they’re running or what the uptime on them is so I’ll use PowerShell (of course) to determine this information.

Use PowerShell to Determine the Differences in Group Membership between Active Directory Users

I recently saw a post on Reddit where someone was trying to create a function that takes an Active Directory user name as input for a manager who has direct reports (subordinates) specified in Active Directory. They wanted to determine if the Active Directory group membership of any of those subordinates is different than the others. There are two different parts to this scenario. Returning a list of the manager’s direct reports by querying that property from the manager’s user account in Active Directory:

Using Pester for Test Driven Development in PowerShell

How do you normally write your PowerShell code? Your answer is probably like mine and most other IT pros. You have a task that you need to accomplish and instead of performing a clicker-size in the GUI whenever that task is required to be performed, you write a PowerShell one-liner, script, or function to automate that task. You test it a little to make sure there aren’t any major issues and you implement it, moving on to the next task.

Creating a Custom DSC Resource to Configure Jumbo Frames on Network Cards

Recently while working on configuring a new server with DSC (Desired State Configuration), I discovered that there wasn’t a DSC resource for configuring the jumbo frames setting on network cards so I decided to write my own. This blog article steps you through the process of creating a custom DSC resource, specifically one that is used to configure the jumbo frames setting on network cards. The specific settings for jumbo frames can vary depending on your network card manufacturer and the specific driver.

My Solution to the Impractical One-liner Challenge

I recently participated in an Impractical One-liner Challenge that Stephen Owen posted on his blog site where he challenged his readers to come up with a PowerShell one-liner that would allow the person running it to select a single OU (Organizational Unit) from a list of all the OU’s in Active Directory and then move a list of computer accounts that are contained in a text file to that OU.

Use PowerShell to Determine what Outlook Client Versions are accessing your Exchange Servers

Earlier this month I saw a blog article on The EXPTA {blog} about Reporting Outlook Client Versions Using Log Parser Studio and I thought I would show you a simple alternative using PowerShell that accomplishes the same task while giving you some additional flexibility. This simple PowerShell function can be used to parse the Exchange Server RPC logs. #Requires -Version 3.0 function Get-MrRCAProtocolLog { <# .SYNOPSISIdentifies and reports which Outlook client versions are being used to access Exchange.

Unlock a Volume Protected with BitLocker Drive Encryption

Have a Windows Server 2012 R2 machine that runs the Server Core (no-GUI) installation of the operating system? Maybe that server has a volume that is protected with BitLocker Drive Encryption? If so, how would you unlock the encryption so you can access the data on that volume without using a graphical user interface? With PowerShell of course, specifically the Unlock-BitLocker PowerShell cmdlet: Unlock-BitLocker -MountPoint 'D:' -Password (Read-Host 'Enter Password' -AsSecureString) µ

Creating a Simplistic GUI Interface with Out-GridView

A couple of weeks ago I noticed a post in the forums at PowerShell.org where a question was asked about selecting a group of servers in Server Manager and running a PowerShell script against that selection of machines. While my solution doesn’t accomplish exactly what I think they were looking for, it does the next best thing. First, I added a menu item to Server Manager called MrToolkit (short for Mike Robbins Toolkit):

PowerShell Function to Create CimSessions to Remote Computers with Fallback to Dcom

I’ve found myself writing the same code over and over in my PowerShell scripts where I’m performing a task that requires me to create a CimSession to one or more computers without knowing what version of PowerShell is installed on the remote computers or if PowerShell is even installed on the remote computers. While it is possible to create a CimSession to a remote computer in any of those scenarios I just described, it’s a fair amount of code to add to multiple scripts and then the same redundant code ends up being in multiple files which creates a nightmare if you ever find an issue with the code and need to update it for any reason.

Set a Users Active Directory Display Name with PowerShell

I recently saw an article on how to set a users Active Directory display name based on the values of their given name, initials, and surname. I came up with my own unique solution for this task and thought I would share it with you, the readers of my blog. As you can see in the following example, there are a mixture of users who need their display name corrected based on the requirement that their display name be listed as Givenname Initials Surname:

Find and Disable Active Directory Users with PowerShell Faster than You can Open the GUI

In this scenario, a support request has been escalated to you because the help desk is unable to find a user account in Active Directory that needs to be disabled. The help desk included a screenshot where they attempted to search for the user who is named “William Doe”: The request you received also stated that the user is in the Sales department so you perform a quick search for users who have a last name of “Doe” and who are also in the Sales department:

Extract the Name from an Active Directory Distinguished Name with PowerShell and a Regular Expression

This is actually something I had a small blurb about in my previous blog article, but I wanted to go back, revisit it, and write a dedicated blog article about it. Sometimes there are properties in Active Directory like the one in the following example where the Manager property is being returned as a distinguished name and what you really wanted was just their name (in human readable format): Get-ADUser -Filter * -SearchBase 'OU=Northwind Users,OU=Users,OU=Test,DC=mikefrobbins,DC=com' -Properties Manager, Title | Format-Table -Property Name, Title, Manager -AutoSize You could write a complicated function or script to query Active Directory for the Managers information and create a custom object to return both the actual users information and the managers information, but if you simply want the name of the manager (in this example), it’s much easier to use the substring method or a regular expression.

Create Active Directory Users Home Folder and Assign Permissions with PowerShell

The following function is a work in progress, but I thought I would go ahead and share it. This function requires a module named PowerShellAccessControl that was created by Rohn Edwards which is downloadable from the TechNet Script Repository. The version 3.0 beta revision of his module which is also downloadable on that same page is what was used to test the examples shown in this blog article. #Requires -Version 3.

Using PowerShell to Search for Specific Users in Active Directory without Knowing their Exact Information

You’re looking for a user in your Active Directory environment who goes by the nickname of JW. You know that’s the user’s initials and you need to find their AD user account. Typically you’d use the Identity parameter, but that parameter doesn’t allow wildcards: Get-ADUser -Identity j*w* Verifying wildcard’s are not allowed on the Identity parameter of Get-ADUser: help Get-ADUser -Parameter identity What you’ll need to do is use the Filter parameter instead:

PowerShell Function to Prevent Starting Hyper-V VM’s that are Connected to an External Network

Beginning with Windows 8 (Professional and Enterprise Edition), Hyper-V is available on workstations that have a processor that supports SLAT (Second Level Address Translation). For specifics about the requirements, see the Client Hyper-V blog article on Microsoft TechNet. That means you have a Hypervisor running right on your desktop or laptop computer for free. With the price of hardware these days, your regular everyday computer can be spec’d out with an i7 processor, 16 gigabytes of memory, and one or more solid state drives and in addition to performing your everyday work on it, you have an awesome test environment without the need for additional physical computers.

Determine the Last Day of the Previous Month with PowerShell

I recently had a need to determine the last day of the previous month with PowerShell. Unless I’m overlooking something, PowerShell doesn’t natively have a way to determine this. Luckily, the System.Time class in the .NET Framework has a DaysInMonth method that returns the number of days in a specific month which effectively gives you the last day of the month. The command to determine what I needed was simple enough:

PowerShell Version 5 New Feature: New Parameters added to the New-DscCheckSum and Test-DscConfiguration Cmdlets

I’m continuing on my series of blog articles on the new features in the preview version of PowerShell version 5. Today I’ll be discussing the existing DSC (Desired State Configuration) cmdlets in PowerShell version 4 that now have new parameters as of the May 2014 preview version of PowerShell version 5. To begin, I’ll define a DSC configuration that’s parameterized so that it’s reusable: configuration iSCSI { param ( [Parameter(Mandatory)] [string[]]$ComputerName ) node $ComputerName { WindowsFeature MultipathIO { Name = 'Multipath-IO' Ensure = 'Present' } Service iSCSIService { Name = 'MSiSCSI' StartupType = 'Automatic' State = 'Running' } } } Run the configuration specifying the computer names to create MOF files for:

PowerShell Version 5 New Feature: SkipLast Parameter added to Select-Object

I’m picking up where I left off in my last blog article on the new features in the PowerShell version 5 preview. Today I be covering a new parameter, SkipLast that has been added to the Select-Object cmdlet. I have a text file where I saved a list of the available packages in the default OneGet Chocolatey repository. There are a total of 1893 items in this file: (Get-Content -Path C:\demo\packages.

PowerShell Version 5 New Feature: NoWait Parameter added to Stop-Service

I presented a session on “What’s New in PowerShell Version 5?” at TechStravaganza in Atlanta this past Friday and there was a lot of information I wasn’t able to get to because of the massive amount of information that I’ve compiled about the updates to PowerShell version 5 that are in the May 2014 preview version so I thought I would blog about them. He’s a picture of me presenting at TechStravaganza in Atlanta this past Friday.

If (‘Interested’ -in ‘PowerShell’) {‘Are you Participating in the PowerShell.org Forums?’}

If you’re interested in PowerShell and you’re not participating in the forums at PowerShell.org, you’re missing out on an awesome opportunity to learn from others instead of having to re-invent the wheel each time you need to accomplish a task. If you’ve been using PowerShell for a while and you’re not participating in the forums, then you’re missing out on an opportunity to help others who are asking for your assistance.

Error when Using PowerShellGet Find-Module or Install-Module with the Name Parameter and a Local NuGet Repository

If you’re following me on Twitter then you probably know that I’ve been working a lot with the new features in PowerShell version 5, with my focus being on the cmdlets in the OneGet and PowerShellGet modules. I’ve been fighting an issue where an error is received when the Name parameter is specified with Find-Module or Install-Module when using a local NuGet Repository: Find-PSGetExtModule : Module ‘Pscx’ was not found in the Gallery.

Helping Others at Microsoft TechEd with PowerShell 911

While at Microsoft TechEd last week, I met a gentleman from Europe who was experiencing a particular issue with the Get-ADUser PowerShell cmdlet. When Get-ADUser is used with a hard coded value such as name as shown in the following example, it returns the expected information without issue: Get-ADUser -Filter {Name -eq 'Administrator'} The issue is that when the name, for example, is stored in a variable and double quotes are used to try to expand the variable, nothing is returned:

Open Scripts in a new tab in the PowerShell ISE using PSEdit

While at TechEd last week, PSEdit was used in one of the PowerShell sessions that I sat through. Afterwards a couple of friends asked me if I had ever heard of it and said they hadn’t so I thought I would write a blog article about it to help spread the word. PSEdit is a function that only exists in the PowerShell ISE. Type in PSEdit followed by the name of a PowerShell script and that script will be opened in a new tab in the ISE:

How to Create Reusable PowerShell Functions for Microsoft SQL Server Database Administration

In my last blog article on Getting Started with Administering and Managing Microsoft SQL Server with PowerShell, I left off by introducing you to how to query information about your SQL Server using PowerShell with SQL Server Management Objects (SMO). In this blog article, I’ll pick up where I left off and write a reusable PowerShell function to return information about SQL Server files and file groups while making the use of SMO transparent to the user of the function.

Getting Started with Administering and Managing Microsoft SQL Server with PowerShell

I’ve used PowerShell to administer and manage Microsoft SQL Server for quite some time although I haven’t blogged much about it. I thought I would take the time to write a series of blog articles about using PowerShell to administer and manage Microsoft SQL Server to help others who are just getting started and to clear up some common misconceptions. Just to give you a little background information about myself, I’ve worked (professionally) in a data-center environment administering and managing every version of SQL Server since 6.

Checking and Setting the Start Mode of a Windows Service with PowerShell

Working with Services in PowerShell is probably one of the first tasks you’ll undertake as a PowerShell newbie. Recently I needed to disable a few Windows services on a server and I’m a big believer in being able to get back to where you started so the first thing I set out to accomplish was to find out what the start mode was of the services I needed to change.

Exploring the Find-Package Cmdlet from the PowerShell version 5 Preview OneGet Module

While presenting on the OneGet Module in the preview version of PowerShell version 5 for the Mississippi PowerShell User Group last week I discovered a couple of things about the Find-Package cmdlet that I wanted to share. The first thing is wildcards don’t work with the name parameter: Find-Package -Name *Java* That’s seems to be because they’re already performing a wildcard search as I’ll search for Java in the following example and notice that none of the packages are that exact name.

Return an Error Message from a Remote Computer when an Attempt to Install a Package using the OneGet Module Fails

This blog article will walk you through the issue of the OneGet module not returning an error message when an attempt to install a package fails on a remote computer via the Install-Package cmdlet and PowerShell remoting. Attempting to install a package such as WireShark on a remote computer gives you a quick flash across the screen that’s too quick to read and then it gives your prompt back with no errors and no feedback about whether or not the package was installed:

Getting Installed Packages InSync Across Multiple Machines with the PowerShell version 5 Preview OneGet Module

I presented a session for the Mississippi PowerShell User Group a couple of days ago and I thought I would share a couple of things I showed during that presentation that I hadn’t previously blogged about. I’m starting where I left off during my last blog article about the OneGet module in the PowerShell version 5 preview. I’ve stored the names of the packages that are installed on the local computer (PC03) in a variable named Software and created PSSessions to three remote computers (PC04, PC05, and PC06).

Using the PowerShell version 5 Preview OneGet Module with PowerShell Remoting

I’m picking up where I left off in my last blog article. Adobe Reader, ImgBurn, and WinRAR have been installed on a Windows 8.1 Enterprise edition computer named PC03. All of the examples shown in this blog article are being run from the PC03 computer. I’ll use a little trick I showed you a few blog articles ago and store the names of the installed packages in a variable and return them at the same time, all in a one-liner:

Installing Software with the OneGet Module in PowerShell version 5

As referenced in my previous blog article, a preview version of PowerShell version 5 was released last week. One of the new modules is named “OneGet” which contains a number of new PowerShell cmdlets: Get-Command -Module OneGet There’s only limited help available for these cmdlets since attempting to update the help fails for the two new modules that are part of the PowerShell version 5 preview: Update-Help Update-Help : Failed to update Help for the module(s) ‘NetworkSwitch, OneGet’ with UI culture(s) {en-US} : For security reasons DTD is prohibited in this XML document.

Where and Foreach Methods in PowerShell version 4

It’s a little over a month until Microsoft TechEd North America 2014 which is in Houston this year. I was trying to remember the cool stuff I saw at TechEd last year and Desired State Configuration along with the announcement about PowerShell version 4 were the two big things I remember, but let’s not forget about some of the other things such as the new Where and Foreach methods. I certainly don’t claim to be an expert with these, but I’m going to provide a couple of examples for documentation for myself as well as to get you thinking about them:

PowerShell: Output the Result of a Command and Assign it to a Variable in One Line

As of today, there is one month left until the PowerShell Summit North America 2014. I tweeted something out last night and thought I would write a quick blog about it since I often find myself looking for a tweet months later when I can’t remember how I did something that I previously tweeted out. This tweet used all 140 characters that twitter allows: "There are $(($i=New-TimeSpan -End 2014-04-28T09:00-07).Days)days & $($i.

Run a local PowerShell Function against a Remote Computer with PowerShell Remoting

Did you know that it’s super easy to run a function that exists only on your local computer against a remote computer even when no remoting capabilities have been added to the function itself? It does however require that PowerShell remoting be enabled on the remote system, but if you’re running Windows Server 2012 or higher, PowerShell remoting is enabled by default on those operating systems. I’ll start off by creating a function that performs a meaningful task so I can use it to demonstrate this process.

Use PowerShell to Determine the PDC Emulator FSMO Role Holder in your Active Directory Forest Root Domain

Each domain has a PDC emulator FSMO role so how do I determine which domain controller holds the PDC emulator FSMO role in the forest root domain if I have multiple domains in my forest? Sounds like you can’t see the forest root for the trees :-). The answer of course is with PowerShell: Get-ADForest | Select-Object -ExpandProperty RootDomain | Get-ADDomain | Select-Object -Property PDCEmulator The Active Directory PowerShell module which is part of the Remote Server Administration Tools (RSAT) is installed on the workstation these commands are being run from.

Proving Leap Year is NOT Every Four Years with PowerShell

Last week, I saw a couple of tweets from PowerShell MVP Jeffery Hicks about leap year that caught my attention: One of the reasons that I found those tweets so interesting is that I had just heard the night before on of all places, Wheel of Fortune, that leap year wasn’t every four years. I’d always been told that leap year was every four years and it has been for my entire life so it was time to investigate further.

No PowerShell, you may not install Bing Desktop on my Computer!

I recently noticed some strange behavior from PowerShell on my computer when attempting to import all of the available modules : Get-Module -ListAvailable | Import-Module -DisableNameChecking PS [MikeFRobbins.com]\>Import-Module -Name PSWindowsUpdate Confirm Are you sure you want to perform this action? Performing the operation “Bing Desktop v1.3.1[9 MB]?” on target “PC01”. [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is “Y”): I could create some elaborate script to iterate through each module and tell me what module is trying to install Bing Desktop, or I can simply use the PassThru parameter:

PowerShell One-Liner to List All Modules and Return How Many Cmdlets Each One Contains

A big misconception when it comes to PowerShell one-liners is that they’re one line of code as the name implies. That assumption is incorrect though because a one-liner can be written in one physical line of code such as in this example: Get-Module -ListAvailable | Import-Module -PassThru | ForEach-Object {Get-Command -Module $_} | Group-Object -Property ModuleName -NoElement | Sort-Object -Property Count -Descending Or it can be written in multiple physical lines of code such as in the next example.

Using PowerShell to Investigate Duplicate IP Address Issues that were issued from a Microsoft based DHCP Server

Over the past couple of weeks, you’ve received several support calls about duplicate IP Address issues from users whose machines receive their IP Address from your organizations internal Microsoft based DHCP Servers. The users who reported the issues use thin clients and when the IP Address conflicts occur they receive a popup message containing their IP Address and the MAC Address of the machine that duplicated the IP Address. You and your staff need to retrieve additional information about the IP Address and MAC Address that the users received in order to try to determine what’s causing the problem.

Add an Active Directory User to the Same Groups as Another User with PowerShell

A request has been received to grant additional permissions to an existing user in your organizations Active Directory environment. The username of this existing user is frank0. In additional to his current responsibilities, Frank will be taking on the responsibilities of Alan who goes by the username of alan0. Note: The examples shown in this blog article are being performed on a Windows 8.1 machine that has the Remote Server Administration Tools installed.

PowerShell Tip from the Head Coach of the 2014 Winter Scripting Games: Design for Performance and Efficiency!

There are several concepts that come to mind when discussing the topic of designing your PowerShell commands for performance and efficiency, but in my opinion one of the items at the top of the list is “Filtering Left” which is what I’ll be covering in this blog article. First, let’s start out by taking a look at an example of a simple one-liner command that’s poorly written from a performance and efficiency standpoint:

PowerShell Tip #3 from the Winner of the Advanced Category in the 2013 Scripting Games

In my previous blog article, I left off with the subject of inline help and stated there was a better way. I’m fast-forwarding through lots of concepts and jumping right into “Advanced Functions and Scripts” with this tip because they are where you’ll find the answer to a “better way” to add inline help. The inline comments we saw in the previous tip looked like this: function Get-BiosInfo { # Attempting to retrieve the BIOS information from the local computer Get-WmiObject -Class Win32_BIOS } When looking at the syntax for this function, you can see that it has no parameters:

PowerShell Tip #2 from the Winner of the Advanced Category in the 2013 Scripting Games

Tip #2 - Comment (Document) your code! This is another one of those tips that probably isn’t very popular, but regardless of how good you are at writing PowerShell scripts and functions, they’re useless if no one else can figure out how to use them. You might be thinking that you’re the only one who uses the PowerShell code that you write, but I’m sure that you like to go on vacation just like the rest of us and none of us are going to live forever.

PowerShell Tip #1 from the Winner of the Advanced Category in the 2013 Scripting Games

In case you haven’t heard, the 2014 Winter Scripting Games are just now getting started. Regardless of your skill level with PowerShell, it couldn’t be a better time to participate since this is the first time in the history of the scripting games that you’ll be able to work as part of a team and receive proactive feedback (before your code is judged) from a team of expert coaches who use PowerShell in the real world on a daily basis.

Using PowerShell to Remove Phishing Emails from User Mailboxes on an Exchange Server

You’ve all seen those phishing emails that occasionally get past your spam filters and you all also know that no matter how many times you tell users not to open those suspicious emails and click on links contained in them, users are ultimately gullible so sometimes you have to take matters into your own hands and protect them from themselves. Here’s an example of a recent phishing email that I’ve seen:

Setting an Active Directory User Account to Expire at a Specific Time of Day with PowerShell

Notice that in Active Directory Users and Computers (ADUC) when setting the expiration of a user account, there’s only a way to have the account expire at the end of a specific day: The same option exists in the Active Directory Administrative Center (ADAC): In ADAC, you can see the PowerShell command that the GUI uses to accomplish this task: Let’s query that particular property with PowerShell to see exactly what it’s now set to:

PowerShell Remoting Error When Trying to use Invoke-Command Against a Domain Controller

I wrote a blog article last year where the Antivirus I was using on my workstation had caused issues when trying to connect to remote machines with PowerShell. I recently reloaded my workstation with Windows 8.1 and reloaded the Antivirus which is now at version 7 (Eset NOD32). Remote connectivity via PowerShell worked without issue and without having to change any settings except when trying to use the Invoke-Command cmdlet against domain controllers which I find to be very strange.

PowerShell Script to Determine What Device is Locking Out an Active Directory User Account

I recently received a request to determine why a specific user account was constantly being locked out after changing their Active Directory password and while I’ve previously written scripts to accomplish this same type of task, I decided to write an updated script. Active Directory user account lockouts are replicated to the PDC emulator in the domain through emergency replication and while I could have used the Get-ADDomain cmdlet to easily determine the PDC emulator for the domain:

Lock Out Active Directory User Accounts with PowerShell

As I’m sure you’re aware, there’s no setting where you can simply flip a switch to lock out Active Directory user accounts. So what is one to do if you need some locked out accounts to do testing with? Disclaimer: All data and information provided on this site is for informational purposes only. Mike F Robbins (mikefrobbins.com) makes no representations as to accuracy, completeness, currentness, suitability, or validity of any information on this site and will not be liable for any errors, omissions, or delays in this information or any losses, injuries, or damages arising from its display or use.

PowerShell One-Liner to Locate Scripts and Automatically Open them in New Tabs in the ISE

I recently wrote a blog about how to find scripts where you had accomplished some specific task. That blog article was titled How do I find that PowerShell Script where I did __________?. What if you not only want to find those scripts, but also open them automatically in new tabs in the PowerShell ISE? It just so happens that you’re in luck: Get-ChildItem -Path 'C:\Scripts\*.ps1' -Recurse | Select-String -Pattern "1.

Use PowerShell to Resolve the Error: “Not Enough Server Storage is Available to Process this Command”

Recently after updating the antivirus solution at one of my customer sites they started receiving the following error when attempting to access their old Windows 2003 servers: \\Server\Share is not accessible. You might not have permission to use this network resource. Contact the administrator of this server to find out if you have access permissions. Not enough server storage is available to process this command. Once this registry entry is added, it does require the remote server to be restarted.

Insane PowerShell One-Liner to Return the Name of Users with Quarantined Mailboxes in Exchange 2010

Have you ever had any mailboxes on your Exchange 2010 server marked as being quarantined? According to this Microsoft article, Exchange will isolate or quarantine any mailboxes that it detects as being poisoned. That TechNet article goes on to tell you how you can drill down in the registry on the Exchange Server to locate the GUID of the quarantined mailboxes. I don’t know about you but using the GUI to dig around in the registry is not what I call fun so I decided to use PowerShell to accomplish that task.

How do I find that PowerShell Script where I did __________?

I saw a tweet from June Blender a few days ago that I thought was interesting: I knew you could use Select-String for searching documents like this but it’s not something that I knew the exact syntax for off the top of my head. It’s something that would have taken me at least a few minutes to figure out, probably with a little trial and error. It just so happens that a few days later, I was looking for how I had done something with the range operator in one of my PowerShell scripts.

Determine What Active Directory Organization Units a Group Policy is Linked to with PowerShell

Have you ever noticed that there’s not many GPO related PowerShell cmdlets? I started out wanting to know what group policies existed that weren’t linked to OU’s and added a few other properties to return additional useful information for the ones that were: #Requires -Version 3.0 #Requires -Modules GroupPolicy function Get-GPOLink { <# .SYNOPSISReturns the Active Directory (AD) Organization Units (OU's) that a Group Policy Object (GPO) is linked to. .

Windows 8.1 RSAT PowerShell Cmdlets Get-ADUser & Get-ADComputer : One or more Properties are Invalid

I saw a tweet yesterday from Chris Duck about a PowerShell version 4.0 bug: The issue occurs when you try to use the Get-ADUser or Get-ADComputer cmdlets along with specifying the Properties parameter with the asterisk “*” wildcard character to select all of the properties. No issue when the client is running Windows 8.1 with the RSAT tools installed and the Active Directory domain controllers are running Windows Server 2012 R2:

PowerShell Function to Determine Daylight Saving Time

About a year ago, I wrote a PowerShell one-liner to Calculate What Date Thanksgiving is on with PowerShell (in the United States). When looking back at that blog now, my first thought is boy that is some rough code that’s hard to read. Instead of re-writing the same thing again, I decided to write something similar applying what I’ve learned during the past year to it. That’s how I came up with the idea to write a PowerShell function that returns the beginning and ending dates for daylight saving time in the USA for a given year or years:

Using PowerShell Desired State Configuration to Unzip Files

A couple of months ago I wrote a blog about a PowerShell Function to Unzip Files Using the .NET Framework 4.5 with Fallback to COM. I’ve since discovered that the new Desired State Configuration (DSC) feature in PowerShell version 4 can unzip files. You probably wouldn’t use this feature just to unzip a single file to a single server, but it does open up some interesting possibilities. This blog article is not meant to be an all inclusive tutorial on DSC, it’s only meant to give you a peek inside the built-in DSC Archive Resource capabilities.

Fun and Games with PowerShell

I hadn’t previously used a “do until” loop in PowerShell so I decided this was as good as an excuse as any to use one since the loop has to run at least once anyway and it gave me a chance to learn something new. Add-Type -AssemblyName System.Speech [int]$guess = 0 [int]$attempt = 0 [int]$number = Get-Random -Minimum 1 -Maximum 100 $voice = New-Object System.Speech.Synthesis.SpeechSynthesizer $voice.Speak("Ahoy matey! I'm the Dreaded Pirate Robbins, and I have a secret!

PhillyPosh User Group Meeting Presentation Follow-up: PowerShell Second-Hop Problem with CimSessions

This blog article is a follow-up to my presentation for the Philadelphia PowerShell User Group which was on September 5th. A video of that presentation is available on the PhillyPosh YouTube Channel: I received a question towards the end of the meeting wanting to know if the Cim Cmdlets and Sessions experience the same sort of second hop authentication issue as using Invoke-Command where your credentials can’t be re-used by a remote machine for authentication to access resources on a third machine that your command is attempting to use.

PowerShell Function to Stop a Windows Service with a Status of Stopping

If you’re reading this blog article, you’ve probably tried to stop a Windows Service and it’s hung or stuck with a status of Stopping: An average Windows Admin would say “The server is going to have to be rebooted to clear up this problem”. This problem can be resolved with PowerShell though without the need for a restart. The machine I’m testing these examples on just happens to be running PowerShell version 2 so I’ll use the v2 syntax to see if the Get-Service cmdlet has any properties that may help.

PowerShell Function to Unzip Files Using the .NET Framework 4.5 with Fallback to COM

A few days ago, I saw a tweet about someone needing to extract a zip file with PowerShell and wanting to accomplish the task without loading any third party extensions so I thought I would write a function to accomplish the task. I start out by declaring the function followed by its name, it includes comment based help which is collapsed in the following image, then the [CmdletBinding()] attribute is specified to define this function as an advanced function.

PowerShell Parameter Validation: Building a Better ValidatePattern with ValidateScript

Let’s start out by taking a look at what the PowerShell built-in help says about the ValidatePattern and ValidateScript validation attributes: Here’s what that help topic says about ValidatePattern: We’ll test using ValidatePattern with an example that I used in my entry for advanced event #4 in the Script Games this year as shown in the following example: function Test-ValidatePattern { [CmdletBinding()] param( [Parameter(Mandatory)] [ValidatePattern("^(?!^(PRN|AUX|CLOCK\$|NUL|CON|COM\d|LPT\d|\..*)(\..+)?$)[^\x00-\x1f\\?*:\"";|/]+\.html?$")] [string]$FileName ) Write-Output $FileName } Who knows what that regular expression does?

Use PowerShell to Determine the Chain of VHD’s for a Virtual Machine on Hyper-V

You want to determine what VHD’s exist for the virtual machines (VM’s) that are virtualized on your Windows 8 or Windows Server 2012 Hyper-V virtualization host. This may sound simple, but what if you have a base image or template that has been configured and then multiple VM’s have been created using differencing disks that reference that single base image? If that weren’t difficult enough to keep track of, you may also have snapshots of those VM’s which are also classified as differencing disks in HyperV.

How to Create PowerShell Script Modules and Module Manifests

My entry for the Scripting Games advanced event 4 contained four separate functions: I want to create a module that contains these functions. There are several different types of modules, but what I’ll be creating is a “Script Module”. Modules sound like something really complicated, but script modules are actually simple. Currently, I have the functions saved as a ps1 file which I dot-source to load the functions into memory, but I want to share this tool with others so it makes more sense to create a module out of it.

PowerShell Version 4 New Feature: A UserName Property Has Been Added To Get-Process Output Objects

Thanks to a tweet from Mark Schill, I discovered that Get-Process now has an IncludeUserName parameter in PowerShell version 4: This means no more having to use WMI to determine what processes are being run by which users: For those of us who work in a terminal services environment, this is a really big deal. I do find it odd that it was added via a switch parameter instead of just making it another property.

PowerShell Version 4 New Feature: Requires Statements Now Let Users Require Administrator Access Rights If Needed

In PowerShell version 4, there’s a new RunAsAdministrator option for the Requires statement that prevents a script from executing unless PowerShell is running as an administrator. The information about this new option from the PowerShell version 4 about_Requires help topic is shown in the following image. To learn more about the requires statement, run help about_requires from PowerShell. Here’s the message that’s displayed if this option is specified and the person running the script is not an administrator:

Using a Counter Variable in a PowerShell Workflow Foreach -Parallel Loop

As I’m sure most of my blog readers are aware, I competed in the advanced track of the Scripting Games this year and ended up doing quite well. Two first place finishes and three second places finishes with the official judges and four first place crowd score finishes. I also ended up being the overall winner of the advanced track. A few days ago someone on twitter asked me as the winner of the Scripting Games advanced track, what I would do with it?

Win a Six Month Subscription to Interface Technical Training’s Video Collection by Solving this PowerShell Puzzle!

During the 2013 Scripting Games, I won three subscriptions, each good for six months of video training at Interface Technical Training. I have a subscription already so I asked Don Jones about re-gifting my prizes since I don’t need more than one subscription so here’s your chance to win one. The first video training subscription that I won was given to Rohn Edwards who is the co-founder of the Mississippi PowerShell User Group.

2013 PowerShell Scripting Games Advanced Event 6 – The Grand Finale

For me, the Scripting Games have been a great learning experience this year. I’ve used many PowerShell features that I hadn’t used before such as splatting, ADSI, Workflows, and producing html webpages with PowerShell. I plan to write detailed followup blog articles on each of these topics over the next few months. Event 6 was definitely challenging since I hadn’t used workflows before but I also knew that’s what was really needed to accomplish the given task properly (In my opinion).

2013 PowerShell Scripting Games Advanced Event 4 – Auditors Love Greenbar Paper

For this event I created multiple functions and I’m going to quote chapter 6, section 1 of the Learn PowerShell Toolmaking in a Month of Lunches book written by Don Jones and Jeffery Hicks, published by Manning: A function should do one and only one of these things: Retrieve data from someplace Process data Output data to some place Put data into some visual format meant for human consumption I started out by naming my function to create the audit report properly (New-UserAuditReport).

2013 PowerShell Scripting Games Advanced Event 3 – Bringing Bad Habits from the GUI to PowerShell

I’m seeing a trend with a lot of PowerShell scripters. Many of us have a GUI, non-scripting background and we moved to PowerShell because we didn’t want to be button monkeys clicking through the same options in the GUI day in and day out. I’ve always heard, if you’re going to do something more than once, do it (script it) in PowerShell. The trend I’m seeing is many are bringing their bad habit of wanting to repeat themselves over and over, day in and day out, to PowerShell.

2013 PowerShell Scripting Games Advanced Event 2 – Why NOT to use the Win32_ComputerSystem WMI Class

The majority of the entries I’ve seen for the Scripting Games event 2 are using the TotalPhysicalMemory property from the Win32_ComputerSystem WMI class to determine the total amount of physical memory in a server. The property name is TotalPhysicalMemory after all so that’s what it should contain, right? Not so fast, keep reading to discover why. Your manager needs an inventory of all of your company’s physical servers that are located in three different data centers which are in different parts of the country.

2013 PowerShell Scripting Games Advanced Event 2 – Attention to Detail is Everything

Here’s my approach to the 2013 PowerShell Scripting Games Advanced Event 2: When I start one of the Scripting Games events, I read and re-read the scenario because if you don’t understand the requirements, you can’t write an effect script, function, command, tool, etc. It’s not a bad idea to print out the event scenario and highlight the high-points. Here’s the scenario for Advanced Event 2 -An Inventory Intervention, I’ll place the items in bold that I would normally highlight on my printout:

Lessons Learned from the Scripting Games Advanced Event 1

This is a continuation from my previous blog titled 2013 PowerShell Scripting Games Advanced Event 1 – Parameters Don’t Always Work As Expected. This isn’t the exact script, but sections of it. You’ll notice at the bottom of the first image shown below, I retrieve the list of folder names from the files variable to keep from having to make another call to the file system. Going from one variable to another in memory is a cheap operation where as going to disk to retrieve something is more expensive from a resources standpoint.

2013 PowerShell Scripting Games Advanced Event 1 – Parameters Don’t Always Work As Expected

The scenario for this event states the following which has been paraphrased: Someone allowed log files to build up for around two years and they’re starting to causing disk space issues on the server. You need to build a tool to archive the log files because this has happened more than once. Applications write log files to a sub-folder in C:\Application\Log. Examples are C:\Application\Log\App1, C:\Application\Log\OtherApp, and C:\Application\Log\ThisAppAlso. The log files have random file names and a .

PowerShell Function to Determine the Active Directory FSMO Role Holders via the .NET Framework

Last week I posted a PowerShell function to determine what Active Directory domain controllers held the FSMO roles for one or more domains and forests. That particular function used the Get-ADDomain and Get-ADForest cmdlets which are part of the Active Directory PowerShell module. As it so happens, a friend of mine, Shay Levy who is a PowerShell MVP posted an article on PowerShell Magazine that uses a couple of one liners that use the .

Use PowerShell to Find Where the Current FSMO Roles are Assigned in Active Directory

A while back, I had a need to figure out with PowerShell what server in an Active Directory domain held the PDC Emulator FSMO Role. I found a script on a very popular blog site that figured it out by using a command similar to this: Get-ADDomainController -Filter * | Where-Object OperationMasterRoles -contains PDCEmulator | Select-Object -Property Name While it accomplished what was necessary, I immediately thought “I can do better” and improved the one liner so it filtered left:

Using PowerShell v3 Features to Figure Out the Mysterious PowerShell Pipeline

I actually wrote this blog a couple of weeks ago and postponed it until I could do further testing because I thought of some scenarios where it possibly wouldn’t work. I wrote a couple of new blogs over the past couple of weeks and forgot about this one. Low and behold, I had rescheduled this blog for today and forgot all about it so I had two blogs posted today!


PowerShell Web Access Error: “Sign-in failed. Verify that you have entered your credentials correctly.”

Scenario: You’ve partnered with a company who is testing a new software application that uses PowerShell Web Access. You’ve provided this company with an Active Directory account named “Joe Doe”. This account is only allowed to sign into the PowerShell Web Access interface of a server named WWW in the mikefrobbins.com domain. Password policies in this domain use the default settings. Forty-two days after the account was created, you receive an email from the partner company asking if something has been reconfigured because they are unable to sign into PowerShell Web Access.

Use PowerShell to add an additional Domain Controller to an existing Windows Server 2012 Active Directory Domain

Recently, I decided to add a second domain controller to my mikefrobbins.com domain. The existing server and this new server that will become a domain controller both run the Microsoft Windows Server 2012 operating system and both were installed with the default installation type of server core (no GUI). Even though the GUI can be turned on and off in Windows Server 2012 (unlike in Windows Server 2008 and 2008 R2), I prefer not to add the GUI unless absolutely necessary.

Use PowerShell to Remotely Enable Firewall Exceptions on Windows Server 2012

You’re attempting to view the event logs of a couple of remote Windows Server 2012 servers that have been installed with the default installation type of server core (No GUI). You receive the following error when attempting to connect to these servers using the Event Viewer snapin in an MMC console: Computer ‘DC01.MIKEFROBBINS.COM’ cannot be connected. Verify that the network path is correct, the computer is available on the network, and that the appropriate Windows Firewall rules are enabled on the target computer.

Use PowerShell to Create a Scheduled Task that Uses PowerShell to Pause and Resume AppAssure Core Replication

In this scenario there are multiple AppAssure Core servers, one at each physical location that is used to backup the local servers. Each AppAssure Core server is setup to replicate its data to an offsite AppAssure Core server at a separate physical location across a wide area network for disaster recovery purposes. Due to bandwidth constraints, you want to pause the replication between the AppAssure Core servers during normal business hours.

PowerShell: Determine Exposed WMI and CIM Class Methods

During last months Arizona PowerShell User Group meeting, Aleksandar Nikolić, a PowerShell MVP, posted a number of great tips in the chat during The Scripting Guy (Ed Wilson)’s presentation which was on managing Windows 8 remotely with PowerShell version 3 (An awesome session). One of the code snippets that Aleksandar posted was how to determine what the exposed WMI and CIM class methods are. Here’s the code snippet which returns a list of the exposed methods for the Win32_Process class:

PowerShell Magazine Brain Teaser Winner!

I received notification yesterday from PowerShell Magazine that I had won last weeks PowerShell Brain Teaser to Assign a list of processes to a variable and output it to the console. Your new task is to get a list of running processes, assign it to a variable and output the result to the console window. Use the minimal number of characters. Be aware, a space is a character too. The shortest solution wins.

PowerShell: Save-Help for Modules that Aren’t Installed on the Local Computer without Copying Files

In my previous blog article on this subject, I showed how to copy the PowerShell module manifest file from a server with the module you want to download the help for to the local computer to trick it into thinking the module was installed locally, but copying files can get messy and isn’t really a robust way of accomplishing that task. The first method I used did get me thinking about this process though.

PowerShell: Save-Help for Modules that Aren’t Installed on the Local Computer

Update-Help and Save-Help are new PowerShell version 3 cmdlets which allow you to initially download PowerShell help and keep the local PowerShell help files updated that are installed on your computer and available via the Get-Help cmdlet. In PowerShell version 3, Save-Help allows the updated help files to be saved to a location where a machine that doesn’t have Internet access can update it’s help from. The problem is that in order to save help for a module, that module has to exist on the local computer that’s performing the actual download otherwise an error will be generated:

Piping PowerShell Output to the Clipboard

It’s definitely beneficial to attend technology events so you can talk to other IT Pro’s. This past weekend I presented a session at PowerShell Saturday in Atlanta and while at the speaker dinner I made a comment about a new version of the PowerShell Community Extensions being released. The only cmdlet that’s part of that module that I use all of the time is Out-Clipboard which allows you to paste the output of a PowerShell command into notepad, Word, an email, etc:

Use PowerShell to Create Active Directory User Accounts from Data Contained in the Adventure Works 2012 Database

This past Saturday, I presented a session at PowerShell Saturday 003 in Atlanta. Towards the end of the presentation, I created 290 Active Directory user accounts by using the information for employees contained in the Adventure Works 2012 database. This is actually a PowerShell script that I whipped up Friday night at the hotel after the speaker dinner. I populated some demographic information by joining multiple tables together from that particular database.

Use PowerShell to Create a New Active Directory Forest on Windows 2012 Server Core Installation (no-GUI)

You have a fresh installation of Windows Server 2012 that was installed using the default installation type of server core installation (no-GUI). This server will be the first domain controller in a brand new Active Directory forest. Log into the server and launch PowerShell by typing powershell.exe. You’ll need to first add the AD-Domain-Services role to the server: Add-WindowsFeature AD-Domain-Services The installation of this role completes and a restart is not required:

Use PowerShell to Obtain a List of Processes Where the Executable has been Modified in the Past 90 Days

Use PowerShell to obtain a list of currently running processes where the executable file has been modified in the past 90 days. The number of days is a parameterized value so it can be specified when running the script without having to manually modify the script each time you want to change the value. The script uses a foreach loop to iterate through each individual process that is returned by the Get-Process cmdlet.

PowerShell v3 Where-Object Syntax Produces Different Results Than v2 Syntax

I posted a blog yesterday about a PowerShell issue I was experiencing and the problem ended up being due to the new PowerShell version 3 Where-Object Syntax producing different results than the PowerShell version 2 Where-Object syntax. Piping Get-Volume to Where-Object and filtering on the drive letter using the version 3 syntax appears to be case sensitive. It doesn’t return results when using a lower case ‘c’: Get-Volume | where DriveLetter -eq 'C' Get-Volume | where DriveLetter -eq 'c' Using the PowerShell version 2 syntax with Where-Object does not appear to be case sensitive.

PowerShell: Filtering Left Could Produce Different Results Than Filtering with Where-Object

While doing some testing on my Windows 8 machine today, I discovered an issue where Filtering Left could produce different results than filtering with the Where-Object cmdlet. Nothing special here. Just using the Get-Volume cmdlet and filtering left with its DriveLetter parameter. Using either an upper or lowercase ‘C’ returns the same results: Get-Volume -DriveLetter 'C' Get-Volume -DriveLetter 'c' Using the Where-Object cmdlet to do the filtering, while not a best practice when the filtering can be accomplished earlier in the pipeline, should return the same results or at least you would think it should.

Use PowerShell to Determine When Your DHCP Lease Expires

This blog post applies to only Windows 8 and Windows Server 2012. Want to know how much time there is until your current DHCP leases expire? Get-NetIPAddress -PrefixOrigin Dhcp | select InterfaceAlias , IPAddress, ValidLifetime I have 23 hours, 47 minutes, and 46 seconds until my current DHCP lease expires on one of my network interfaces and 22 seconds more than that left on the other one. Want to know the exact date and time of when they expire?

Targeting Down Level Clients with the Get-CimInstance PowerShell Cmdlet

This past weekend, I attended PowerShell Saturday 002 in Charlotte, NC. One of the sessions I attended was “Discovering the Power of WMI & PowerShell in the Enterprise” by Brian Wilhite. One of the cool things that Brian covered in his session was how to use the new PowerShell version 3 Get-CimInstance cmdlet to target down level clients that don’t have PowerShell installed or don’t have PowerShell remoting enabled. There’s no parameter to change the protocol on the actual Get-CimInstance or New-CimSession cmdlets, but it can be added using the the New-CimSessionOption cmdlet.

Use PowerShell to Display IIS Application Pool Identity Account Passwords in Clear Text

It’s fairly common to see the identity for an IIS application pool changed to a domain user account. The following image shows three application pools, the DefaultAppPool has the default settings, the www app pool has a Managed Service Account specified, and the wwwDev app pool has a standard domain user account specified: When a standard user account is specified, the password is entered as shown below: I’ve used what you would think is a super secure password, generated by KeePass:

Use PowerShell to Check for Processor (CPU) Second Level Address Translation (SLAT) Support

The hardware requirements for using Hyper-V to run virtual machines on a Windows 8 client states that a 64-bit system that has a processor (CPU) that supports Second Level Address Translation (SLAT) is required. A minimum of 4GB of RAM is also required. How do I know if my Processor (CPU) supports Second Level Address Translation? You could do like most blogs on the Internet state and use Coreinfo: You have two additional choices if you already have Windows 8 or Windows Server 2012 Installed.

Finding Aliases for PowerShell Cmdlet Parameters

Many PowerShell cmdlet parameters have aliases such as Cn for ComputerName. These aliases aren’t well documented and even viewing the full help for a cmdlet doesn’t show them. The following command can be used to display a list of all the parameters for a particular PowerShell cmdlet and any aliases that exist for those parameters: (Get-Command (Read-Host "Enter a PowerShell Cmdlet Name")).parameters.values | select name, aliases One thing to keep in mind is this is a list of all the parameters from all parameter sets which means some of them are mutually exclusive and can’t be used with one another.

Use Data Stored in a SQL Server Database to Create Active Directory User Accounts with PowerShell

I need a few Active Directory users created in my mikefrobbins.com test environment so I thought why come up with fake information when I could use information that I already have in a SQL Server database? The Employees table in the Northwind database looks like an easy enough candidate since all the data I need is in one table. This is about the concept and not about seeing how complicated I can make this process.

Use PowerShell to List Stopped Services that are Set to Start Automatically While Excluding Delayed Start Services

Have you ever had 67 emails about services on your servers being up and down from your monitoring solution? It’s not a good feeling and those emails are only about the ones that monitoring is setup for. What other services could be stopped that aren’t being monitored? Wouldn’t you like a quick and easy way to check whether or not all of the services that are set to start automatically are actually running?

Use PowerShell to Audit Logon Authentication Type

Want to know what type of authentication mechanism is being used when users log onto your servers? This script pulls the information from the event logs to determine how users are being authenticated. It uses Get-Winevent with the FilterXPath parameter. That parameter and what the logon type numeric codes translate to are a couple of things that I haven’t seen much documentation on. The script sorts by server name in ascending order and then by the time in descending order.

Using PowerShell to Find Expiring SSL Certificates & the Websites they’re Associated with

Have you recently received a notification about an expiring SSL certificate and don’t remember where all it’s used at? It’s generally not an issue to figure this out with normal certificates which are issued for a single name, but if it’s a wildcard certificate, it could be used on lots of different websites within your organization. The following PowerShell script retrieves all of the SSL certificate’s thumbprints and their expiration dates on an individual server that has IIS installed (This has only been tested on Windows Server 2008 R2).

Rename an IIS Web Application with PowerShell

Want to rename an IIS Web Application on a Windows 2008 R2 server? It’s not possible from the GUI, but it’s simple to accomplish using PowerShell. First, let’s create a web application in an existing website and then verify it exists: Import-Module WebAdministration New-Item -ItemType Directory -Path d:\iis\robbinsapps New-WebApplication -Name RobbinsApps -Site MikeFRobbins -PhysicalPath d:\iis\robbinsapps -ApplicationPool "ASP.NET v4.0" Get-ChildItem iis:\sites\mikefrobbins Here it is in the GUI: Rename the web application using PowerShell and then verify it was renamed:

Create a New IIS Website with PowerShell

On a Windows Server 2008 R2 machine, IIS has already been installed and you want to create an additional website. If necessary, an additional IP Address has been added to the server also. Use the New-Website PowerShell cmdlet to accomplish this task: Import-Module WebAdministration New-Item -type directory -path d:\iis\mikefrobbins New-Website -Name "mikefrobbins" -Port 80 -IPAddress "192.168.1.222" -PhysicalPath d:\iis\mikefrobbins -ApplicationPool "ASP.NET v4.0" You can get a list of websites running on the server by using the Get-Website cmdlet or by running Get-ChildItem on the IIS PSDrive:

Interesting How People are Claiming to Have Same Beginner 1 Solution as the Expert Solution but Still Did Not Get 5 Stars

This past weekend I posted a blog about Beginner Event #9 of the 2012 PowerShell Scripting Games and I received a comment on it from @ruddawg26. I took a look at his profile and tweets. I found a tweet that was tweeted by him Interesting how people are claiming to have same beginner 1 solution as the expert solution but still did not get 5 stars #2012SG so I decided to investigate further which is how this blog came to be.

Performance Counters – 2012 PowerShell Scripting Games Beginner Event #10

Gather all of the counter information for the processor counter set. Take three separate readings at five second intervals. This information should be appended to a single text file named servername_ProcessorCounters.txt in the Documents special folder. You’ll lose points for complexity. Use native PowerShell commands where possible. This was the most confusing event for me since it specified “Processor Performance Counter Set” in one of the design points and my home pc with an AMD processor has a “Processor Performance” counter set:

Search Event Log – 2012 PowerShell Scripting Games Beginner Event #9

The details of the event scenario and the design points for Beginner Event #9 of the 2012 PowerShell Scripting Games can be found on the Hey, Scripting Guys! Blog. Find Veto Shutdown Events in the Application Event Log. A screenshot was provided that contains EventID 10001 and Winsrv as the source. Write a one liner to display the date of occurrence and the application name. Your command should be efficient. Complexity will cost you points.

Determine Hardware Type – 2012 PowerShell Scripting Games Beginner Event #8

Write a script to determine if a computer is a laptop or a desktop from a hardware prospective and display the output on the console. If this requires admin rights, you should detect if it is running as an admin or standard user. Extra points for writing a simple function that returns a boolean. I kind of figured this was going to be a WMI thing since it involved hardware. Some research turned up an MSDN article on the Win32_ComputerSystem class which contained a PCSystemType property.

Enabled Logs with Data – 2012 PowerShell Scripting Games Beginner Event #7

Display a list of enabled logs that contain data. Do not display errors. Include hidden logs. Display the complete log name and number of entries. Sort by the logs with the most entries in them. My research on this one lead me to the Use PowerShell to Query All Event Logs for Recent Events blog article on the Hey, Scripting Guy! Blog. I also used the online help by running Get-Help Get-WinEvent -Online.

Working with WMI – 2012 PowerShell Scripting Games Beginner Event #6

The details of the event scenario and the design points for Beginner Event #6 of the 2012 PowerShell Scripting Games can be found on the Hey, Scripting Guys! Blog. Write a PowerShell script to determine the uptime of servers by using the WMI class WMI32_OperatingSystem. The script should display the server name, how many days, hours, and minutes the server has been up. As usual, I started out by running Get-Help Get-WMIObject to determine what the available parameters were for this cmdlet.

Finding Application Errors – 2012 PowerShell Scripting Games Beginner Event 5

The details of the event scenario and the design points for Beginner Event #5 of the 2012 PowerShell Scripting Games can be found on the Hey, Scripting Guys! Blog. Your manager has task you with producing a report of applications that are causing errors on your servers. This report should display the source and number of errors from the application log. How can I find out what PowerShell cmdlets are available to query the application event log?

Just Passing Thru – 2012 PowerShell Scripting Games Beginner Event 4

The details of the event scenario and the design points for Beginner Event #4 of the 2012 PowerShell Scripting Games can be found on the Hey, Scripting Guys! Blog. The key to this one is figuring out how to format the output as shown in the screen shot in the event scenario which is similar to the one in the image below: PowerShell Down Under posted some great prep videos leading up to the beginning of the scripting games and one of them titled Scripting Games 2012 - Working with Folders gives you a head start on solving this one.

Toughest Event Yet – 2012 PowerShell Scripting Games Beginner Event #3

The details of the event scenario and the design points for Beginner Event #3 of the 2012 PowerShell Scripting Games can be found on the Hey, Scripting Guys! Blog. This was the toughest event out of the first three for me. I spent a lot of time researching how to check permissions because part of the first design point stated: “If you do not have permission off the root, create the nested folders where you have permissions”.

Get-Method | My-Madness | 2012 PowerShell Scripting Games Beginner Event #2

The details of the event scenario and the design points for Beginner Event #2 of the 2012 PowerShell Scripting Games can be found on the Hey, Scripting Guys! Blog. Listed below are my notes about the requirements and design points: Find all services that are running and can be stopped. The command must work against remote computers. Use the simplest command that will work. You do not need to write a script.

My Approach to the 2012 PowerShell Scripting Games Beginner Event #1

Listed below are my notes about the requirements and design points: Computers run Windows 7 and servers run Windows 2008 R2. They’re all in one domain. PowerShell remoting is enabled on all computers (both servers and desktops). Use PowerShell to retrieve the top ten processes based on the memory working set. There’s no need to write a script. The command can be a one liner. You can use aliases. The command must be capable of running remotely against other domain computers.