Run powershell script from windows powershell

How do I run a PowerShell script?

  • I have a script named myscript.ps1
  • I have all the necessary frameworks installed
  • I set that execution policy thing
  • I have followed the instructions on this MSDN help page
    and am trying to run it like so:
    powershell.exe 'C:\my_path\yada_yada\run_import_script.ps1' (with or without --noexit)

which returns exactly nothing, except that the file name is output.

No error, no message, nothing. Oh, when I add -noexit, the same thing happens, but I remain within PowerShell and have to exit manually.

The .ps1 file is supposed to run a program and return the error level dependent on that program’s output. But I’m quite sure I’m not even getting there yet.

What am I doing wrong?

Peter Mortensen's user avatar

asked Jan 9, 2010 at 22:19

Pekka's user avatar

1

Prerequisites:

  • You need to be able to run PowerShell as an administrator
  • You need to set your PowerShell execution policy to a permissive value or be able to bypass it

Steps:

  1. Launch Windows PowerShell as an Administrator, and wait for the PS> prompt to appear

  2. Navigate within PowerShell to the directory where the script lives:

    PS> cd C:\my_path\yada_yada\ (enter)
    
  3. Execute the script:

    PS> .\run_import_script.ps1 (enter)
    

Or: you can run the PowerShell script from the Command Prompt (cmd.exe) like this:

powershell -noexit "& ""C:\my_path\yada_yada\run_import_script.ps1""" (enter)

according to Invoking a PowerShell script from cmd.exe (or Start | Run) by Kirk Munro.

Or you could even run your PowerShell script asynchronously from your C# application.

TylerH's user avatar

TylerH

20.8k67 gold badges76 silver badges102 bronze badges

answered Jan 9, 2010 at 22:24

marc_s's user avatar

marc_smarc_s

734k176 gold badges1334 silver badges1460 bronze badges

6

If you are on PowerShell 2.0, use PowerShell.exe’s -File parameter to invoke a script from another environment, like cmd.exe. For example:

Powershell.exe -File C:\my_path\yada_yada\run_import_script.ps1

Peter Mortensen's user avatar

answered Jan 9, 2010 at 23:39

Keith Hill's user avatar

Keith HillKeith Hill

195k42 gold badges353 silver badges370 bronze badges

5

If you want to run a script without modifying the default script execution policy, you can use the bypass switch when launching Windows PowerShell.

powershell [-noexit] -executionpolicy bypass -File <Filename>

answered Jan 30, 2011 at 22:23

Chingiz Musayev's user avatar

Chingiz MusayevChingiz Musayev

2,8321 gold badge14 silver badges6 bronze badges

1

Type:

powershell -executionpolicy bypass -File .\Test.ps1

NOTE: Here Test.ps1 is the PowerShell script.

igr's user avatar

igr

10.2k13 gold badges65 silver badges111 bronze badges

answered Feb 5, 2015 at 22:38

Sudheesh's user avatar

SudheeshSudheesh

1,1591 gold badge7 silver badges2 bronze badges

1

I’ve had the same problem, and I tried and tried… Finally I used:

powershell.exe -noexit "& 'c:\Data\ScheduledScripts\ShutdownVM.ps1'"

And put this line in a batch-file, and this works.

Peter Mortensen's user avatar

answered Mar 8, 2010 at 13:47

Dennis's user avatar

DennisDennis

1,8103 gold badges22 silver badges42 bronze badges

If you only have PowerShell 1.0, this seems to do the trick well enough:

powershell -command - < c:\mypath\myscript.ps1

It pipes the script file to the PowerShell command line.

Peter Mortensen's user avatar

answered Jul 1, 2010 at 9:32

AndyM's user avatar

AndyMAndyM

3,5946 gold badges40 silver badges45 bronze badges

1

Pretty easy. Right click the .ps1 file in Windows and in the shell menu click on Run with PowerShell.

Peter Mortensen's user avatar

answered Aug 23, 2016 at 14:51

electronictonic's user avatar

1

  1. Open PowerShell in administrator mode
  2. Run: set-executionpolicy unrestricted
  3. Open a regular PowerShell window and run your script.

I found this solution following the link that was given as part of the error message: About Execution Policies

Make sure to run set-ExecutionPolicy default once you’re done, or you will be exposed to security risks.

TylerH's user avatar

TylerH

20.8k67 gold badges76 silver badges102 bronze badges

answered Sep 17, 2019 at 16:04

JovanToroman's user avatar

0

If your script is named with the .ps1 extension and you’re in a PowerShell window, you just run ./myscript.ps1 (assuming the file is in your working directory).

This is true for me anyway on Windows 10 with PowerShell version 5.1 anyway, and I don’t think I’ve done anything to make it possible.

Peter Mortensen's user avatar

answered Sep 6, 2016 at 19:58

