Running a powershell script from the command line. Writing and running scripts in PowerShell

1. Writing a script

A PowerShell script (no matter what version) is a text file with a *.ps1 extension.

Here is an example of a simple Power Shell script (file systemInfo.ps1):

# Retrieve WMI object for the operating system

Get-WmiObject Win32_OperatingSystem

This file can be created and edited, for example, in FAR Manager.

Please notethat FAR Manager, although it can work in the Power Shell console, executes scripts from under itself in the environment of a regular Windows console cmd . That is, FAR Manager can only be used to create and edit PowerShell scripts, but not to run them. But before you get disappointed, read point 3.

2. Running the script

The script must be executed from the Power Shell console, and not from the regular Windows console. In the Power Shell console, you need to go to the directory where the script is located (with the commands CD ), and then run the script itself, making sure to include the characters in front of it".\" . For example, we have the path to the script file d:\work\systemInfo.ps1 . Then the launch commands will look like this:

cd\

cd work

.\systemInfo.ps1

or like this (just specify the full path to the script):

d:\work\systemInfo.ps1

Most likely, the following error will appear when running the script:

The file D:\work\systemInfo.ps1 cannot be loaded because script execution is not allowed on this system. Type "get-help about_signing" for more information.

line:1 character: 18

CategoryInfo: NotSpecified: (:), PSSecurityException

FullyQualifiedErrorId: RuntimeException

The error appears because by default Power Shell has the maximum security policy enabled, which allows you to run PowerShell commands on the command line, but does not allow you to run a script with PowerShell commands on the same command line.

To enable the execution of PowerShell scripts, you need to create a *.bat file, for example enableScript.bat with the following content:

powershell -Command Set-ExecutionPolicy RemoteSigned

This *.bat file can be executed in any console: either in PowerShell or in a regular console cmd . After executing this file, PowerShell scripts will run in the PowerShell console.

3. Running a PowerShell script from a regular Windows cmd console

The PowerShell script can also be executed from a regular Windows console. To do this you can use the command:

Powershell -File ./systemInfo.ps1

This way you can execute scripts directly from FAR Manager and they will work.

But there is a slight subtlety here. Parameter-File only fires on local paths, even if the path is relative"./" . That is, if *.ps1 - the file is on the local disk C: or D: , then such a call will work. But if you try to execute a script located on a domain resource, the script will not be found. Perhaps this will be fixed in future versions of PowerShell.

Running PowerShell scripts on a schedule

The tasks of almost any system administrator include writing various scripts and running them. Scheduling a script to run on a schedule using Task Sheduler is not a difficult task, but there are some nuances when using PowerShell, which I will discuss in this article.

So, let's say I have a script start.ps1 that I need to run every day for 10 days. There are two ways to solve this problem.

Method 1

To run the script, we will use the Task Scheduler snap-in, also known as the task scheduler. You can find it in the Administrative Tools section, or by clicking Win+R and entering the command taskschd.msc. Open the scheduler and in the Actions section select Create Task.

On the General tab, specify the name and description of the task, as well as (if necessary) the user under whose name the task will be launched. In order for the task to be executed regardless of whether the user is logged in to the system, select the “Run whether user is logged on or not” option. If an elevation of privileges is required to complete a task, then check the “Run with highest privileges” option.

Next, go to the Triggers tab and create a new trigger, which will store the launch schedule for our task. In the Start field we indicate the start date and time, and in the Expire field we indicate the date and time the task is completed. We indicate to perform the task daily (Daily) and set the repeat period (Recur every) to 1 day.

Note. If you want to run a task more often than once a day, then you need to select One time, and in the Advanced settings section, select the Repeat task every item and specify the repetition time, minimum 5 minutes, maximum 1 hour. If this is not enough, then you can additionally specify a time delay in the Delay task for up to field.

And the main thing. Go to the Action tab and specify the action for the scheduled task. Let me remind you that for PowerShell security reasons, scripts can only be executed interactively, that is, you must first launch the PowerShell shell and specify the path to the script in it. Therefore, in the “Action” field we indicate the launch of powershell.exe, and in the “Add Arguments” field the -File parameter and the path to our script, like this:

File ″C:\Scripts\start.ps1″

You can also specify in the arguments field:

