user

Converting Your Batch Script to PowerShell

Introduction

Crista Perlton

Crista Perlton


LATEST POSTS

How Licenses Work with Chocolately 22nd March, 2024

How to Handle npm Dependencies with Lock Files 16th January, 2024

PowerShell

Converting Your Batch Script to PowerShell

Posted on .

How do you convert your Windows Batch scripts to PowerShell? The basic “how” is ridiculously easy: Rename the file from .bat/.cmd to .ps1. If it runs exactly the same as it did before, you’re done.

But if it doesn’t run exactly the same way as it did before, you have to prepare to rewrite it. There are no translation tools available (we’ve searched), so you have to do it by hand, line-by-line, and discover what worked in your Batch script but doesn’t in PowerShell. This requires knowing how to read Windows Batch and how to write PowerShell. There are SO many resources you can find on Google to help you learn both of these. That’s why this article isn’t about that.

Batch still works, despite it’s age. Have you ever stopped to ask yourself why should I convert my Windows Batch scripts to PowerShell?

The Need to Migrate

There’s a better way to approach the migration from Batch to PowerShell, starting with the question, “Do I have to migrate at all?”

Don’t rush to migrate your Windows Batch scripts to PowerShell just because they’re old or should be modernized. Instead, consider why each Batch script should be migrated and when it’s necessary to migrate before even thinking about how to execute the migration.

Use the three scorecards below on complexity, length, and impact to quantify the timeline for migrating your Windows Batch scripts to PowerShell.

Windows Batch Script is an Arcane Technology

Batch scripts are pretty ancient. However, many Batch files still execute exactly as expected, despite being a decade old. No problems.

But as years pass and employees move on, “ancient” becomes “arcane,” meaning “understood by few; mysterious or secret.” Those who wrote, read, and understood these Batch scripts are probably long gone from your organization. While the scripts might still work, current employees likely don’t know how they work, and most importantly how to fix them if something goes wrong.

No one has any idea how complex Windows Batch scripts work anymore, because they don’t have to. Things that a PowerShell script today can accomplish were done with complicated Batch Scripts back in the day. Scott Hanselman, for example, has blogged a lot about PushD and PopD, commands that run the command line directory stack, which was some complex flow logic. This Batch magician created a “Sleep” workaround (since Batch doesn’t have that command) by pinging an invalid IP address.

It’s Batch magic, honestly. Like asking me to spot and fix a grammatical error in an Ancient Greek text, modern tech people must be trained in ‘The Ancient Art of Batch’ to deal with Windows Batch scripts. But the resources to train someone to do these magic tricks don’t exist anymore. When the Batch magic stops working, you use PowerShell to execute the same tasks.

But just because your Windows Batch scripts are entering the realm of the arcane, you can probably let them keep working as long as they work.

Resist the “Spring Cleaning” Urge

Imagine walking into your office to find Jeffrey carefully reorganizing all the company’s tax documents from 1995 to the present. While we love organized files, I would hope that you and I would ask Jeffrey the same question: WHY are you reorganizing something that doesn’t need our attention?

Like very old tax documents (which, by the way, you only need to retain for a few years, not decades), migrating your Windows Batch scripts to PowerShell just because they’re old isn’t a good enough reason to prioritize it.

Resist the temptation to migrate for the sake of migration or just to do some tidying. You could be damaging your team and organization by wasting your time and talents while increasing risk. Remember that a poorly written PowerShell script is so much worse than an excellent Windows Batch script (especially one with excellent comments on it).

If I haven’t been clear enough yet, let me sum up: Windows Batch scripts are often ancient and arcane but don’t rush to migrate them to PowerShell.

This begs the question: How do you determine the best time to migrate Batch to PowerShell?

Windows Batch Script Migration Scorecards

We’ve got you covered. This part of the article gives you migration scorecards, contextual info about each, and an interpretation of the scores. Score your own Batch scripts on these scorecards, then use those scores in the final scorecard to get a better sense of the migration urgency.

There are three elements to calculate Batch-to-PowerShell migration urgency: complexity, length, and impact.

A word to the wise: A Batch script that doesn’t use any Batch commands, one that basically just executes programs, is always convertible to PowerShell and will run exactly the same. No matter how long or critical, because the complexity is zero, the final score for these scripts will always be zero.

Complexity

Definition: the control flow of the script (NOT how complicated the stuff is that the script controls)

“Complexity and batch!? But I thought it was simple.” While Batch is objectively simpler than PowerShell, you can do some insanely complex things—and mad genius sysadmins before you probably did. Well-documented/well-commented scripts of any type are significantly less complex than their ‘naked’ counterparts. In fact, when using a tool like Otter, scripts with Comment-based help can be executed via an automatically generated UI. This enables those who are less comfortable or familiar with PowerShell to run scripts without expert intervention.  

Windows Batch Script Complexity Scorecard

Score points for any/all that apply.POINT VALUEYOUR POINTS
Basic Windows Batch commands:
Uses ERRORLEVEL+1 
Uses variables/SET commands+1 
Uses loops/FOR command+1 
Uses commands you’ve never seen+3 
Uses clever hacks/tricks+5 
Well-commented/Well-documented-2 
YOUR TOTAL
(You’ll use this total on the last scorecard.)

