Scripting is disabled on this system. Writing and running scripts in PowerShell


Hello everyone, today I want to tell you how to run a PowerShell script in Windows. Imagine a situation: you wrote a script that greatly simplifies the display of information on Active Directory, you open the Powershell snap-in, enter the path to your script, press enter and get an error.

Can't download file<путь к вашему файлу>, since script execution is prohibited for this system. Type "get-help about_signing" for more information.

Let's see how to solve it.

PowerShell has a number of execution modes that determine what type of code is allowed to run. This is all controlled by a registry key that lives in HKLM. There are 4 different execution modes:

Limited(Restricted): The default execution policy does not allow scripts to run and only allows interactive commands to run.

All signed(All Signed): Allows all scripts to run. True, all scripts and configuration files must be signed by a publisher you trust; this mode exposes you to the risk of running signed (but malicious) scripts after receiving confirmation of trust in the publisher.

Deleted signed(Remote Signed): Local scripts work without a signature. All downloaded scripts must be digitally signed.

Unlimited(Unrestricted): All scripts and configuration files obtained from communication applications, like Microsoft Outlook, Internet Explorer, Outlook Express and Windows Messenger work after confirming that you understand that the file comes from the Internet; no digital signatures are required; This mode exposes you to the risk of running unsigned, malicious scripts.

By default, PowerShell uses Restricted mode. In this mode, PowerShell works only as an interactive shell. It does not allow scripts to run, and only loads configuration files that are signed by a publisher you trust.

Allow powershell scripts to run

To run scripts you create yourself, you must allow untrusted scripts to run using the command Set-ExecutionPolicy remotesigned and confirmation (Attention!!! To run this command, you must run PowerShell with administrator rights). After this, you can run the script again.

When asked, press Y to allow script execution. After these manipulations, you will be able to run your script.

More than one year has passed since Windows release 7 and Server 2008.

Programmers, system administrators and advanced users have found many uses for the blue window, similar to the command line.

Most novice users don’t even know what PowerShell (PS) is.

But scripts for PowerShell allow you to automate almost 100% of the actions and scripts performed in the operating system via the command line and GUI.

Let's get acquainted with the main capabilities of this program, paying more attention to the function of creating and running scripts (firmware).

There are countless manuals and documentation for the program, including in Russian. Purpose of the article– provide the user with conceptual knowledge, bring up to date, but whether it’s worth getting to know the interpreter and the execution of scripts in it more closely, everyone will decide for themselves.

What is Windows PowerShell?

PowerShell– an interpreter based on the .NET Framework, equipped with its own scripting language.

The first means that it works in text mode: you enter a command, run it, and on the screen you see the result of its execution.

As it was in MS-DOS and older versions of UNIX.

The second significantly simplifies, speeds up and automates the administration and maintenance of systems, applications, processes and related services by administrators and ordinary users.

Compared to other interpreters, PS is different:

  • integration with – allows you to create powerful scripts by introducing into them program code;
  • all returned data are objects, not text/string data, which means they are passed on to other scripts and processed in any way.

PowerShell version 2 has the following capabilities, Let's look at some of them in more detail:

  • Ability to represent commands as cmdlets– they are launched inside the interpreter; otherwise, the command is executed in a separate process.
  • Using Conveyors– are designed to transfer data from one command to another while maintaining their structure and type.
  • Integrated multi-stream data transfer over the network with prioritization and connection resumption.
  • Support for positional and named parameters.
  • Background work – asynchronous calling of commands and running scripts on remote machines.
  • Setting up limited sessions with remote clients and running scripts on them.
  • Modules– a way of organizing scripts when they become self-sufficient and executed in their own container without affecting the module’s environment.
  • Availability of an error handler.
  • Graphical environment for the language: syntax, debugger, highlighting, automatic command completion with support for Unicode and bookmarks.
  • Adding breakpoints to lines, commands, operations and variables for debugging the script.
  • Block and interlinear comments.
  • Support for creating aliases for some cmdlets, which are converted into ordinary commands at the time of execution.
  • Creating limited sessions, where you can execute a strictly defined list of commands and much more.