Command - Executes the specified commands and any other parameters. This parameter can also be used to run a script, for example: -Command ″& (C:\Scripts\start.ps1)″. In addition, it can be used to pass parameters to the script: -Command ″& (C:\Scripts\start.ps1 -a 1 -b 3)″;
-ExecutionPolicy — sets the script execution policy for the current session, can take the values ​​Unrestricted, RemoteSigned, AllSigned and Restricted. The specified policy will be in effect only in the current session and takes precedence over any previously created policies;
-NonInteractive — disable the output of interactive requests to the user;
-WindowStyle Hidden - launch the PowerShell window in hidden mode, invisible to the user;
-NoProfile - prevents profile loading, which can speed up script execution somewhat;
-NoExit — leave the shell open after running the script. This may be needed when checking and debugging the script.

After filling out the required fields, click OK and save the task. Now the script will run on a schedule every day at the specified time for 10 days.

Method 2

PowerShell 3.0 introduced new Sheduled Job functionality, which makes it possible to create scheduled jobs directly from the console, without using the Scheduler snap-in. Let's use it for the scheduled launch of our script.

First, we create a launch schedule (daily at half past five in the evening, for 10 days):

$t = New-JobTrigger -Daily -At 4:30PM -DaysInterval 10

Then we save the credentials in a variable:

$cred = Get-Credential contoso\administrator

As an option, we specify running the task with elevated privileges:

$o = New-ScheduledJobOption -RunElevated

And register a task with the name Start:

Register-ScheduledJob -Name Start -FilePath C:\Scripts\start.ps1 -Trigger $t -Credential $cred -ScheduledJobOption $o

To make sure that the job has been created, you can open the scheduler and find our job in the Microsoft\Windows\PowerShell\SheduledJobs section.

Note. For each scheduled PowerShell job, a folder of the same name is created in the %systemdrive%\Users\%username%\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJobs directory. This folder contains the task itself in an XML file and the Output folder, in which, in subfolders by execution time, the task execution history is stored - the execution result (Result.xml file) and the task status (Status.xml). These files can be useful for debugging and diagnostics if the job does not work properly.

Execution Policy

In conclusion, let me remind you of one important point, namely the Execution Policy. You can view the current policy value using the Get-ExecutionPolicy command. Execution policy can have the following values:

Restricted - execution of any scripts is blocked. Default value;
AllSigned - execution of scripts with a digital signature is allowed;
RemoteSigned - scripts prepared on the local computer can be run without restrictions, scripts downloaded from the Internet - only with a digital signature;
Unrestricted - execution of any scripts is allowed. When running an unsigned script that was downloaded from the Internet, the program may require confirmation;
Bypass - nothing is blocked, no warnings or requests appear.

Usually, for trouble-free execution of scripts, it is enough to set the value to RemoteSigned. You can change the current value using the Set-ExecutionPolicy command, for example:

Set-ExecutionPolicy RemoteSigned -force

Note. If the execution policy specified in the command contradicts group policy, then the parameter will be written to the registry, but will not take effect.

Hi all! Today a short note on the topic, how to open powershell as administrator. Let me remind you that PowerShell is a powerful programming and administration language from Microsoft; every year it acquires an increasing number of cmdlets and functionality. Essentially, it is a replacement for the Windows Command Prompt. Below we will consider methods that allow you to open and configure it.
.

Methods for opening a PowerShell snap-in

Powershell is developing very well and with the release of Windows 10 it has already received version 5, but our topic is different. So how to open powershell? Everything is simple if in Windows XP, then nothing. Since it is delivered separately, in all subsequent releases it comes as a built-in component. The most universal way to open powershell is to click

Win+R and enter powershell

By pressing enter, the PowerShell console will launch, the only problem is that it will not open as administrator. And as a result, many commands will not be executed; below we will see how to do this on behalf of the administrator.

How to run windows powershell as administrator in Windows 8.1 and Windows 7

You can open Windows Powershell through Start. In Windows 8.1, Windows 2012 R2, go to System Tools - Windows and right-click and select Run as administrator.

In Windows 7 and Windows 2008 R2 it looks like this Start > Accessories > Windows PowerShell

You can also create a shortcut in the task item and right-click on it and select the appropriate item

It would be convenient if PowerShell always opened as administrator, let's implement it. This is done the same way in all versions of Windows. Opening the control panel

Right-click on it and select Properties. You can immediately see the path to the file where it is located in the system.

Click the "Advanced" button. You will see additional properties. where you need to check the box Run as administrator.

It's very simple. I am sure that now you will not have a question about how to open Windows Powershell. Another useful thing is to change the font in the powershell window.

