Powershell changing script execution policy. Writing and running scripts in PowerShell

There is always room for creativity in administration. Do you want to do some automation of a routine task? Please! Do you need to regularly check something for activity? No problem! Do you want to process some giant report and display only relevant data? That's possible too. All these and many other tasks are best solved using scripts, and PowerShell is the optimal choice in the case of Windows.

What is PowerShell and why is it good?

Users of UNIX and Linux, and at some point also macOS, are accustomed to always having Bash at hand - a slightly old-fashioned, but universal and powerful tool with which you can do amazing things with just a couple of lines. You register a new script in cron - and you’re done, it’s already running on your computer or server and quietly doing something useful.

Returning to Windows (and sometimes you can’t do without it), you understand that .bat scripts, although good, do not always save you: their capabilities are very limited. And if you still thought that PowerShell is an unknown thing for which you need to pick up and configure something, then don’t rush to conclusions - if you look at it, it’s not bad at all.

Windows PowerShell is an extensible open source automation tool that consists of a shell (command line) and a scripting language. It was first shown in 2003 (then called Monad). PowerShell 2.0 was released as part of Windows 7 and Windows Server 2008 R2 and has been present in Windows as a standard feature ever since. It was even included in Windows XP SP3. PowerShell is built on top of and integrated with the .NET Framework. PowerShell can access COM, WMI and ADSI, and of course also executes console commands.

In general, posh has strong ties to Microsoft products, be it Active Directory or postal Exchange server. This allows you to access them through the console and issue commands without connecting to the server equipment.

If you weren't interested in PowerShell before, then most likely you have the second version. I recommend upgrading to at least the third one - it contains much more features and useful tips. Without going into details, PowerShell 2.0 includes about a dozen modules and about 350 commands, and PowerShell 3.0 already has about 2,300 cmdlets from more than 70 modules. The “hacker” also wrote about how the newest PowerShell version 5 from Windows 10 differs.

Choosing a development environment and tools

Now let's figure out where it is most convenient to write code. You can, of course, also in Notepad, Notepad++ or Sublime. But this is in in this case Not the smartest editor's choice. It's best to start getting acquainted with PowerShell armed with the included .


This is not even an editor, but an almost full-fledged development environment. There is an IntelliSense feature that allows you to view a list of cmdlets and their parameters, variables, utilities, and more. Snippets are supported, it is possible to expand the set of functions through various add-ons. The Commands window is also very useful. In it you can compose commands in visual mode: you select a module, find the desired cmdlet and set the necessary parameters to it. The resulting command can be copied to the console or immediately executed. In general, a kind of designer for the admin. And of course, there is syntax highlighting, a debugger and much more.

However, PowerShell ISE also has worthy competitors. One of them - .

PowerGUI is a visual extension to PowerShell. It makes it easy to build your own scripts before choosing the cmdlets you need. You take what you need to solve the problem and drag and drop parts of the code until you get a script. One of the main features of PowerGUI is Power Packs, ready-made scripts published by the user community and made available for free access. There are simple commands like adding users, and complex ones - for example, managing switches and virtual machines. All of them can be easily supplemented and modified according to needs.


Sapien companies are a more advanced environment, which is designed for joint development of one project big amount participants. If you've ever worked with Visual Studio, I think you'll notice the similarities. Some useful features of PowerShell Studio include the Ribbon panel, support for remote debugging, and compiler features that allow you to include scripts in executable files. There is support different versions PowerShell.


The Script Browser for Windows PowerShell ISE is also worth mentioning. This is not a development environment, but a very interesting tool developed by Microsoft. Script Browser provides access to a database of ready-made scripts that can be used as samples for writing your own code. This thing can also analyze the code you write and suggest how to improve it.


Some useful tricks

Having figured out the editor, you can start writing code. PowerShell is not a complicated language, and I think you'll get the hang of it quickly. The commands here are called cmdlets, and each of them consists of two parts. First comes the action, for example Get, Set, Add, Invoke, Remove. Then it indicates what the action is aimed at: Service, VM, AzureAccount, DHCPServerSetting. Each part is separated from the other by a hyphen. It turns out, for example, get-process. This, by the way, useful command, which displays a list of processes. Let's say, if you write

