Converting Your Batch Script to PowerShell
by Crista Perlton, on Feb 26, 2021 3:34:00 PM
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. Bravo.
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 is old. Batch is arcane. But Batch still works. Have you ever stopped to ask yourself why should I convert my Windows Batch scripts to PowerShell?
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.
Windows Batch Script is an Arcane Technology
Batch scripts, at this point, are pretty ancient. Ancient isn’t in and of itself bad. Many Batch files are more than a decade old and still execute exactly as expected. No problems. But as the years pass and employees move on, “ancient” becomes “arcane,” which is when problems arise.
“Arcane” means “understood by few; mysterious or secret.” Those who wrote these Batch scripts (and could read them and understood how they functioned) are probably long gone from your organization. While the scripts might still work, current employees likely don’t know what they’re looking at, how it works, and most importantly how to fix it if something goes wrong.
Basically 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 very 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. And 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. It’s very cool that they found this workaround. 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 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. Your heart might be in the right place, but 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.
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, as we discussed above. 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 run scripts without expert intervention.
Windows Batch Script Complexity Scorecard
|Score points for any/all that apply.||POINT VALUE||YOUR POINTS|
|Basic Windows Batch commands:|
|Uses variables/SET commands||+1|
|Uses loops/FOR command||+1|
|Uses commands you've never seen||+3|
|Uses clever hacks/tricks||+5|
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 VALUE||YOUR 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*||+ ∞||+ ∞|
|* 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 them.|
Definition: how important to daily operations and/or to security 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 potential for risk 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, as we said above, 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 VALUE||YOUR 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|
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 not 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.|
|Over 5,550||🚫 Do not migrate. The Windows Batch scripts in these cases are so complex, lengthy, and/or have such risk of the 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.
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.