PowerShell source code made available to everyone: Any community member can freely create their own extensions to increase the functionality of the command line interpreter.

Start mastering the integrated scripting language, without having programming skills, it is possible.

It is unlikely that you will be able to create a complex scenario, but almost everyone will be able to perform sequences of primitive actions.

Although, without knowledge of the basic concepts of PowerShell, it is unlikely that you will be able to do anything in the command interpreter window. Let's start with them.

Cmdlets

Cmdlets– peculiar PS commands behind which hide the most different functions. The commands built into the interpreter are implemented on the verb-noun principle, for example, Get-Process (getting a list of processes). This solution allows you to understand the essence of the command already from its name (on English language).

Some cmdlets support receiving/transferring data and arrays of information while preserving their structure and type. This works on the principle of a conveyor (this will be discussed in the next section). Regardless, the cmdlets run and process the objects in order.

To implement cmdlets, any supported .NET APIs created in any .NET language can be used.

Thus, the user is given access to specific functions of the program.

Cmdlets are able to gain access to the required information directly or through unique paths (drive letters and directory paths).

Using cmdlets you can work with objects file system and certificate stores, installed applications and services.

Conveyor

When creating not very primitive scripts or to perform any operations with data obtained as a result of the script, sometimes you also have to perform some actions.

There is a conveyor for this. As in UNIX, it combines commands by passing the output of one cmdlet into the input of another, unchanged, preserving its type.

In this case, no container or character-by-character parsing of information is required.

Part transmitted information function may also be included. After finishing the work of the combined commands, the function of converting information into text form (converting data to strings) is called using text formatting.

Scripts

Despite the fact that the shell allows you to automate many actions, you need to enter commands manually, which is not very convenient.

Especially when the same operations must be performed over and over again.

And you can’t do without the human factor: typos, errors, accidentally hitting keys when writing lines of code, correcting or retyping a line requires a more user-friendly attitude.

To perform monotonous chains of actions in PS, scripts are implemented - text files with a sequence of commands inside that are understandable to the interpreter.

Scripts in PowerShell will further simplify and automate the work on the PC and its maintenance, especially if the script contains branches, conditions, logical operations and cycles.

But here “all that glitters is not gold”: writing your own script or uploading a ready-made one (albeit slightly tailoring it to your own goals) will not work out that easily.

If inMicrosoftit was allowed no matter how much trouble made scripts forPowerShell , written by scammers and ill-wishers for selfish or hooligan purposes.

To run on Windows PS, you must pass its launch control.

If it fails, and the script must be executed, you will have to change the configuration of the objects responsible for the security of macros.

Before using scripts

When using VBS, many problems arise, which the PowerShell developers got rid of completely if script security is not lowered to satisfy user script requests or solve problems related to the level of security operating system.

Running a downloaded script on a user's machine is a simple and effective option for spreading malware. software or theft personal information by intruders.

Everything happens due to basic ignorance of the contents of the script file (ps1) and the desire to quickly solve their problems at the expense of the work of others. Objects that control the security level of script execution create an environment in which it is impossible to run the script.

Intentional running of macros occurs after changing the security level, if the user gives the go-ahead, realizing what he is doing, and knowing for sure what is in the *.ps1 file.

Because security configuration is inconvenient for people who need to implement and run their own scripts, it is possible to change the configuration.

Here you can either reduce protection to a minimum or wisely maneuver between the ability to open holes for penetration and ease of working with PowerShell.