rainabba's user avatar

rainabbarainabba

3,85435 silver badges36 bronze badges

3

Using cmd (BAT) file:

@echo off
color 1F
echo.

C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File "PrepareEnvironment.ps1"

:EOF
echo Waiting seconds
timeout /t 10 /nobreak > NUL

If you need run as administrator:

  1. Make a shortcut pointed to the command prompt (I named it
    Administrative Command Prompt)
  2. Open the shortcut’s properties and go to the Compatibility tab
  3. Under the Privilege Level section, make sure the checkbox next to «Run this program as an administrator» is checked

answered Nov 17, 2014 at 9:04

Kiquenet's user avatar

KiquenetKiquenet

14.6k35 gold badges148 silver badges243 bronze badges

An easy way is to use PowerShell ISE, open script, run and invoke your script, function…

Enter image description here

Peter Mortensen's user avatar

answered Nov 1, 2016 at 16:39

Jose Evaristo Cepeda Barrera's user avatar

0

  • Give the path of the script, that is, path setting by cmd:

    $> . c:\program file\prog.ps1

  • Run the entry point function of PowerShell:

    For example, $> add or entry_func or main

Peter Mortensen's user avatar

answered Jun 16, 2013 at 9:28

pkm's user avatar

pkmpkm

2,7032 gold badges30 silver badges44 bronze badges

1

You can run from cmd like this:

type "script_path" | powershell.exe -c -

answered Aug 23, 2020 at 7:30

Wasif's user avatar

WasifWasif

14.8k3 gold badges14 silver badges34 bronze badges

Use the -File parameter in front of the filename. The quotes make PowerShell think it is a string of commands.

Peter Mortensen's user avatar

answered Aug 1, 2018 at 11:17

Engineer's user avatar

EngineerEngineer

8341 gold badge13 silver badges27 bronze badges

0

I’ve just found the method what Microsoft do when we right click on a ps1 script and click on «Run with PowerShell» :

"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & 'C:\Users\USERNAME\Desktop\MYSCRIPT.ps1'"

answered Mar 31, 2022 at 8:19

Roukmoute's user avatar

RoukmouteRoukmoute

6811 gold badge11 silver badges26 bronze badges

With the appropriate execution policy, you should just be able to call the file directly and Windows will associate it with PowerShell

C:\my_path\yada_yada\run_import_script.ps1

That does not do so well with arguments. The real answer to your question is that you are missing the & to say «execute this»

powershell.exe '& C:\my_path\yada_yada\run_import_script.ps1'

answered Jan 6, 2022 at 3:03

carrvo's user avatar

carrvocarrvo

5115 silver badges11 bronze badges

If you’re new to the PowerShell scripting language and want to learn how to run PowerShell script, you’ve come to the right blog post. This blog will be a tutorial covering common ways to run scripts and a few issues that may pop up.

Not a reader? Watch this related video tutorial!

Not seeing the video? Make sure your ad blocker is disabled.

Announcing a Free LIVE training – Starting your PowerShell Journey – presented by Johan Arwidmark. Understand how PowerShell skills enhance your IT career, learn where to start with PowerShell, build your first scripts, and ask Johan questions directly in a live training environment.

Prerequisites

This article will be a walkthrough for you about how to run PowerShell on your local computer. If you’d like to follow along, please be sure you have the following prerequisites in place before starting this article.

  • A Windows 10 computer with Administrator privileges.
  • Windows PowerShell version 5 or higher. You can also use PowerShell v7. This tutorial will focus on Windows PowerShell since the Windows operating system already has it.
  • Any text file editor

Dealing with the Execution Policy

If this is the first time you’re trying to execute a Windows PowerShell script, you may run into a common problem. PowerShell will probably return an error message stating that a script “cannot be loaded because running scripts is disabled on this system”.

PS> .\GetServices.ps1
 File C:\Temp\GetServices.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at
 https:/go.microsoft.com/fwlink/?LinkID=135170.
 At line:1 char:1
 .\GetServices.ps1
 ~~~~~ CategoryInfo          : SecurityError: (:) [], PSSecurityException
 FullyQualifiedErrorId : UnauthorizedAccess   

PowerShell returns the error message above when you try to run a PowerShell with an execution policy set to Restricted, Remote Signed or All Signed.

Restricted

Restricted is the default policy set for Windows client computers. If you are using PowerShell for the first time, your default policy would probably be set to restrict all the scripts.

You can still execute individual commands in a terminal, but not a script file. The restriction includes any file ending with .ps1xml, .psm1 or .ps1.

Unrestricted

Unrestricted allows you to run any script however, it warns you before execution if the script is downloaded from the internet. This policy is usually the default for any non-windows devices.

Remote Signed

Remote Signed policy allows you to run any script that is either (a) digitally signed or (b) any script written on your local computer with or without a signature.