Length

Definition: how long the Batch script is; how big the .bat/.cmd file is.

One thing I had to remind myself when learning PowerShell was that scripts and application code are very different. Applications can be hundreds of thousands of lines of code—even millions for monoliths. A “big” script is at least 1,000 times fewer lines of code; even the biggest scripts aren’t a thousand lines. (A thousand-line Batch script?! What a nightmare… Pray to the Ancient Gods of Batch that that script never fails.)

Windows Batch Script Length Scorecard

Score only the most descriptive choice.POINT VALUEYOUR POINTS
Under 10 lines+1 
10 to 49 lines+2 
50 to 99 lines+5 
100 to 199 lines+10 
200 to 499 lines+50 
500 to 9999 lines+100 
1000 or more lines*+ ∞+ ∞
YOUR TOTAL
(You’ll use this total on the last scorecard.)
* Really?! That’s… a Batch-based application. Someone must really have forsaken the Ancient Gods of Batch. There are some scripts that should never be touched. This is one of them.

Impact

Definition: how important to daily operations and/or to secure a Windows Batch script is

Some scripts have little business impact. The Batch script that downloads the payroll data file and uploads it to the bank, by contrast, has a huge business impact. The risk potential is a two-sided coin:

  • A script executing something essential to daily operations and/or security shouldn’t be altered “just because it’s old Batch”
  • A script executing something essential to daily operations and/or security can’t afford to fail without a plan to immediately repair it (which, again, is very hard with Batch scripts)

You have to consider both sides of the impact coin when scoring your Batch scripts. Some examples of risk factors to consider include:

  • Failed script execution risks data breaches
  • Failed script execution risks business-damaging downtime
  • Failed script execution negatively impacts employees (like delaying paychecks)
  • Number of servers affected (one server, one server cluster, servers across a national/international environment)

Windows Batch Script Impact Scorecard

Score only the most descriptive choice.POINT VALUEYOUR POINTS
Miniscule (no impact on end-users, impacts only you/your team)+10 
Minor (minor business operations impact and/or has an easy workaround to avoid minor security risks)+20 
Major (moderate business operations impact and/or security risk)+30 
Critical (serious business operations impact and/or security risk)+40 
Super-critical/Blocker (a major malfunction that affects business operations or risks to security)+50 
YOUR TOTAL
(You’ll use this total on the last scorecard.)

What’s Your Score?

Take your scores from the three scorecards above, and plug them into the following formula:

Complexity Score x Length Score x Impact Score = Your Migration Difficulty Score  

Multiplying your three scores together yields your migration difficulty score.

Interpret Your Batch Migration Difficulty Score

0✔ Migrate Today.  A Batch script that doesn’t use Batch commands is always convertible to PowerShell by just changing the .cmd/.bat to a .ps1 ending, regardless of length or impact. Renaming should do it!
1 to 10✔ Rewrite as Needed. Carefully rewriting the script from Batch to PowerShell should work, and there’s no need to rush the process.
11 to 550⚠️Consult with Experts. These may be trickier than they seem, so make sure to have a Windows Batch and/or PowerShell expert available to evaluate and review the scripts before and after they’re migrated.
551 to 5,500⚠️For Experts Only. Only Windows Batch and PowerShell scripting experts should evaluate these scripts to consider if they should even be PowerShell scripts at all, or dedicated applications, and how to migrate them.
Over 5,550🚫 Do not migrate The Windows Batch scripts in these cases are so complex, lengthy, and/or have such a risk of a heavy impact that their entire purpose needs to be reevaluated, and reconsidered from the ground up.

Windows Batch Scripts shouldn’t really be hitting scores above 550. When you see scripts this complex, it’s important to reevaluate the business processes and tools. Maybe it should be split into multiple, simpler scripts – or even converted into an application that can be maintained and tested by developers using CI/CD tools.

You Have Your Score. Now What?

How to migrate your Windows Batch scripts to PowerShell and how soon to do it are the product of complexity, length, and impact. We gave you four scorecards to help you determine this “how” factor for your Batch scripts.

It may be just as simple as renaming your Windows Batch file as a PowerShell file, as tough as rewriting a new PowerShell script, as complicated as transitioning scripts to applications, and anything in between.

We can’t tell you right now that “you should migrate batch scripts after they reach X age.” That’s not a thing. At Inedo, we believe in arming you with the best tools and advice to make the best decisions for your unique situation.

Context is Key

In this article, we gave you what you need to make the best decisions for each script (and this part’s very important) in the context of your organization. Migration difficulty must be assessed in context. Fifty “Easy” migrations might, in context, be a single “Difficult” situation that should be made into an application, for example. Context, context, context.

It is vital to assess and plan carefully before going Batch script crazy. This is just one advisable way to plan and manage your PowerShell scripts. For many more, take a look at our free eBook, “Ultimate Powershell Levelup Guide”. Sign up for your copy today!

Crista Perlton

Crista Perlton

Navigation