How to Open PowerShell from the Start Button Context Menu in Windows 10

Microsoft is increasingly focusing on its powerful language (PowerShell) from the command line, and this is logical, since its capabilities for managing operating systems of the Windows family are almost limitless, if not more than in the graphical interface. Starting with version 1709 of Windows 10, in the context menu, PowerShell replaced the usual cmd. Right-click on the start button in Windows 10 and from the context menu, select the appropriate item:

  1. Windows PowerShell
  2. Windows PowerShell (administrator) is exactly the mode with maximum rights in Windows 10.

Launch Windows PowerShell using Search in Windows 10

In Windows 10 and older versions, you can find the PowerShell shell using a regular search; there is a special section for this. Click next to the Start button, the magnifying glass icon. In the search form that opens, enter the word PowerShell. You will search for all options, among which you will find the shell. If you right-click on it, you can open it as an administrator.

Launching Windows PowerShell from the Start menu in Windows 10

To open PowerShell from the Start menu, open it and find the Windows PowerShell item, it will be in the form of a folder, open it and run the appropriate version.

If you right-click, you can run the Vershel shell as an administrator with administrator rights.

Additional and generic shell launch methods

There are also very specific methods for opening a shell with a powerful language from Microsoft. The most clumsy one is to simply find the executable file and run it directly from its location on the system. Let's go to your Windows 10 along the following path:

C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell

As a result, you will see a folder with shortcuts that are present in the Start menu, you can launch them.

You can also run the original executable file, which is located along the path:

C:\Windows\System32\WindowsPowerShell\v1.0

And by right-clicking on it, you can download it as an administrator, with maximum rights.

You can also launch Windows PowerShell from the command line window; to do this, simply enter the magic word in it and press Enter.

Well, let me also remind you of the method for launching a new task from the “Task Manager” snap-in. Open "Task Manager", select menu item "File - Run new task"

In the window that appears, enter PowerShell.

Well, the last method known to me is to launch PowerShell through Windows 10 Explorer, to do this, open Explorer, select the menu item “File - launch Windows PowerShell”, there will be both modes.

What is PowerShell ISE

You've probably noticed that the PowerShell ISE shortcut is everywhere, and you'd like to know what it is. In a nutshell, this is a special shell in which you can write scripts and scripts in PowerShell, using all the variety of cmdlets that Microsoft offers you.

Powershell changing the font is very simple, go to the Font tab in the properties, where you can set the size from 5 to 72.

You can also get to properties from the utility window itself, click on the icon in the upper left corner and select properties

Here the font settings are slightly different, and as they change, the size of the console also changes.

On the Colors tab, you can set the font color in Powershell and the window itself. By making it black, for example, like the command line.

I also advise that if you are an active console user, set the buffer size not to 50 commands, but at least to 100.

Thank you for your attention. These are the methods for opening the Power Shell console in Windows. Site material

PowerShell is an alternative command line with extensive functionality. Many computer owners who are well versed in system processes are interested in the possibilities of using it on Windows 10 and previous versions of this software in order to change specific processes and PC settings for themselves.

There is nothing complicated about using PowerShell. Just follow all the instructions in this article and you will succeed.

If you are not an expert in this topic, you are just starting to study command lines and the actions that can be performed in them, it will be useful for you to know the answers to the main questions about using such an application. For example, how to run Windows PowerShell ISE Windows 10 and write and work with scripts.

How to open PowerShell?

This can be done in several of the following ways:

  • - you will find the application in the general list of components under the letter W.
  • Using search in the Taskbar - open it and enter the word PowerShell to search.
  • Using the “Run” menu, run it through the Win + R combination and write the name of the utility, after which it will be found in the system.
  • In Commander, set the PowerShell action - but you should know that you will be working with the application through an already running line, and not in a separate window.
  • In Windows Settings, select Taskbar Properties and Start Menu. In the “Navigation” tab, check the box next to “Replace the command line with PowerShell...”. Now you can enable the utility using the Win+X combination.

How to write and run scripts?

How to create a PowerShell script and run it? This can simply be done in a notepad - using it, indicate the commands you need in the new document. Then save it, but change the format to .ps1 - this is the extension that the files of this system utility have.

You can write scripts in the application itself like this:

  • Launch it.
  • Click on the “Create” item.
  • Or click on “File” and select “Create” from the list that appears.
  • Write all the commands that need to be executed, save the file.