If a script is downloaded from the internet and not signed, you would need to unblock the file. You can do so by right-clicking on the file and choosing Properties. Or, you could use the Unblock-File PowerShell cmdlet for that particular script file.

Using a Remote signed policy would be an ideal option when running a script downloaded from the internet.

All Signed

All signed requires all the scripts to be signed digitally by a trusted publisher. This includes the scripts downloaded from the internet and written locally on your computer.

Changing the PowerShell Execution Policy

To change the execution policy:

  1. Open Windows PowerShell with Run as Administrator to make sure you have the highest permission to make the policy changes.
Search PowerShell in Start Menu
Search PowerShell in Start Menu

2. When open, run the following PowerShell command to set your computer’s execution policy. The execution policy, as covered above, can be one of three different types. This tutorial is using a useful yet still secure execution policy of RemoteSigned.

Since this tutorial assumes you’ve downloaded from the Internet the GetServices.ps1 script file, set the execution policy to RemoteSigned.

The RemoteSigned execution policy forces you to cryptographically sign every PowerShell script downloaded from the Internet before PowerShell will run it on your system.

3. You should see an output requesting to confirm the action. Enter Y and hit enter to confirm the policy change.

Execution Policy Change
 The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose you to the
 security risks described in the about_Execution_Policies help topic at https:/go.microsoft.com/fwlink/?LinkID=135170. Do you want to
 change the execution policy?
 [Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "N"): 

At this point, follow the next steps to explore different methods to run the PowerShell script on your computer.

How to Run PowerShell Script

To demonstrate running a PowerShell script, you actually need a script file to run! If you don’t have one handy, download this ZIP file and extract the PS1 file within. You’ll find a simple script file inside called GetServices.ps1.

Write-Output "Listing Computer Services"
Get-Service

Every PowerShell script should end with a .ps1 extension.

Using the Console

Once you have a script ready, there are a few different ways you can execute a PowerShell script file. One of the most common ways is via the PowerShell console.

To do so:

  1. Open the PowerShell console as shown above.

2. Navigate to the file system location your script is located using the Set-Location PowerShell cmdlet or the cd alias. This tutorial’s script is found in the C:\Temp directory.

3. Run the script using a dot (.) notation. PowerShell is a shell that also looks for command names. To differentiate between a PowerShell command and a script, you must preface the script with a dot. This dot represents the current directory.

How to Run a PowerShell Script from the Command Line via the PowerShell Location

If you can’t or would rather not run scripts via the PowerShell console, you can also do so with the good ol’ command line (command prompt).

To run scripts via the command prompt, you must first start up the PowerShell executable (powershell.exe), with the PowerShell location of C:\Program Files\WindowsPowerShell\powershell.exe and then pass the script path as a parameter to it.

You can run scripts with parameters in any context by simply specifying them while running the PowerShell executable like powershell.exe -Parameter 'Foo' -Parameter2 'Bar'.

Once you open cmd.exe, you can execute a PowerShell script like below. This example is running the engine and passing it the script path of C:\Temp\GetServices.ps1.

Notice below that the example below is using the PowerShell location path to run the script. You’ll have to do this if the folder isn’t in your PATH somewhere.

CMD> C:\Program Files\WindowsPowerShell\powershell.exe "C:\Temp\GetServices.ps1"

The PowerShell location for PowerShell 7 uses a different executable named pwsh.exe typically located in C:\Program Files\PowerShell\7\pwsh.exe.

Below is a handy YouTube video that covers executing a script via a batch file which the cmd.exe executes.

Using the PowerShell ISE

If you create your own scripts or edit others’, you’ll probably be using a script editor like the PowerShell ISE or maybe Visual Studio (VS) Code. Since the ISE comes with Windows, let’s focus on that method for this tutorial.

To invoke a script via the ISE:

  1. Navigate to Start Menu, search for PowerShell ISE and open it.
Search PowerShell ISE in Start Menu
Search PowerShell ISE in Start Menu

2. Click on FileOpen and find your script.

Open Script using File Menu
Open Script using File Menu

3. With the script open, click on the green run button to execute the script. This button will invoke the script in the built-in PowerShell terminal at the bottom.

Run Script using PowerShell ISE
Run Script using PowerShell ISE

The Sample Script’s Output

A PowerShell script can sometimes return output. This happens when the script you’re executing is built to return objects which is a fundamental component of PowerShell.

If you run the sample GetServices.ps1 script, you will see the following. This script runs the Get-Service cmdlet which returns all of the services installed on your local Windows computer.

