Icon Fame Journal.

Juicy entertainment chatter with tabloid flavor.

general

How to use a batch file to make powershell scripts easier to run

By Emily Bell

I am trying to run this script in PowerShell. I have saved the below script as ps.ps1 on my desktop.

I have made a batch script to run this PowerShell script

But I am getting this error:

How to use a batch file to make powershell scripts easier to run

How to use a batch file to make powershell scripts easier to run

9 Answers 9

You need the -ExecutionPolicy parameter:

Otherwise PowerShell considers the arguments a line to execute and while Set-ExecutionPolicy is a cmdlet, it has no -File parameter.

I explain both why you would want to call a PowerShell script from a batch file and how to do it in my blog post here.

This is basically what you are looking for:

And if you need to run your PowerShell script as an admin, use this:

Rather than hard-coding the entire path to the PowerShell script though, I recommend placing the batch file and PowerShell script file in the same directory, as my blog post describes.

If you want to run from the current directory without a fully qualified path, you can use:

If you run a batch file calling PowerShell as a administrator, you better run it like this, saving you all the trouble:

It is better to use Bypass .

How to use a batch file to make powershell scripts easier to run

How to use a batch file to make powershell scripts easier to run

Small sample test.cmd

If you want to run a few scripts, you can use Set-executionpolicy -ExecutionPolicy Unrestricted and then reset with Set-executionpolicy -ExecutionPolicy Default .

Note that execution policy is only checked when you start its execution (or so it seems) and so you can run jobs in the background and reset the execution policy immediately.

How to use a batch file to make powershell scripts easier to run

Another easy way to execute a ps script from batch is to simply incorporate it between the ECHO and the Redirection characters,(> and >>), example:

Last line deletes the created temp file.

If your PowerShell login script is running after 5 minutes (as mine was) on a 2012 server, there is a GPO setting on a server – ‘Configure Login script Delay’ the default setting ‘not configured’ this will leave a 5-minute delay before running the login script.

How to use a batch file to make powershell scripts easier to run

you can convert any PowerShell script into a batch file easily using this PowerShell function:

To convert all PowerShell scripts inside a directory, simply run the following command:

Where is the path to the desired folder. For instance:

To convert a single PowerShell script, simply run this:

Where is the path to the desired file.

The converted files are located in the source directory. i.e., or .

Putting it all together:
create a .ps1 file (PowerShell script) with the following code in it:

And don’t forget, if you wanna convert only one file instead of many, you can replace the following

November 17, 2013 6 minute read

Aside – This post has received many tangential questions in the comments. Your best bet at getting an answer to those questions is to check Stack Overflow and/or post your question there.

A while ago in one of my older posts I included a little gem that I think deserves it’s own dedicated post; calling PowerShell scripts from a batch file.

Why call my PowerShell script from a batch file?

When I am writing a script for other people to use (in my organization, or for the general public) or even for myself sometimes, I will often include a simple batch file (i.e. *.bat or *.cmd file) that just simply calls my PowerShell script and then exits. I do this because even though PowerShell is awesome, not everybody knows what it is or how to use it; non-technical folks obviously, but even many of the technical folks in our organization have never used PowerShell.

Let’s list the problems with sending somebody the PowerShell script alone; The first two points below are hurdles that every user stumbles over the first time they encounter PowerShell (they are there for security purposes):

  1. When you double-click a PowerShell script (*.ps1 file) the default action is often to open it up in an editor, not to run it (you can change this for your PC).
  2. When you do figure out you need to right-click the .ps1 file and choose Open With –> Windows PowerShell to run the script, it will fail with a warning saying that the execution policy is currently configured to not allow scripts to be ran.
  3. My script may require admin privileges in order to run correctly, and it can be tricky to run a PowerShell script as admin without going into a PowerShell console and running the script from there, which a lot of people won’t know how to do.
  4. A potential problem that could affect PowerShell Pros is that it’s possible for them to have variables or other settings set in their PowerShell profile that could cause my script to not perform correctly; this is pretty unlikely, but still a possibility.

So imagine you’ve written a PowerShell script that you want your grandma to run (or an HR employee, or an executive, or your teenage daughter, etc.). Do you think they’re going to be able to do it? Maybe, maybe not.