Scripts can still be written and edited in FAR Manager, but they cannot be used directly in such an application, because it displays files of this type through the standard cmd line. However, other actions are performed in the same way as in the “native” utility.

You can run the script this way:

  1. Log into PowerShell as an administrator.
  2. Use the cd commands to specify the location of the required file. For example, e: cd\ cd work .\ filename. Ps1, or e: \work\filename.ps1
  3. In this case, e: is the name of the hard drive where the file is located.
  4. Press Enter.

The program will definitely show you a message with the text “The file ___ .Ps1 cannot be loaded because script execution is prohibited on this system...” when you run the command for the first time. The fact is that Windows is equipped with protection against interference thanks to the developers, so none of the users by default have access to perform such actions. But this limitation can be easily circumvented.

How? The text that appears with the error will recommend running the command get-help about_signing to get more information. You can follow these instructions, or use the Set-ExecutionPolicy remotesigned combination - after entering it, confirmation will be required, and the restriction will be removed.

Other questions about use

Many people have a question: how to find out the version of PowerShell? To do this, do the following:

  1. Enter $PSVersionTable.
  2. If this does not lead to anything, then you have version 1.0 - there is a $host.version command for it.
  3. Otherwise, detailed information will appear about which version of the application is installed on the PC.

Another question worth answering is how to remove PowerShell? This will require the following actions:

  • Go through the Control Panel to the Add/Remove Programs menu.
  • Find the Microsoft Windows branch
  • Uninstall the update for the WindowsPowerShell(TM) component and follow the system instructions.

Now you know everything about how to write and run PowerShell scripts, you can use this command line for many operations on the system. Additionally, you always have the opportunity to find out the version of this product and even partially remove it - due to the fact that it is installed along with system components, this will still not be possible to do completely. We only advise you to be careful when performing all such actions so as not to harm the computer as a whole.

Running a PowerShell script

This note describes how to configure the necessary parameters to launch PowerShell scripts. Most often on first start .ps1 scripts you see the following errors:

File unable to load. File does not have a digital signature. The script will not be executed on the system. For more information, enter the command "Get-Help about_signing".
The file cannot be loaded. The file is not digitally signed. The script will not execute on the system. Please see “Get-Help about_Signing” for more details.

Launch a program from an unreliable publisher? File published by CN= This publisher is not marked as trusted by this system. You should only run scripts from trusted publishers.
[V] Never run [D] Don't run [R] Run once [A] Always run [?] Help (default "D"):
Do you want to run software from this untrusted publisher? The file is published by CN= This publisher is not trusted on your system. Only run scripts from trusted publishers.
[V] Never run [D] Do not run [R] Run once [A] Always run [?] Help (default is “D”):

These errors and messages are caused by Windows execution policy settings PowerShell. However, you should not think that these parameters actually increase the security of the OS, because the code will still work if you copy it into the PowerShell console. Thus, security settings can be disabled - they only protect against accidental actions. Therefore usually this problem is solved by the team:

Set-ExecutionPolicy Unrestricted LocalMachine

Of course, this approach is not applicable in a corporate environment, so let’s look at this situation in more detail. You can view the current policy settings in all application areas by running the cmdlet Get-Executionpolicy with the list parameter.

get-executionpolicy -list

Scope ExecutionPolicy
—— —————
MachinePolicy Unrestricted
UserPolicy Undefined
Process RemoteSigned
CurrentUser AllSigned
LocalMachine Restricted

This policy can take 6 values:

Restricted(The policy is executed by default. For example, if all application areas are set to Undefined)
- Allows individual commands, but scripts cannot be executed.
- Prevents the execution of all script files, including format and configuration files (PS1XML), module script files (PSM1), and Windows PowerShell profiles (PS1).

AllSigned

- Requires all scripts and configuration files to be signed by a trusted publisher, including scripts prepared on the local computer.
- Warnings are issued before executing publisher scripts that have not yet been determined to be trusted.
— There is a risk of executing unsigned scripts from sources other than the Internet, as well as signed but malicious scripts.

RemoteSigned
— Execution of scripts is allowed.
- Requires scripts and configuration files downloaded from the Internet (including email and instant messaging programs) to be digitally signed by a trusted publisher.
— Does not require digital signatures for scripts executed and written on the local computer (not downloaded from the Internet).
— There is a risk of executing signed but malicious scripts.