PS> .\GetScripts.ps1
Listing Computer Services
Status   Name               DisplayName
------   ----               -----------
Running  aakore             Acronis Agent Core Service
Stopped  AarSvc_1b668d      Agent Activation Runtime_1b668d
Running  AcronisActivePr... Acronis Active Protection Service
Running  AcronisCyberPro... Acronis Cyber Protection Service
Running  AcrSch2Svc         Acronis Scheduler2 Service
Running  AdobeARMservice    Adobe Acrobat Update Service
Running  AdobeUpdateService AdobeUpdateService
Running  AGMService         Adobe Genuine Monitor Service
Running  AGSService         Adobe Genuine Software Integrity Se...
----Truncated----

Announcing a Free LIVE training – Starting your PowerShell Journey – presented by Johan Arwidmark. Understand how PowerShell skills enhance your IT career, learn where to start with PowerShell, build your first scripts, and ask Johan questions directly in a live training environment.

Running a PowerShell Script from Within a Script

Let’s say you have two scripts and you’d like one to call the other. Perhaps you have a script called GetUser.ps1 and one called ResetPassword.ps1. Inside of the GetUser.ps1 script, you’d like to execute the ResetPassword.ps1 to reset a user password.

Inside of the calling script (GetUser.ps1), you’d add a line to execute the other script just like you would call the script from the command line.

You can see below you have a couple of options. You should typically choose to run the other script within the same session or scope to simplify things unless you have a specific reason to run the script in another PowerShell session.

## To run the other script in a new session
powershell.exe .\ResetPassword.ps1
## To run the other script in the same session
.\ResetPassword.ps1

Running from PowerShell Command-Line

To run a PowerShell script(.ps1 file) from a PowerShell command line:

  • Launch the PowerShell as an Administrator and wait for the PS> prompt to appear.
  • Navigate to the directory having your PowerShell script file.
  • Type .\ followed by the ScriptFileName.ps1 and hit Enter to execute the script.

.\test.ps1

&lt;#

test.ps1 has the following command that will

be executed when we will run the script

WriteHost «You’ve successfully run PowerShell Script.»

#&gt;

Youve successfully run PowerShell Script.

You must fulfil some prerequisites to execute the PowerShell script by following the above mentioned steps. First, you must be able to run the PowerShell as an Administrator. Second, you must be able to ByPass the PowerShell execution policy or set it to a permissive value.

Now, the point is, why do we have to set or ByPass the execution policy? It is because the PowerShell execution policy is set to Restricted due to its default behaviour, which means you can not run the .ps1 file. For the execution policy, we have a few options that are listed below:

  • Restricted – It is the default option, which does not allow running a PowerShell script.
  • Unrestricted – We can not run any script; it shows warnings for the downloaded scripts.
  • AllSigned – It allows running signed scripts from trusted publishers only.
  • ByPass – It lets us run all scripts without any warnings.
  • RemoteSigned – This option needs a digital signature for the downloaded scripts. We can execute scripts that are written locally and unblock the downloaded scripts to execute them without the signature.

You can check this for more details about these options. We can also run the .ps1 by Right Click on the script file and selecting Run with PowerShell.

Running from Windows Command-Line

Use powershell -noexit to run a PowerShell script from the Windows Command line (cmd.exe).

powershell noexit «&amp; ««E:\Test\test.ps1»«»

&lt;#

test.ps1 has the following command that will

be executed when we will run the script

WriteHost «You’ve successfully run PowerShell Script.»

#&gt;

Youve successfully run PowerShell Script.

The above command was used to run the specified PowerShell script.

Let’s split it into chunks to understand each part of it.

First, we used the powershell to launch the PowerShell environment while the -noexit parameter was used to keep the PowerShell window open even after the script was finished executing. This way, we can see the output generated by the script file that just ran. Next, we used the call operator represented by the & sign to run the command, script block or expression.

This command is run from the Windows Run Dialog (opened with Windows key+ R) or from the command prompt as we did above. Note that the output will be visible in the PowerShell window if you run it from Windows Run Dialog. On the other hand, if you run it from Windows Command Prompt, you will see the output without opening PowerShell Window.

Using Invoke Expression Cmdlet

To run a ps1 file from PowerShell command line:

  • Launch the PowerShell as an Administrator and wait for the PS> prompt to appear.
  • Navigate to the location where your PowerShell script file lives.
  • Use the Invoke-Expression cmdlet to run the PowerShell script.

InvokeExpression .\test.ps1

&lt;#

test.ps1 has the following command that will

be executed when we will run the script

WriteHost «You’ve successfully run PowerShell Script.»

#&gt;

Youve successfully run PowerShell Script.

The Invoke-Expression cmdlet is used to run the expression or commands on our local computer. It runs or evaluates the given string as a command and returns the outcomes of the specified command or expression.

That’s all about how to run ps1 File From PowerShell.

Running Windows PowerShell Scripts

Customizing the Conosle