You should be kind to your users and provide a batch file to call your PowerShell script.

The beauty of batch file scripts is that by default the script is ran when it is double-clicked (solves problem #1), and all of the other problems can be overcome by using a few arguments in our batch file.

Ok, I see your point. So how do I call my PowerShell script from a batch file?

First, the code I provide assumes that the batch file and PowerShell script are in the same directory. So if you have a PowerShell script called “MyPowerShellScript.ps1” and a batch file called “RunMyPowerShellScript.cmd”, this is what the batch file would contain:

Line 1 just prevents the contents of the batch file from being printed to the command prompt (so it’s optional). Line 2 gets the directory that the batch file is in. Line 3 just appends the PowerShell script filename to the script directory to get the full path to the PowerShell script file, so this is the only line you would need to modify; replace MyPowerShellScript.ps1 with your PowerShell script’s filename. The 4th line is the one that actually calls the PowerShell script and contains the magic.

The –NoProfile switch solves problem #4 above, and the –ExecutionPolicy Bypass argument solves problem #2. But that still leaves problem #3 above, right?

Call your PowerShell script from a batch file with Administrative permissions (i.e. Run As Admin)

If your PowerShell script needs to be run as an admin for whatever reason, the 4th line of the batch file will need to change a bit:

We can’t call the PowerShell script as admin from the command prompt, but we can from PowerShell; so we essentially start a new PowerShell session, and then have that session call the PowerShell script using the –Verb RunAs argument to specify that the script should be run as an administrator.

And voila, that’s it. Now all anybody has to do to run your PowerShell script is double-click the batch file; something that even your grandma can do (well, hopefully). So will your users really love you for this; well, no. Instead they just won’t be cursing you for sending them a script that they can’t figure out how to run. It’s one of those things that nobody notices until it doesn’t work.

So take the extra 10 seconds to create a batch file and copy/paste the above text into it; it’ll save you time in the long run when you don’t have to repeat to all your users the specific instructions they need to follow to run your PowerShell script.

I typically use this trick for myself too when my script requires admin rights, as it just makes running the script faster and easier.

Bonus

One more tidbit that I often include at the end of my PowerShell scripts is the following code:

This will prompt the user for keyboard input before closing the PowerShell console window. This is useful because it allows users to read any errors that your PowerShell script may have thrown before the window closes, or even just so they can see the “Everything completed successfully” message that your script spits out so they know that it ran correctly. Related side note: you can change your PC to always leave the PowerShell console window open after running a script, if that is your preference.

I hope you find this useful. Feel free to leave comments.

Update

Several people have left comments asking how to pass parameters into the PowerShell script from the batch file.

Here is how to pass in ordered parameters:

And here is how to pass in named parameters:

And if you are running the admin version of the script, here is how to pass in ordered parameters:

And here is how to pass in named parameters:

And yes, the PowerShell script name and parameters need to be wrapped in 4 double quotes in order to properly handle paths/values with spaces.

A friend was lamenting to me recently that there was an aspect of Powershell that he found annoying. He didn’t like the fact that you had to open a PowerShell command line window to run a script. Well guess what, dear friend – you don’t really need to do that! image001

” data-medium-file=” data-large-file=” title=”image001″ src=” alt=”” />

Purpose:

This blog entry details the quick and easy method for running a PowerShell script from a shortcut on your desktop. To get started let’s have a quick little script on hand to test how this works.

1. Open notepad, copy the below text into it, and save it as PowerShellTest.ps1. Keep track of where you save it.

$name = Read-Host “What is your name?” #Get name from CLI.

$quest = Read-Host “What is your quest?” #Get quest fromCLI

$windowObject = new-object -comobject wscript.shell #Create windows message box object.

$output = $windowObject.popup(“Hello $name.`nYour quest sounds exciting!”,0,”Quest: $quest”,1) #Display the message.

Now, here is how you can open that script in Powershell by just clicking on an icon.

2. Where ever you saved PowerShellTest.ps1, right click and select New Document.

3. Name the file “PowerShellTest.cmd“. The cmd is used to assign a file extension type of command to the text file. This lets it operate as an executable file.

4. You will see the following popup message:

Select “Yes” to confirm.

5. Now right click the PowerShellTest.cmd file that you just made, and select “Edit“. This will open up the CMD file in Notepad, and allow you to finish this process.

6. Inside of the cmd file, type in “Powershell.exe”, a space, and then the name of the PowerShell file you made in step 1.

Notice that I added “.” to the front of the file name. This is required by Powershell to help indicate that this is a file, and not a variable. It is called “Dot Sourcing” in Powershell.

The actual text I used is: Powershell.exe .PowerShellTest.ps1

7. Save and then close the CMD file to continue.

8. Now, to test the final product, double-click on the CMD file that you made in steps 3 and 4. You will get the following result:

You are going to be prompted for your name, and your quest. Just make up something dreadfully clever for each. Once you type the text, press Enter for each line. After your final entry a message box is displayed, indicating the the script has completed.

So, there you go. You were able to run a PowerShell script by simply clicking on a CMD text file. I generally store the CMD file with the PowerShell script file to make them quickly accessible.

Summary:

While this program is simple, it does highlight the method for opening a PowerShell script from Windows Explorer. Incidentally, it shows the method to prompt a script user for input, and also shows how to display a Windows message box output.

As always, let know if you have any questions or comments.

  • ROM
  • CPU
  • RAM
  • GPU

You can run a batch file within PowerShell. I would run it as either a job or a process so that your file deletes do not conflict with whatever your batch file is trying to do. Take your PowerShell commands back out of the batch file, then run the following as a PowerShell script.

Keep them in the same directory to make things easier. If you do, the batch file line can be location neutral as long as both files are moved together.

17 Replies

why do you want to run this from batch ?

The above command

You can run command line commands within PowerShell, but you cannot run PowerShell commands within the command console.

The batch file is choking on the | Where-Object command.

You should specify the & operator to run a string command.

You should specify the & operator to run a string command.

I tried that, but like Shelly mentioned above, I am getting an error (‘Where-Object’ is not recognized as an internal or external command, operable program or batch file.) on the Where-Object command. And that is where I am having trouble, not sure if it’s a formatting issue, or if I am just not able to run this command from a batch file, although I am almost sure it’s something I’m doing wrong.

Is what you posted pretty much your entire batch file? Is there a reason you cannot convert it to a PowerShell ps1 script?

Is what you posted pretty much your entire batch file? Is there a reason you cannot convert it to a PowerShell ps1 script?

As of right now it is part of a larger script used to create backups provided by a vendor, I am just modifying to make it a but more redundant as the backups are located locally on a desktop (if you can believe that).

Is what you posted pretty much your entire batch file? Is there a reason you cannot convert it to a PowerShell ps1 script?

As of right now it is part of a larger script used to create backups provided by a vendor, I am just modifying to make it a but more redundant as the backups are located locally on a desktop (if you can believe that).

Is there a reason you can’t have the batch file call a ps1 script instead?

You can run a batch file within PowerShell. I would run it as either a job or a process so that your file deletes do not conflict with whatever your batch file is trying to do. Take your PowerShell commands back out of the batch file, then run the following as a PowerShell script.

Keep them in the same directory to make things easier. If you do, the batch file line can be location neutral as long as both files are moved together.

You can run a batch file within PowerShell. I would run it as either a job or a process so that your file deletes do not conflict with whatever your batch file is trying to do. Take your PowerShell commands back out of the batch file, then run the following as a PowerShell script.

Keep them in the same directory to make things easier. If you do, the batch file line can be location neutral as long as both files are moved together.

I was trying to avoid that for simplicity’s sake (i’m trying to avoid taking complete owenership of this process lol), but I suppose I can go that route

I was able to run this from a batch file:

I didn’t have .PDFs or .PS files modified within the last two hours to test the exact same conditions, and I don’t want to delete files, so I output the results to text file. This ran on the first try without any errors or issues, and I got my output in text correctly.

The Where-Object clause should not cause any problems if you format the command correctly.

I was able to run this from a batch file:

I didn’t have .PDFs or .PS files modified within the last two hours to test the exact same conditions, and I don’t want to delete files, so I output the results to text file. This ran on the first try without any errors or issues, and I got my output in text correctly.

The Where-Object clause should not cause any problems if you format the command correctly.

No worries, this is the error I got when running that

I was able to run this from a batch file:

I didn’t have .PDFs or .PS files modified within the last two hours to test the exact same conditions, and I don’t want to delete files, so I output the results to text file. This ran on the first try without any errors or issues, and I got my output in text correctly.

The Where-Object clause should not cause any problems if you format the command correctly.

No worries, this is the error I got when running that

That error usually means that you have an odd number of brackets. Please post the exact code that you ran that generated this error.

I’ve made several powershell script for my customers. They have very little knowledge about SharePoint and Powershell.

I want to let them run these scripts when they want, but don’t want them to learn SharePoint Management shell.

What is the proper way to provide these scripts to the (power) users?

How to use a batch file to make powershell scripts easier to run

3 Answers 3

Give them a GUI : )

You could package the scripts into a console application with a simple menu to automate everything.

Or a WPF application. That would work too (and would look a heck of a lot nicer).

Just some more-user-friendly ideas.

Create a batch file(a text file with an extension of .bat). Inside the batch file write:

Put the batch file in the same directory as your PowerShell scripts. Your users can just double click the batch file. Easy as it gets. Make sure you explicitly load the SharePoint snap-in in your PowerShell scripts:

Have you tried PowerShell ISE? Check this link Download Powershell

ISE is an Integrated Development Environment to run and debug powershell in a more friendly way.

Hope this helps

How to use a batch file to make powershell scripts easier to run

Not the answer you’re looking for? Browse other questions tagged powershell or ask your own question.

Related

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

  • Blog
  • Facebook
  • Twitter
  • LinkedIn
  • Instagram

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.7.20.39804

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

How to use a batch file to make powershell scripts easier to run

Guest post

This is a guest post from Phil Factor. Phil Factor (real name withheld to protect the guilty), aka Database Mole, has 30 years of experience with database-intensive applications.

Despite having once been shouted at by a furious Bill Gates at an exhibition in the early 1980s, he has remained resolutely anonymous throughout his career.

He is a regular contributor to Simple Talk and SQLServerCentral.

How to use a batch file to make powershell scripts easier to run

  • Flyway
  • Database Builds and Deployments

How to create a batch file that executes any number of database migration tasks across a range of servers and databases, using Flyway.

Guest post

This is a guest post from Phil Factor. Phil Factor (real name withheld to protect the guilty), aka Database Mole, has 30 years of experience with database-intensive applications.

Despite having once been shouted at by a furious Bill Gates at an exhibition in the early 1980s, he has remained resolutely anonymous throughout his career.

He is a regular contributor to Simple Talk and SQLServerCentral.

Batch files are still in common use for automating database deployments because it is very easy to run lots of tasks concurrently, across several databases. Although PowerShell now dominates for database deployment tasks on Windows, many of Flyway’s features are intended as a way of making batch file automation easier.

The DOS batch files to run Flyway can be as simple as you like. Some can be little more than a means to preserve for repetitive use the list of commands required for a successful run of a task. They also provide a simple way of integrating with other build automation tools and software development tools.

In this article, I’ll show you how to create a batch file that automates database migrations for any number of databases, across several servers, upgrading every specified database to the requested version, from a single set of migration scripts. It is all very easy and very configurable. It is done by storing all the tasks as config files and executing them each in turn as parameters to Flyway. I show how to do something similar with PowerShell automation in Automating Migrations for Multiple Databases using Flyway.

In the past, before PowerShell became popular, Flyway command line has, when run in Windows, mainly been executed at the command prompt or within DOS batch scripts. These scripts don’t have the same level of risk with network security that you have with PowerShell. Some shops will even discourage the use of PowerShell, but I’ve never seen or heard of DOS batches being banned.

I’m currently working on a Flyway project in my programmer’s editor, creating a migration script, and it offers a good example of why you might choose to use a DOS batch script. They’re a breeze to integrate. I can run a ‘clean’, ‘info’, ‘migrate’, or ‘repair’ instantly, save a script to Git, as well as being able to execute the SQL Script, just by clicking a menu item. There are plenty of examples of such so scripts on the Internet. Like many programmers’ editors, the one I use allows you to extend its facilities. Although SSMS is my natural habitat, old developer habits occasionally kick in, and I grasp for a good programmer’s editor to help with trickier database development activities.

To understand how this works, it pays to appreciate the subtleties of the Flyway configuration files. If you use them sensibly, it saves you a lot of typing, and effort. When Flyway starts up, it reads several config files in order, as follows:

  1. /conf/flyway.conf file. You are likely to store here just the generic machine-level configuration items only, such as the license key or the text encoding system you use.
  2. /flyway.conf file, which would contain all the user-level information and any general information that should be kept private to your login, such as network credentials.
  3. /flyway.conf file. This is in the Flyway project directory and will have all the project-level configuration items that are shared.

These flyway.conf files are intended for your general work with Flyway and your project in general. However, you can still get Flyway to use other configurations by using the configuration parameter -configFiles=”myFirstconf,mySecondconf…” . These files can have any filename, but I think they ought to have a .conf filetype. What additional config files would you want to specify at the command line? Here, you’d want to specify the location of project-specific files that have connection details and any other details specific to a particular server or database. These need to be in a subfolder within your user area so they are protected. As you can supply a list of paths to config files, you can, if you want, save yourself time and effort by having a config file for each server, and a config file for each database as well and having one for project settings. You can then provide them in a list to the -configFiles configuration parameter. Flyway is very accommodating.

If you store these files in the user area, you can rely on Windows security to offer protection for files that may contain credentials. DOS Batch processing doesn’t have an easy way of doing encryption. If Flyway reads credentials direct from a config file in the user area, they never appear in the script, which is good for us and very tiresome for the hacker. It isn’t ideal for team-working though, especially when you need to make changes to the way databases are migrated, but then it isn’t hard to develop the system by setting up secure network shares.

Although Flyway Community doesn’t allow passwords to be stored in a vault, Flyway Teams is more geared to the corporate user as it allows access to HashiCorp Vault.

We’ll take advantage of all this by keeping a config file for every database that we want to manage. These are stored together in a config folder within the user area. Each copy of a database, Pubs in this example, will be managed from one project, one Scripts folder, and one config folder. This is easily expanded if required, as described previously.

A task for our DOS script consists of one or more databases for a single project that ought to be deployed at the same time. I’ll show later how we can define a subset that you want for a task, or don’t want.

To demonstrate, we’ll use the same long-suffering sample project PubsAndFlyway that we’ve used in previous articles and you can find the source scripts here:

We’ll need a folder of databases in the Home directory, each one represented by a config file like this:

How to use a batch file to make powershell scripts easier to run

A typical config file will have contents like this.

My name is Philipp C. Heckel and I write about nerdy things.

  • Stay connected
  • LinkedIn
  • GitHub

Snippet 0x05: Windows .bat: Checking if process is running by PID file

  • Aug 07 / 2014
  • 4
  • Batch, Code Snippets, Windows

How to use a batch file to make powershell scripts easier to run

Snippet 0x05: Windows .bat: Checking if process is running by PID file

Batch (.bat) files are an MS-DOS legacy technology and I don’t know a single person who loves writing them — and yet, to this day, many people have to do it. In order to run Java programs, start daemons or check if a process is running, batch files have to be used. For my open source file sync tool Syncany, I had to do just that:

The Syncany daemon runs in the background and is started by a batch script. To check if the daemon is already running, the batch script needs to read a PID file and determine if a process with this PID is running.

Since it took me an enormeous amount of time to figure out how to do that (I am a Linux guy!), I wanted to share that little script in this code snippet.

  1. 1. Full code
  2. 2. Read PID file, and check if process running
  3. 3. Issues and justification
  4. A. About this post

1. Full code

As always, the full working code (embedded in a my open source file sync software Syncany is available on GitHub. Feel free to use it, or to leave feedback in the comments.

2. Read PID file, and check if process running

Assuming that the application writes a PID file, the batch script has to do two things: First, it needs to check whether that PID file exists. If it doesn’t the application is obviously not running (or the PID file creation failed for some reason).

And second, check if the process ID in the PID file is actually running. If it is, the daemon/process is running. If it is not, the process has probably crashed or has forgotten to clean up after itself. In that case, we can consider the process not running.

Without further ado, here’s the .bat file:

By default, the script is assumed to be not running, so only if the PID file exists (if exist ..), the file is read (set /P APID= . ) and check if that file has a size of zero (if not defined size set size=0).

In the last bit, we check if the process ID is not -1, and the size of the temporary error output file is zero (no error); and only then we set RUNNING=1.

3. Issues and justification

I most certainly realize that this solution is not great. I’d even go as far as to say it’s a dirty workaround. However, all the other solutions I’ve tried (tasklist .. | find and checking for the %ERRORLEVEL%) were terribly unreliable. In particular, the find errorlevel/exit code arbitraribly returned 0 (99%), 1 or 9009 — even if the state of the daemon/process did not change. The solution above works just fine, and I hope it’ll help you guys somehow.

A. About this post

I’m trying a new section for my blog. I call it Code Snippets. It’ll be very short, code-focused posts of things I recently discovered or find fascinating or helpful. I hope this helps.

4 Comments

Great!
Thankyou for this share!

You said: “In order to run Java programs, start daemons or check if a process is running, batch files have to be used.”

That’s not true, PowerShell can do all those things in a much more structured way than batch files. I rarely find that I _must_ use batch files. There are times that they are more convenient than PowerShell scripts since they work automatically as drop targets on Windows but even then I often use the batch file to pass the dropped filename to a PowerShell script. I bet I could make ps1 files valid drop targets too but I just haven’t bothered.

That could be done in just a couple relevant lines of PowerShell script like this:
$id = get-content $env:APPDATA\Syncany\daemon.pid -ErrorAction SilentlyContinue
$env:RUNNING = $(get-process -Id $id).Count

You could even replace the $id in the second line with the first line wrapped in $() and make it a single line script. If the process doesn’t exist then you will get an error message at the prompt about $id being null. With a little more scripting that error could be avoided but it’s not harmful to the function of the script.

I know that wasn’t the point of your blog post but PowerShell has been around for quite a while now so I hate to see batch files used when PowerShell would be so much easier.

I’ve never done any PS (not a Windows person). I’ll certainly give it a shot though. Thanks for the comment.

Came across this in a google search. you saved me a day of coding. thanks!

Leave a comment

I’d very much like to hear what you think of this post. Feel free to leave a comment. I usually respond within a day or two, sometimes even faster. I will not share or publish your e-mail address anywhere.

Azure Pipelines | Azure DevOps Server 2020 | Azure DevOps Server 2019 | TFS 2018 – TFS 2015

Use this task to run a Windows .bat or .cmd script. Optionally, allow it to permanently modify environment variables.

This task is not compatible with Windows containers. If you need to run a batch script on a Windows container, use the command line task instead.

For information on supporting multiple platforms, see cross platform scripting.

In Microsoft Team Foundation Server (TFS) 2018 and previous versions, build and release pipelines are called definitions, runs are called builds, service connections are called service endpoints, stages are called environments, and jobs are called phases.

YAML snippet

Arguments

ArgumentDescription
filename
Path
(Required) Path of the cmd or bat script to execute. Should be fully qualified path or relative to the default working directory (please note that working directory could differ from ‘workingFolder’ which could be specified for this task).
arguments
Arguments
(Optional) Specify arguments to pass to the script.
modifyEnvironment
Modify environment
(Optional) Determines whether environment variable modifications will affect subsequent tasks
Default value: False
workingFolder
Working folder
(Optional) Current working directory when script is run. Defaults to the agent’s default working directory
failOnStandardError
Fail on Standard Error
(Optional) If this is true, this task will fail if any errors are written to the StandardError stream.
Default value: false

Example

Create test.bat at the root of your repo:

On the Build tab of a build pipeline, add this task:

Open source

This task is open source on GitHub. Feedback and contributions are welcome.

Where can I learn Windows commands?

How do I set a variable so that it can be read by subsequent scripts and tasks?

To learn more about defining build variables in a script, see Define and modify your build variables in a script.

To learn more about defining release variables in a script, see Define and modify your release variables in a script.

Q: I’m having issues with publishing my artifacts. How can I view the detailed logs?

To enable detailed logs for your pipeline:

  1. Edit your pipeline and select Variables
  2. Add a new variable with the name System.Debug and value true
  3. Save

Q: Which variables are available to me?

A: $(Build.SourcesDirectory) and $(Agent.BuildDirectory) are just few of the variables you can use in your pipeline. Variables are available as expressions or scripts.

Do I need an agent?

You need at least one agent to run your build or release.

I’m having problems. How can I troubleshoot them?

I can’t select a default agent pool and I can’t queue my build or release. How do I fix this?

My NuGet push task is failing with the following error: “Error: unable to get local issuer certificate”. How can I fix this?

This can be fixed by adding a trusted root certificate. You can either add the NODE_EXTRA_CA_CERTS=file environment variable to your build agent, or you can add the NODE.EXTRA.CA.CERTS=file task variable in your pipeline. See Environment variables for more details.

I use TFS on-premises and I don’t see some of these features. Why not?

Some of these features are available only on Azure Pipelines and not yet available on-premises. Some features are available on-premises if you have upgraded to the latest version of TFS.

How to use a batch file to make powershell scripts easier to run

If you work with a computer long enough, you’ll end up developing a few workflows. These can be simple or complex, but it’s likely you’ll end up with a few that are unique to you. The more you do with your computer, the more likely you’ll end up using the Command Prompt or the more powerful PowerShell.

Sometimes you might find yourself running the same few commands every time you launch PowerShell or the command prompt. Instead, why not save some time and run them automatically on launch?

What Can You Do with Automatic Commands?

You may have a workflow that sees you creating a bunch of files in a directory each time you use Command Prompt or PowerShell. With automatic commands you can clean that directory each time you open a prompt. You can also use this to change the default directory the Command Prompt or PowerShell opens in.

Those are just a few examples. Your own workflows will dictate what you automatically run.

Setting Up Automatic PowerShell Commands

To run commands automatically in PowerShell, edit your profile. To get started, check to see if you have a profile already. Open PowerShell and type the following:

This will return either True or False. If it’s false, run the following command:

This will overwrite any existing profile. If the previous command returned True, you likely don’t want to run this. If you want to start over, go right ahead.

How to use a batch file to make powershell scripts easier to run

To actually set up your automatic commands, edit your profile. Use the text editor of your choice, but Notepad is installed by default. Edit the file in Notepad by typing the following:

Put any commands you can run in PowerShell here, and they’ll automatically run every time you open it. If you’re familiar with Linux, this is essentially the same as editing your “

In most cases PowerShell’s execution policy will prevent this script from running. This is to help keep your system safe. To allow your the script to run, launch PowerShell as administrator and run the following:

Read over the prompt and enter Y to set the new execution policy.

Setting Up Automatic Command Prompt Commands

Compared to the Unix-style approach you use to automatically run commands in PowerShell, the Command Prompt is much more Windows-like. There are two different ways to do this, depending on how you prefer to work.

Method 1: The Windows Registry

Like the PowerShell method above, this specifies a script to run every time that you launch the Command Prompt. Unlike that method, it uses the Windows Registry to define which file runs. For this example we’re assuming you want to use a file called “auto.cmd.”

To create the proper registry value, open the Command Prompt and run the following:

How to use a batch file to make powershell scripts easier to run

Now create a file in your profile folder (usually “C:\Users\USERNAME”) named “auto.cmd.”

Edit this file with the commands you want to run automatically when the Command Prompt is launched.

If you decide you no longer need this to run automatically, delete the registry key. Just run the following:

Method 2: Use a Shortcut

If you have a simple case and don’t want to use the registry, you can use a desktop shortcut. As an example, in Windows 10 you can find Command Prompt in the Start menu, right click and select “Open File Location”. Copy the Command Prompt shortcut here and paste it to your desktop.

Right-click on your newly pasted shortcut and select Properties. You’ll see a section with the app’s path. It will read like the following:

Simply alter this by adding -cmd /K and then the command or commands of your choosing. Here’s an example:

This will simply open the Command Prompt and then clear the screen. You can also chain commands by using && between them. Here’s another example:

This will clear the screen and then display the contents of the directory.

Conclusion

Depending on what you need to do, one or more of the above methods should work for you. If you end up using the Command Prompt even more, take a look at our guide to customizing how it looks.

Kris Wouk is a writer, musician, and whatever it’s called when someone makes videos for the web.