The shell has three levels of security:

  • files with the ps1 extension are not identified by the system as executable and are designated as unknown or text (by double click open in the computer's default text editor);
  • The shell allows you to execute scripts after specifying their full path, script files in the current directory are not searched, making it impossible to execute macros located in the current directory;
  • running the built-in Execution Policy script, responsible for adding the required one to the list of allowed scripts.

Don't even think about changing the configuration, lowering it to at least the second level, without familiarizing yourself with the basicsPowerShelluntil you begin to at least superficially understand the contents of *.ps1.

There is also the concept of an execution policy, created to prevent scripts from being accidentally executed. There are five launch policy settings:

  • limited – installed by default, only scripts signed by Microsoft are executed, allowing you to obtain information about hardware and shell computer;
  • having a signature deleted files – you can execute all macros, but files sent by mail must be signed;
  • digitally signed by a trusted source– all signed scripts are executed;
  • unlimited– launch any macros;
  • bypass– intended for programmers who create own system security rather than using the one provided in the shell.

You can check the current state of the execution policy using the “Get-ExecutionPolicy” command.Whatever the security policy, the user will not be able to run a script that contains commands that he does not have enough privileges to execute.

Launching PowerShell

It's time to move from theory to practice. So, to execute scripts you need to obtain a digital signature or (the second option is simpler).

There are several ways to open a PowerShell window.

It is presented in two forms:

  • classic console;

  • PowerShell ISE – adds support for tabs, syntax, contextual help, contextual and main menus, which greatly facilitates work in the interpreter.

Start

The easiest way to call PS is through Start.

  1. Open the menu(in Windows 7, click “All Programs”).
  2. Let's go to Windows directory PowerShell and click on the desired icon.

Rice. 6 – Launch PS through the “Run” dialog

Win+X

In Windows 10, PS can be called up from the WinX menu. The fact is that by default by clicking on the command "Command line" open CMD. It can be replaced with PowerShell.

Open the “Properties” of the Taskbar, in the “Navigation” tab, put a checkmark next to the only option and save the settings.

You can call PowerShell via command line, writing “powershell” in it or running executable file along the path: %WINDIR%\ System32\ WindowsPowerShell\v1.0 for 32-bit systems and at %WINDIR%\ syswow64\ WindowsPowerShell\v1.0 for 64-bit Windows any editors.

Rice. 8 – Run PS from the directory where its executable file is stored

Most existing answers explain the How, but very few explain the Why. And before you start executing code from strangers on the Internet, especially code that disables security measures, you need to understand exactly what you're doing. So here's a little more detail about this problem.

Politicians Windows execution PowerShell allows you to define the conditions under which Windows PowerShell loads configuration files and runs scripts.

Benefits that are listed in PowerShell Basics - Execution Policy and Code Signing:

  • Execution control. Manage the trust level for script execution.
  • Command Highjack. Preventing commands from being entered my way.
  • Identification. Is the script created and signed by a developer I trust and/or signed with a certificate from a certificate authority I trust.
  • Integrity. Scripts cannot be changed malware or malicious users.

To check the current execution policy, you can run Get-ExecutionPolicy. But you're probably here because you want to change it.

To do this, you'll run the Set-ExecutionPolicy cmdlet.

When updating your execution policy, you have two important decisions to make.

Execution Policy Type:

  • Restricted† - No script can be run on the system by a local, remote or downloaded file.
  • AllSigned. All running scripts require a digital signature.
  • RemoteSigned- All remote scripts(UNC) or downloads must be signed.
  • Unrestricted- no signature required for any type of script.

Scope of the new change

  • LocalMachine† - The execution policy affects all users of the computer.
  • CurrentUser. The execution policy affects only the current user.
  • Process. The execution policy only affects the current Windows process PowerShell.

† = Default value

For example: If you want to change the policy to RemoteSigned for CurrentUser only, you would run the following command:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

Note. To change the execution policy you must run PowerShell As Administrator. If you are in normal mode and try to change the execution policy, you will get the following error:

Access to the registry key "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell" is denied. To change the execution policy for the default scope (LocalMachine), start Windows PowerShell with the Run as administrator option.

If you want to tighten the internal restrictions on your own scripts that have not been downloaded from the Internet (or at least, do not contain UNC metadata), you can force the policy to run signed scripts. To sign your own scripts, you can follow the instructions in Scott Hanselman's article Sign PowerShell Scripts.

Note. Most people may get this error when they open Powershell because the first thing PS tries to do when it starts is to run its user profile script, which sets up your environment, but you like it.

The file is usually located in the folder

%UserProfile%\My Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1

You can find the exact location by running powershell variable

$profile

If there's nothing in the profile you care about and don't want to worry about your security settings, you can simply delete it and powershell won't find anything it can't do.

There are a few in various ways running the script, below are the main ones:

  1. Launch PowerShell and run the script in it (enter the path to the file and the file name, for example, like this: C:\Scripts\test.ps1, or go to the script folder with the command cd C:\Scripts and run it with the command.\test.ps1) The shell can be found and launched in many ways. One way is through the Start menu. For Windows 7 - you need to go to "All Programs" - "Accessories" - "Windows PowerShell" and launch the "Windows PowerShell" shell. For Windows 10 - you need to find the group with the letter "W" and in it you will find "Windows PowerShell".
  2. Launch "Integrated Environment" Windows scripts PowerShell ISE" - this is a program - a development environment that allows you to edit and debug PowerShell scripts, which is also available by default along with PowerShell itself. Having launched it, you just need to click the "Open" button or go to the File menu - Open and select required script, then press F5 or the "Run Script" button. You can find Windows PowerShell ISE in the same place as PowerShell - in the Start menu.
  3. Launch standard command line and write in it:
    powershell -file<имя_скрипта> (example: powershell -file myscript.ps1)

If you haven't run PowerShell scripts before, you'll likely receive the following message: Can't download file<имя_скрипта>, since script execution is prohibited for this system. Type "get-help about_signing" for more information. This is due to the fact that for security reasons and to prevent accidental execution malicious code, all scripts must be digitally signed.

How to allow execution of an unsigned PowerShell script?

1. In PowerShell, before running the script, run the command to allow execution of unsigned scripts for the current shell session:

Set-ExecutionPolicy RemoteSigned -Scope Process

2. At startup from the standard command line use the -executionpolicy parameter, i.e. run the script like this:

<имя_скрипта>

Both methods set the policy only for the current session, while the security policy for executing PowerShell scripts written in the registry will not be changed and will remain the same. If you want to change the script execution security policy to “permanent”, then use this method:

3. Allow launch forever: Launch PowerShell as Administrator, then run the command:

Set-ExecutionPolicy RemoteSigned

Note: If the script was downloaded from the Internet, then to avoid a request for confirmation of launch, you need to use Bypass instead of RemoteSigned - complete shutdown any requests and warnings.

How to run a PowerShell script in the background?

To do this, just use the launch parameter -WindowStyle, which can take the following values: Normal, Minimized, Maximized and Hidden. So, to run an unsigned script in background, you need to run the command:

powershell -executionpolicy RemoteSigned -WindowStyle Hidden -file<имя_скрипта>

You can also add -NonInteractive if you wish, so that the script does not ask any questions. Thus, the script will be executed unnoticed by the user. Be careful when using this method.

Running a PowerShell script with parameters

The actual launch should be done as if you were launching regular program or bat file with parameters. For example, to run a script with parameters from the command line, you can write the following command:

powershell -executionpolicy RemoteSigned -file<имя_скрипта>param1 param2 "another text parameter"

In the script itself you can get these parameters like this:

Param ($var1, $var2, $var3) echo $var1, $var2, $var3

In PowerShell ISE, you can run a script with parameters in the same way using the command pane.

How to run a PowerShell script using a shortcut?

This task can be accomplished in two ways:

  1. Create a bat/cmd file in which to write a command to run the script (you have read the parameters above)
  2. Create a shortcut to PowerShell, which can be found in the c:\Windows\System32\WindowsPowerShell\v folder<версия>\ and in the shortcut properties in the "Object" field, add the necessary parameters.

Thus, for example, to run a powershell script when the user logs in, you can simply create a shortcut as described in point 2 and place it in startup. Also, creating a shortcut using one of the methods above will allow you to easily run the script as an administrator or as any other user as a regular program.

PowerShell scripting language - quite powerful tool for solutions various tasks, but it can be used not only for good things, but also for harm, so use it wisely;)

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. To obtain additional 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 decide as a 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 profiles PowerShell (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 presence 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- application area 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 for all users 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 resulting policy will have the value 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.







2024 gtavrl.ru.