Few things in life are as exciting as getting a brand-new command shell and scripting language; in fact, getting a brand-new command shell and scripting language is soexciting that you can barely get the thing out of the box before you want to take it for a spin. Those of you who’ve downloaded Windows PowerShell know exactly what we’re talking about: if you’re like most people, the very moment the installation process finished you double-clicked a .PS1 file (.PS1 being the file extension for Windows PowerShell scripts), sat back, and waited for the magic to happen.

As it turned out, however, this is what happened:

PowerShell Script in Notepad

Hmmm, instead of running, your script opened up in Notepad. Interesting, but not exactly what you had in mind. Oh wait, you think, I get it: you probably have to run Windows PowerShell before you can run a Windows PowerShell script. OK, that makes sense. And so, with that in mind, you open up Windows PowerShell and type the path to the .PS1 file at the command prompt. You press ENTER and wait for the magic to happen:

As it turned out, however, this is what happens:

File C:\scripts\test.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see "get-
help about_signing" for more details.
At line:1 char:19
+ c:\scripts\test.ps1 <<<<

Wow; how nice. A new command shell and scripting environment that doesn’t even let you run scripts. What will those guys at Microsoft think of next?

Listen, don’t panic; believe it or not, everything is fine. You just need to learn a few little tricks for running Windows PowerShell scripts. And the Scripting Guys are here to help you learn those tricks.

Running Scripts From Within Windows PowerShell

Customizing the Conosle

Let’s start with running scripts from within Windows PowerShell itself. (Which, truth be told, is probably the most common way to run Windows PowerShell scripts.) Why do you get weird error messages when you try to run a script? That’s easy. The security settings built into Windows PowerShell include something called the “execution policy;” the execution policy determines how (or if) PowerShell runs scripts. By default, PowerShell’s execution policy is set to Restricted; that means that scripts – including those you write yourself – won’t run. Period.

Note. You can verify the settings for your execution policy by typing the following at the PowerShell command prompt and then pressing ENTER:

Now, admittedly, this might seem a bit severe. After all, what’s the point of having a scripting environment if you can’t even run scripts with it? But that’s OK. If you don’t like the default execution policy (and you probably won’t) then just go ahead and change it. For example, suppose you want to configure PowerShell to run – without question – any scripts that you write yourself, but to run scripts downloaded from the Internet only if those scripts have been signed by a trusted publisher. In that case, use this command to set your execution policy to RemoteSigned:

Set-ExecutionPolicy RemoteSigned

Alternatively, you can set the execution policy to AllSigned (all scripts, including those you write yourself, must be signed by a trusted publisher) or Unrestricted (all scripts will run, regardless of where they come from and whether or not they’ve been signed).

See? No need to need to panic at all, is there?

Note. Not sure what we mean by “signing scripts?” Then open up PowerShell, type the following, and press ENTER:

Or, even better, download our Windows PowerShell Graphical Help File and read the same topic in standard Windows help format.

After you change your execution policy settings it’s possible to run scripts. However, you still might run into problems. For example, suppose you change directories from your Windows PowerShell home directory to C:\Scripts (something you can do by typing cd C:\Scripts). As it turns out, the C:\Scripts folder contains a script named Test.ps1. With that in mind you type the following and the press ENTER:

And here’s the response you get:

The term 'test.ps1' is not recognized as a cmdlet, function, operable program, or script file. Verify the term and try again.
At line:1 char:7
+ test.ps1 <<<<

We know what you’re thinking: didn’t we just change the execution policy? Yes, we did. However, this has nothing to do with the execution policy. Instead, it has to do with the way that PowerShell handles file paths. In general, you need to type the complete file path in order to run a script. That’s true regardless of your location within the file system. It doesn’t matter if you’re in C:\Scripts; you still need to type the following:

Now, we said “in general” because there are a couple of exceptions to this rule. For example, if the script happens to live in the current directory you can start it up using the .\notation, like so:

Note. There’s no space between the .\ and the script name.

And while PowerShell won’t search the current directory for scripts it will search all of the folders found in your Windows PATH environment variable. What does that mean? That means that if the folder C:\Scripts is in your path then you can run the script using this command:

But be careful here. Suppose C:\Scripts is not in your Windows path. However, suppose the folder D:\Archive is in the path, and that folder also contains a script named Test.ps1. If you’re in the C:\Scripts directory and you simply type Test.ps1 and press ENTER, guess which script will run? You got it: PowerShell won’t run the script in C:\Scripts, but it will run the script found in D:\Archive. That’s because D:\Archive is in your path.

Just something to keep in mind.

Note. Just for the heck of it, here’s a command that retrieves your Windows PATH environment variable and displays it in a readable fashion:

$a = $env:path; $a.Split(";")

Even More About File Paths

Customizing the Conosle

Now we know that all we have to do is type in the full path to the script file and we’ll never have to worry about getting our scripts to run, right? Right.