get - process BadTh *

we will see something like this:

Handles NPM (K ) PM (K ) WS (K ) VM (M ) CPU (s ) Id ProcessName

------------------------

28 4 - 210844 - 201128 - 163 25.67 2792 BadThread

Now you can terminate the frozen process:

You can view it recursively, albeit with a little more complex logic:

You can also do

By the way, for each field in the options window account or a computer you can access and read the data. This way you can make entire sections. Here, for example, is a query based on data about telephone numbers:

Get - AdUser - Filter * - Properties OfficePhone | FT OfficePhone, UserPrincipalName

PowerShell vs bat

Sometimes a problem can be solved either using the old fashioned method or using PowerShell. I recommend not to be lazy and use PS, if only simply because this way you will learn it faster and will be able to use it in more complex situations. In addition, you will gradually appreciate its syntax - more elegant and consistent. Here are some examples of how things have been done before and how they can be done using PowerShell.

The following command line will reboot the computer with a delay of ten seconds:

This is how you can restart the dnscache service (or any other) via bat:

sc stop dnscache

sc start dnscache

Running a PowerShell script

This note is dedicated to describing the settings required parameters for start PowerShell scripts. Most often on first start .ps1 scripts you see 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 policy settings Windows execution 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 that all scripts and configuration files be signed by a trusted publisher, including scripts prepared in 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 to be digitally signed by a trusted publisher (including email and instant messaging programs).
— 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 Windows script PowerShell is embedded within a larger application, or for configurations where Windows PowerShell is the platform for the program, which 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 politicians of this 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

In this case, Areas of Application 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 required to be specified. 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.

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 this software to change specific processes and PC settings for yourself.

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 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 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 very easily circumvented.

How? The text that appears with the error will recommend that you enter 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 it will appear detailed information about what 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, it will still not be possible to do this completely. We only advise you to be careful when performing all such actions so as not to harm the computer as a whole.

Running PowerShell scripts on a schedule

The tasks of almost anyone system administrator includes 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 - launches a 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 conflicts group policy, then the parameter will be written to the registry, but will not have any effect.

Default script execution Windows PowerShell prohibited in the system. For security reasons, all PowerShell scripts must be digitally signed. this method called - execution policy. If the script does not meet this condition, then execution PowerShell scripts prohibited in the system. This is primarily due to the fact that the script may contain malicious code that can harm the operating system.


PowerShell has several execution modes that determine what type of code is allowed to run. There are 5 different execution modes:

Restricted
Default value. The execution of any scripts is blocked and the operation of interactive commands is allowed.
All Signed
Execution of scripts that have a digital signature is allowed.
Remote Signed
Local scripts work without a signature. All downloaded scripts must be digitally signed.
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.

The default mode for PowerShell is "Limited". In this mode, PowerShell runs as an interactive shell. If you have not configured PowerShell before, then instead of the script running, you will see an error message written in red font as in the screenshot below.

The safest way to solve this problem is to change the execution policy to unrestricted, run the script, and then change back to the restricted policy.

To change the execution policy to unlimited, use the PowerShell console with Administrator rights and run the following command:

Y (Yes)

Now you can run the script. However, you are exposing the system to serious risk, so when the script is finished running, be sure to set the execution policy back to restricted mode. You can do this using the following command:

After running the command, you will be asked to confirm the execution policy change. We will answer Y (Yes)

The execution of any scripts is blocked. Default value.

Set-ExecutionPolicy Restricted

Execution of scripts that have a digital signature is allowed.

Scripts prepared on the local computer can be run without restrictions, scripts downloaded from the Internet - only if they have a digital signature.

Set-ExecutionPolicy RemoteSigned

Execution of any scripts is allowed. When running an unsigned script that was downloaded from the Internet, the program may require confirmation.

Set-ExecutionPolicy Unrestricted

Nothing is blocked, no warnings or requests appear.

To run the above commands without confirming the change, use the option
-Force , for example run the command:

Set-ExecutionPolicy Bypass -Force

Now, when executing commands, you do not need to confirm the changes made.