Unrestricted
- Unsigned scripts can be executed. (There is a risk of executing malicious scripts.)
- Warns the user before executing scripts and configuration files downloaded from the Internet.

Bypass
— Nothing is blocked, and no warnings or requests appear.
- This execution policy is intended for configurations in which a Windows PowerShell script is embedded within a larger application, or for configurations in which Windows PowerShell is the platform for a program that has its own security model.

Undefined
— The current scope does not have an execution policy set.
- If the execution policy in all scopes is Undefined, the execution policy is Restricted, which is the default execution policy.

There are five areas where this policy and settings apply:

MachinePolicy And UserPolicy are set by AD policies or local policies of a given computer.
Process— scope of application: current session. The help says that its value is stored in the $PSExecutionPolicyPreference variable; however, it was not possible to obtain/change the value of this policy through the variable. Changes made to this application area will not affect other sessions.
CurrentUser— scope of the current user. Its value is stored in the registry key HKEY_CURRENT_USER (“HKEY_CURRENT_USER\Software\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell\ExecutionPolicy”).
LocalMachine— scope of application to all users of the current computer. It is stored in the registry key HKEY_LOCAL_MACHINE("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\ScriptedDiagnostics\ExecutionPolicy").

The team get-executionpolicy there is a -Scope parameter. Using this parameter, you can select the scope for which the policy value will be displayed.

Get-ExecutionPolicy -scope Process

Result of running the cmdlet: RemoteSigned

At the same time, Application Areas have priority, MachinePolicy has the highest priority, then UserPolicy, Process, CurrentUser and LocalMachine has the lowest priority.
Therefore in the example:

Scope ExecutionPolicy
—— —————
MachinePolicy Unrestricted
UserPolicy Undefined
Process RemoteSigned
CurrentUser AllSigned
LocalMachine Restricted

In the current session, the resulting policy will be Unrestricted.

In order to find out the value of the script execution policy for a given session, you need to use the Get-ExecutionPolicy cmdlet without parameters.

Conclusion: Unrestricted

Changing the script execution policy PowerShell:

To change the value of PowerShell script execution policies, there is the Set-ExecutionPolicy cmdlet.
This cmdlet has the following parameters:

-ExecutionPolicy
Indicates the value of the policy. Can have the following values: Restricted, AllSigned, RemoteSigned, Unrestricted, Bypass, Undefined. This parameter is required. If not specified, the comadlet will ask for values ​​at runtime.

Conclusion:
Specify values ​​for the following parameters:
ExecutionPolicy:

-Scope
Defines the scope of this policy. Can have the following values: LocalMachine, Process, CurrentUser. If the scope parameter is not specified, the default value is LocalMachine.

Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process

Set-ExecutionPolicy Unrestricted Process

-Force
With this parameter, the cmdlet will not require confirmation from the user. For example:

Set-ExecutionPolicy Unrestricted Process -Force

The cmdlet will not display anything and will apply the policy value.

-Confirm
If, on the contrary, one confirmation is not enough for you. You can specify the Confirm parameter and you will have another, additional, request to confirm your actions:

Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process -confirm

Execution result:

Confirmation
Are you sure you want to perform this action?
Performing a "Set-ExecutionPolicy" operation on the target object "Unrestricted".
[Y] Yes - Y [A] Yes for all - A [N] No - N [L] No for all - L [S] Suspend - S [?] Help (default value is "Y"):

Changing the Execution Policy
Execution policy protects your computer from untrusted scripts. Changing the execution policy may compromise system security, as described in the help topic for the about_Execution_Policies command. Do you want to change the execution policy?
[Y] Yes - Y [N] No - N [S] Suspend - S [?] Help (default value is "Y"):. exe -executionpolicy Unrestricted

Get-ExecutionPolicy -list

Execution result:

Scope ExecutionPolicy
—— —————
MachinePolicy Unrestricted
UserPolicy Undefined
Process RemoteSigned
CurrentUser AllSigned
LocalMachine Restricted

Changing script launch policy settings using group policies.

In group policy, the parameter that controls the launch of scripts is located along the path:

For MachinePolicy:

Computer Configuration/Policies/Administrative Templates/Windows Components/Windows PowerShell

Computer Configuration/Administrative Templates/Windows Components/Windows PowerShell

For UserPolicy:
User Configuration/Policies/Administrative Templates/Windows Components/Windows PowerShell

User Configuration/Administrative Templates/Windows Components/Windows PowerShell

The Execution Policy parameter can take 3 values.