Well, almost right. There’s still the matter of scripts whose path name includes a blank space. For example, suppose you have a script stored in the folder C:\My Scripts. Try typing this command and see what happens:

Of course, by now you’ve come to expect the unexpected, haven’t you? Here’s what you get back:

The term 'C:\My' is not recognized as a cmdlet, function, operable program, or script file. Verify the term and try again.
At line:1 char:8
+ C:\My  <<<< Scripts\Test.ps1

This one you were able to figure out on your own, weren’t you? Yes, just like good old Cmd.exe, PowerShell has problems parsing file paths that include blank spaces. (In part because blank spaces are how you separate command-line arguments from the call to a script.) In Cmd.exe all you can work around this problem by enclosing the path in double quotes. Logically enough, you try the same thing in PowerShell:

And here’s what you get back:

Um, OK …. You try it again. And here’s what you get back:

You try it – well, look, there’s no point in trying it again: no matter how many times you try this command, PowerShell will simply display the exact same string value you typed in. If you actually want to execute that string value (that is, if you want to run the script whose path is enclosed in double quotes) you need to preface the path with the Call operator (the ampersand). You know, like this:

& "C:\My Scripts\Test.ps1"

Note. With this particular command you can either leave a space between the ampersand and the path name or not leave a space between the ampersand and the path name; it doesn’t matter.

To summarize, here’s how you run from scripts from within Windows PowerShell:

  • Make sure you’ve changed your execution policy. By default, PowerShell won’t run scripts at all, no matter how you specify the path.
  • To run a script, specify the entire file path, or either: 1) use the .\ notation to run a script in the current directory or 2) put the folder where the script resides in your Windows path.
  • If your file path includes blank spaces, enclose the path in double quote marks and preface the path with an ampersand.

And, yes, that all takes some getting used to. However, you will get used to it. (To make life easier for you, we recommend that you keep all your scripts in one folder, such as C:\Scripts, and add that folder to your Windows path.)

Note. So can you use PowerShell to add a folder to your Windows Path? Sure; here’s a command (that we won’t bother to explain in this introductory article) that tacks the folder C:\Scripts onto the end of your Windows path:

$env:path = $env:path + ";c:\scripts"

Bonus: “Dot Sourcing” a Script

Customizing the Conosle

Admittedly, up to this point the news hasn’t been all that good: you can’t run a PowerShell script by double-clicking the script icon; PowerShell doesn’t automatically look for scripts in the current working directory; spaces in path names can cause all sorts of problems; etc. etc. Because of that, let’s take a moment to talk about one very cool feature of Windows PowerShell scripting: dot sourcing.

Suppose we have a very simple VBScript script like this one:

If you run this script from the command window, the script will run just fine. However, because we forgot to include an Echo statement we won’t see anything happen onscreen. Because of that we’ll never know the value of C. Sure, we could try typing Wscript.Echo C at the command prompt, but all we’ll get back is the following error message:

'Wscript.echo' is not recognized as an internal or external command,
operable program or batch file.

That should come as no surprise: scripts are scripts, the command window is the command window, and ne’er the twain shall meet. Sure, it would be nice if the command window had access to values that were assigned in a script (and vice-versa), but it ain’t gonna happen.

At least not in VBScript.

Now, let’s consider a Windows PowerShell counterpart to our VBScript script:

$A = 5
$B = 10
$C = $A + $B

Suppose we run this script, then type $C at the command prompt. What do you think we’ll get back? If you guessed nothing, then you guessed correctly:

Variables

In other words, we don’t get back anything at all. Which, again, should come as no great surprise. Come on, Scripting Guys; shouldn’t this be leading us somewhere?

Yes, it should. And believe it or not, it is. Let’s run our PowerShell script again, only this time let’s “dot source” it; that is, let’s type a period and a blank space and then type the path to the script file. For example:

When we run the script nothing will seem to happen; that’s because we didn’t include any code for displaying the value of $C. But now try typing $C at the command prompt . Here’s what you’ll get back:

Good heavens! Was this a lucky guess on the part of the PowerShell console, or is this some sort of magic?

Surprisingly enough, it’s neither. Instead, this is dot sourcing. When you dot source a script (that is, when you start the script by prefacing the path to the script file with a dot and a blank space) any variables used in the script become global variables that are available in multiple scopes. What does that mean? Well, a script happens to represent one scope; the console window happens to represent another scope. We started the script Test.ps1 by dot sourcing it; that means that the variable $C remains “alive” after the script ends. In turn, that means that this variable can be accessed via the command window. In addition, these variables can be accessed from other scripts. (Or at least from other scripts started from this same instance of Windows PowerShell.)

Suppose we have a second script (Test2.ps1) that does nothing more than display the value of the variable $C:

Look what happens when we run Test2.ps1 (even if we don’t use dot sourcing when starting the script):

