How to Run a PowerShell Script From the Command Line and More

“… cannot be loaded because running scripts is disabled on this system”

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”.

Call or invoke a script to run it

The most common (default) way to run a script is by callingit:

PS C:> & “C:BatchMy first Script.ps1”

PS C:> & cscript /nologo “C:Batchanother.vbs”

If the path does not contain any spaces, then you can omit the quotes and the ‘&‘ operator

PS C:> C:BatchMyscript.ps1

If the script is in the current directory, you can omit the path but must instead explicitly indicate the current directory using . (or ./ will also work)

PS C:> .Myscript.ps1

An important caveat to the above is that the currently running script might not be located in the current directory.

Call one PowerShell script from another script saved in the same directory:

#Requires -Version 3.0
& “$PSScriptRootset-consolesize.ps1″ -height 25 -width 90

When you invoke a script using the syntax above, variables and functions defined in the script will disappear when the script ends.1

An alternative which allows running a script (or command) on local or remote computers is Invoke-Command

PS C:> invoke-command -filepath c:scriptstest.ps1 -computerName Server64

1unless they are explicitly defined as globals: Function SCOPE:GLOBAL or Filter SCOPE:GLOBAL or Set-Variable -scope “Global”

Changing the powershell execution policy

To change the execution policy:

Dot sourcing

When you dot sourcea script, all variables and functions defined in the script will persist even when the script ends.

Run a script by dot-sourcing it:

PS C:> . “C:BatchMy first Script.ps1”

Dot-sourcing a script in the current directory:

PS C:> . .Myscript.ps1″

Get output of cmd command from java code

I have a program where I was able to successfully execute cmd commands from my code, but I want to be able to get the output from the cmd command. How can I do that?

So far my code is:

public class Second {
    public static void main(String[] args) {
        System.out.println("Hello world from");


public class Main {
    public static void main(String[] args) {
        String filename = args[1].substring(0, args[1].length() - 5);
        String cmd1 = "javac "   args[1];
        String cmd2 = "java "   filename;

        Runtime r = Runtime.getRuntime();
        Process p = r.exec(cmd1); // i can verify this by being able to see Second.class and running it successfully
        p = r.exec(cmd2); // i need to see this output to see if 


I can check the first command is working successfully by checking for Second.class, but what if this class generated some error, how will I be able to see that error?

:/>  Что делать, если загрузка процессора на 100 процентов в Windows 10: решение проблемы

How do i get code 202 from a cmd file launched by task scheduler?

I don’t believe this is possible by default. The task itself completed successfully, in the sense that it ran at the scheduled time and launched whatever application(s) you wanted it to. The fact that one of the applications raised an error is none of the Task Scheduler’s concern.

However, I was able to achieve almost what you want: you can raise error 203 on one of the actions (not on the task itself) by making sure that the task cannot find the program it is supposed to run as part of the task.

So I created a Task that runs 3 actions:

  1. MyActualBatch.cmd
  2. MyExe.exe
  3. MyResult.cmd

The MyBatch.cmd file contains the following code:

@echo off
if exist MyExe.exe  del MyExe.exe
if exist result.cmd del result.cmd
set myError=0
:: *********** Do all your processing here **********
::    .....
::    Store your specific error code in %myError%, or to 0 to indicate success e.g.:
      set myError=399
::    .....
:: *********** End batch file with following lines **********
if /I %myError% EQU 0 (
   :: No error, so let's copy some small executable that the task can actually run
   :: without impacting the results of the task
   copy /y C:WindowsSystem32ipconfig.exe MyExe.exe > nul
:: Create a batch file that will instantly exit using the original error code
:: created in this one
echo exit /b %myError% > result.cmd
exit /b %myError%

(or, without the comments that clutter the display):

@echo off
if exist MyExe.exe  del MyExe.exe
if exist result.cmd del result.cmd
set myError=399
if /I %myError% EQU 0 (
   copy /y C:WindowsSystem32ipconfig.exe MyExe.exe > nul
echo exit /b %myError% > result.cmd
exit /b %myError%

Whenever your batch file needs to raise an error, you set the myError variable to the value you want to return (I prefer using my own variable rather than relying on the ERRORLEVEL system var, which can be reset by just about any action).

At the end of the script, some code checks if the myError var contains 0 (which means no error occurred). If it does, then the batch creates an executable file named MyExe.exe that the task will be able to run immediately after this batch file ends. But if myError contains a different error value, then the MyExe file will not be created, which will trigger a 203 error in the task when it attempts to run it next.

:/>  Одновременный вывод звука на 2 устройства с программой Realtek HD | Пикабу

Finally, a Result.cmd file is also created so it can be run as the last action by the task, bubbling up the error code you had created in the first task.

Note: the MyExe file is just a copy of IpConfig.exe. I picked that executable simply because AFAIK it’s available on all Windows versions, it’s small, and it just lists information so it can’t break anything by running as part of the task.

How to run a scheduled task in task scheduler through powers shell command

Any Powershell cmdlet to run scheduled task in task scheduler?

We have commands to Disable,Enable,Start,Stop the tasks in task schduler through powershell commands like below.But I didnt find any command to run a scheduled task which is in “Ready” state.Any idea?

Get-ScheduledTask -Taskpath "TasksFolder"|enable-ScheduledTask
Get-ScheduledTask -Taskpath "TasksFolder"|disble-ScheduledTask
Get-ScheduledTask -Taskpath "TasksFolder"|start-ScheduledTask
Get-ScheduledTask -Taskpath "TasksFolder"|stop-ScheduledTask

How to run powershell script from .ps1 file?

I’m trying to automate the execution of a simple PS script (to delete a certain .txt file). Obviously, I’m new to powershell 🙂
When I run the code in shell, it works flawless. But when i save the code as a .ps1 and double-click it (or execute it remotely), it just pops up a window and does nothing.

I’ve tried to save the code as a .bat file and execute it on Windows command line, but it behaves the same: Works by coding directly on prompt, but doesn’t Works by executing the .bat file.

$Excel = New-Object -ComObject Excel.Application
$Workbook = $Excel.Workbooks.Open('H:codestest1.xlsm')
$workSheet = $Workbook.Sheets.Item(2)
$str_name = $WorkSheet.Cells.Item(2,1).Text
Remove-Item -Path "H:text files$str_name.txt" -Force

I expected it to work by double-clicking it, just as it does by running in shell, or in the command line, but i can’t figure out why it doesn’t.


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.

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.


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.

:/>  Средство диагностики directx в Windows 10

Run a cmd batch file

Run a batch script from PowerShell:
PS C:> ./demo.cmd

Early versions of PowerShell would only run internal CMD commands if the batch file was run by explicitly calling the CMD.exe shell and passing the batch file name.

Run a single cmd internal command

This will run the CMD.exe version of DIR rather than the powershell DIR alias for Get-ChildItem:

PS C:> CMD.exe /C dir

Run a vbscript file

Run a vb script from PowerShell:
PS C:> cscript c:batchdemo.vbs

Running a 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"

Every PowerShell script should end with a .ps1 extension.

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.

Related: Back to Basics: Understanding PowerShell Objects

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...


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.

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.

2. Click on File → Open and find your script.

Оставьте комментарий