Cool. Because $C is a global variable everyone has access to it.

And, trust us here: this is pretty cool. For example, suppose you have a database that you periodically like to muck around with. If you wanted to, you could write an elaborate script that includes each and every analysis you might ever want to run on that data. Alternatively, you could write a very simple little script that merely connects to the database and returns the data (stored in a variable). If you dot source that script on startup you can then sit at the command prompt and muck around with the data all you want. That’s because you have full access to the script variables and their values.

Note. OK, sure, this could cause you a few problems as well, especially if you tend to use the same variable names in all your scripts. But that’s OK; if you ever need to wipe out the variable $C just run the following command (note that, with the Remove-Variable cmdlet, we need to leave off the $ when indicating the variable to be removed):

Play around with this a little bit and you’ll start to see how useful dot sourcing can be.

Running Scripts Without Starting Windows PowerShell

Customizing the Conosle

We realize that it’s been awhile, but way back at the start of this article we tried running a Windows PowerShell script by double-clicking a .PS1 file. That didn’t go quite the way we had hoped: instead of running the script all we managed to do was open the script file in Notepad. Interestingly enough, that’s the way it’s supposed to work: as a security measure you can’t start a PowerShell script by double-clicking a .PS1 file. So apparently that means that you do have to start PowerShell before you can run a PowerShell script.

In a somewhat roundabout way, that’s technically true. However, that doesn’t mean that you can’t start a PowerShell script from a shortcut or from the Run dialog box; likewise you can run a PowerShell script as a scheduled task. The secret? Instead of calling the script you need to call the PowerShell executable file, and then pass the script path as an argument to PowerShell.exe. For example, in the Run dialog box you might type a command like powershell.exe -noexit c:\scripts\test.ps1:

Running Scripts from the Run Dialog

There are actually three parts to this command:

  • Powershell.exe, the Windows PowerShell executable.
  • -noexit, an optional parameter that tells the PowerShell console to remain open after the script finishes. Like we said, this is optional: if we leave it out the script will still run. However, the console window will close the moment the script finishes, meaning we won’t have the chance to view any data that gets displayed to the screen.Incidentally, the -noexit parameter must immediately follow the call to the PowerShell executable. Otherwise the parameter will be ignored and the window will close anyway.
  • C:\Scripts\Test.ps1, the path to the script file.

What if the path to the script file contains blank spaces? In that case you need to do the ampersand trick we showed you earlier; in addition, you need to enclose the script path in single quote marks, like so:

powershell.exe -noexit &'c:\my scripts\test.ps1'

Strange, but true!

Note. Here’s an interesting variation on this same theme: instead of starting PowerShell and asking it to run a particular script you can start PowerShell and ask it to run a particular command. For example, typing the following in the Run dialog box not only starts PowerShell but also causes it to run the Get-ChildItem cmdlet against the folder C:\Scripts:

powershell.exe -noexit get-childitem c:\scripts

It’s possible to get even more elaborate when starting Windows PowerShell, but this will do for now. If you’d like more information on PowerShell startup options just typepowershell.exe /? from either the Windows PowerShell or the Cmd.exe command prompt.

By the way, this is the same approach you need to use if you want to run a Windows PowerShell script as part of a logon script. You can’t simply assign a .PS1 file as a logon script; the operating system won’t know what to do with that. Instead, you’ll need to create a VBScript script that calls the PowerShell script:

Set objShell = CreateObject("Wscript.Shell")
objShell.Run("powershell.exe -noexit c:\scripts\test.ps1")

Assign this VBScript script as the logon script and everything should work just fine. (Assuming, of course, that you’ve installed Windows PowerShell on any computers where this logon script is going to run.)

PowerShell scripts are a great way to automate tasks, gather information, or modify properties in bulk. Most PowerShell commands are only a single line that you can just copy and paste into PowerShell. But how do you run a complete PowerShell Script?

There are a couple of options when it comes to running PowerShell scripts, simply from the cmd, using the PowerShell ISE, or even a scheduled task.

In this article, I will explain the different options to run a PowerShell script. Also, I will help you with common errors, like “running scripts is disabled on this system”.

Fix Running Scripts is Disabled on this System

We are going to start with a common error that prevents most users from running a PowerShell script, the error “Running scripts is disabled on this system”. This error is caused by the PowerShell Execution Policy.

By default, the PowerShell Execution policy is set to Restricted. This means that PowerShell scripts won’t run at all.

Running scripts is disabled on this system

So to run a PowerShell script, we first need to change the execution policy. For the policy we have a couple of options:

Execution Policy Description
Restricted Default option – does not allow to run any PowerShell script
Unrestricted Can run any script, shows warning for downloaded scripts
RemoteSigned Requires a digital signature for downloaded scripts. You can
run locally written scripts. You can unblock downloaded scripts
to run them without signature
ByPass You can run all scripts and no warnings are displayed
AllSigned You can only run signed scripts from trusted publishers

Execution Policies are not designed as a security model, but more to prevent the accidental execution of a PowerShell script. The best option is to use the RemoteSigned policy, this way you can’t run a downloaded script by accident (you will have to unblock it first). Read more about the execution policy in this article.

Tip

Learn more about writing your own PowerShell scripts in this complete guide

To change the execution policy in PowerShell (and fix “Running scripts is disabled on this system) we need to start PowerShell with administrator privilege:

  1. Press Windows key + X (or right click on the start menu)
  2. Choose Windows PowerShell (admin)
  3. Run the command below:
Set-ExecutionPolicy RemoteSigned

You should now be able to run PowerShell Scripts.

There are a couple of options to run a PowerShell script. The most convenient way is to simply right-click the file and choose Run with PowerShell.

run powershell script

Run PowerShell Script

But this method comes with a downside. By default, most PowerShell scripts will close the PowerShell window automatically when the script is done. So the script gets executed, but you won’t be able to read any errors or output.

You can solve this by adding the following line to the end of the PowerShell script, but that is not always a convenient option:

Read-Host -Prompt "Press Enter to exit"

Use Windows PowerShell

Personally, I prefer the start PowerShell scripts from the command line in Windows PowerShell itself. There are two ways to do this, you can first start PowerShell and navigate to the script or open PowerShell in the correct location from the explorer.

We start with the latter, opening the PowerShell in the correct location from the explorer. In the explorer, locate the script that you want to run, in this case, c:\temp\powershell.

  1. Right-click on the blank area in Explorer (not on the PowerShell file)
  2. Choose Open PowerShell window here
    (In Windows 11 you will need to select Open in Windows Terminal)

As you can see, PowerShell is started in the folder c:\temp\PowerShell. We can now run the script by simply typing the filename (type the first few letters and press Tab to autocomplete it)

execute powershell script

You can also first start Windows PowerShell:

  1. Right-click on the start menu (or press Windows key + X)
  2. Choose Windows PowerShell
  3. Navigate to the folder where the script is located
    cd c:\path\to\script <enter>
  4. Run the PowerShell script
    .\PowerShellExampleScript.ps1 <enter>

run powershell script from command line

Run PowerShell Script from CMD

If you have tried to run a PowerShell from cmd, then you might have noticed that it will just open the script in notepad. Not really the result we are looking for.

To run the PowerShell script, we need to tell the command prompt to open the script with PowerShell. We can use the following cmd for this:

PowerShell c:\path\to\script\PowerShellScript.ps1

run powershell script from cmd

Note that you will need to specify the full path to the PowerShell script. The result of the script is displayed in the command prompt.

If you want to keep the PowerShell session open, you can add the -noexit parameter to the command:

PowerShell -noexit c:\temp\PowerShell\PowerShellExampleScript.ps1

Using PowerShell ISE

When you download a script from the internet it’s always a good idea to review the script before you run it. An easy way to review and run a PowerShell script is to use the PowerShell ISE.

To open a PowerShell file in the editor, simply right-click it and choose Edit

When you use the editor for the first time you might need to expand the script pane first, to see the content of the PowerShell script:

To run a script in PowerShell ISE simply click on the green play button in the toolbar. The results of the scripts are displayed in the console:

Run PowerShell Script as Administrator

Some PowerShell scripts require administrator privilege to run correctly. They might need access to all folders on your system drive, or need to interact with other domain computers or servers.

The easiest way to run PowerShell scripts as an administrator is to start Windows PowerShell as administrator.

  1. Press Windows key + X (or right-click the start menu)
  2. Choose Windows PowerShell (admin)
  3. Click Yes on the User Account Security prompt

You can now run any PowerShell command or script with Administrator privilege. Simply navigate to the script (or even drag and drop the script) to run it.

You can also run a PowerShell script as administrator from the command line. When you have PowerShell open, we can start a new PowerShell process and run it as Administrator. Optionally we can even specify the file that we want to run:

# Open a new PowerShell windows with Administrator Privilege
Start-Process PowerShell -Verb runAs

# Run PowerShell script with Administrator Privilege
Start-Process PowerShell -Verb runAs -ArgumentList "-file c:\temp\powershell\powershellexamplescript.ps1"

Wrapping Up

I hope you were able to run your PowerShell script with the steps above. Make sure that you have set the Execution policy correctly before you run a PowerShell script.

If you have any questions, just drop a comment below. Make sure you also read more about setting up your PowerShell profile.

  • Run в windows 10 как вызвать
  • Rush royale скачать на пк windows
  • Running source 2 tools requires windows 10
  • Run old games on windows 10
  • Run windows terminal from cmd