How to run powershell script
How to run powershell script
How to Write and Run Scripts in the Windows PowerShell ISE
This article describes how to create, edit, run, and save scripts in the Script Pane.
How to create and run scripts
The Windows PowerShell execution policy determines whether you can run scripts and load Windows PowerShell profiles and configuration files. The default execution policy, Restricted, prevents all scripts from running, and prevents loading profiles. To change the execution policy to allow profiles to load and be used, see Set-ExecutionPolicy and about_Signing.
To create a new script file
To open an existing script
On the toolbar, click Open, or on the File menu, click Open. In the Open dialog box, select the file you want to open. The opened file appears in a new tab.
To close a script tab
Click the Close icon (X) of the file tab you want to close or select the File menu and click Close.
If the file has been altered since it was last saved, you’re prompted to save or discard it.
To display the file path
On the file tab, point to the file name. The fully qualified path to the script file appears in a tooltip.
To run a script
On the toolbar, click Run Script, or on the File menu, click Run.
To run a portion of a script
To stop a running script
There are several ways to stop a running script.
Pressing CTRL + C also works unless some text is currently selected, in which case CTRL + C maps to the copy function for the selected text.
How to write and edit text in the Script Pane
You can copy, cut, paste, find, and replace text in the Script Pane. You can also undo and redo the last action you just performed. The keyboard shortcuts for these actions are the same shortcuts used for all Windows applications.
To enter text in the Script Pane
To find text in the Script Pane
To find and replace text in the Script Pane
To go to a particular line of text in the Script Pane
In the Script Pane, press CTRL + G or, on the Edit menu, click Go to Line.
Enter a line number.
To copy text in the Script Pane
In the Script Pane, select the text that you want to copy.
Press CTRL + C or, on the toolbar, click the Copy icon, or on the Edit menu, click Copy.
To cut text in the Script Pane
To paste text into the Script Pane
Press CTRL + V or, on the toolbar, click the Paste icon, or on the Edit menu, click Paste.
To undo an action in the Script Pane
Press CTRL + Z or, on the toolbar, click the Undo icon, or on the Edit menu, click Undo.
To redo an action in the Script Pane
Press CTRL + Y or, on the toolbar, click the Redo icon, or on the Edit menu, click Redo.
How to save a script
An asterisk appears next to the script name to mark a file that hasn’t been saved since it was changed. The asterisk disappears when the file is saved.
To save a script
Press CTRL + S or, on the toolbar, click the Save icon, or on the File menu, click Save.
To save and name a script
To save a script in ASCII encoding
The following command saves a new script as MyScript.ps1 with ASCII encoding.
The following command replaces the current script file with a file with the same name, but with ASCII encoding.
The following command gets the encoding of the current file.
Windows PowerShell ISE supports the following encoding options: ASCII, BigEndianUnicode, Unicode, UTF32, UTF7, UTF8, and Default. The value of the Default option varies with the system.
Windows PowerShell ISE doesn’t change the encoding of script files when you use the Save or Save As commands.
about_Scripts
Short description
Describes how to run and write scripts in PowerShell.
Long description
Running a script is a lot like running a cmdlet. You type the path and file name of the script and use parameters to submit data and set options. You can run scripts on your computer or in a remote session on a different computer.
Writing a script saves a command for later use and makes it easy to share with others. Most importantly, it lets you run the commands simply by typing the script path and the filename. Scripts can be as simple as a single command in a file or as extensive as a complex program.
Scripts have additional features, such as the #Requires special comment, the use of parameters, support for data sections, and digital signing for security. You can also write Help topics for scripts and for any functions in the script.
How to run a script
Before you can run a script on Windows, you need to change the default PowerShell execution policy. Execution policy does not apply to PowerShell running on non-Windows platforms.
The execution policy is saved in the registry, so you need to change it only once on each computer.
To change the execution policy, use the following procedure.
At the command prompt, type:
The change is effective immediately.
To run a script, type the full name and the full path to the script file.
For example, to run the Get-ServiceLog.ps1 script in the C:\Scripts directory, type:
For example, to run the ServicesLog.ps1 script in the local directory, type:
If the script has parameters, type the parameters and parameter values after the script filename.
For example, the following command uses the ServiceName parameter of the Get-ServiceLog script to request a log of WinRM service activity.
As a security feature, PowerShell does not run scripts when you double-click the script icon in File Explorer or when you type the script name without a full path, even when the script is in the current directory. For more information about running commands and scripts in PowerShell, see about_Command_Precedence.
Run with PowerShell
Beginning in PowerShell 3.0, you can run scripts from File Explorer.
To use the «Run with PowerShell» feature:
Run File Explorer, right-click the script filename and then select «Run with PowerShell».
The «Run with PowerShell» feature is designed to run scripts that do not have required parameters and do not return output to the command prompt.
Running scripts on other computers
To run a script on one or more remote computers, use the FilePath parameter of the Invoke-Command cmdlet.
Enter the path and filename of the script as the value of the FilePath parameter. The script must reside on the local computer or in a directory that the local computer can access.
The following command runs the Get-ServiceLog.ps1 script on the remote computers named Server01 and Server02.
Get help for scripts
The Get-Help cmdlet gets the help topics for scripts as well as for cmdlets and other types of commands. To get the help topic for a script, type Get-Help followed by the path and filename of the script. If the script path is in your Path environment variable, you can omit the path.
For example, to get help for the ServicesLog.ps1 script, type:
How to write a script
A script can contain any valid PowerShell commands, including single commands, commands that use the pipeline, functions, and control structures such as If statements and For loops.
The following example is a simple script that gets the services that are running on the current system and saves them to a log file. The log filename is created from the current date.
Parameters in scripts
To define parameters in a script, use a Param statement. The Param statement must be the first statement in a script, except for comments and any #Require statements.
Script parameters work like function parameters. The parameter values are available to all of the commands in the script. All of the features of function parameters, including the Parameter attribute and its named arguments, are also valid in scripts.
When running the script, script users type the parameters after the script name.
The following example shows a Test-Remote.ps1 script that has a ComputerName parameter. Both of the script functions can access the ComputerName parameter value.
To run this script, type the parameter name after the script name. For example:
For more information about the Param statement and the function parameters, see about_Functions and about_Functions_Advanced_Parameters.
Writing help for scripts
You can write a help topic for a script by using either of the two following methods:
Comment-Based Help for Scripts
Create a Help topic by using special keywords in the comments. To create comment-based Help for a script, the comments must be placed at the beginning or end of the script file. For more information about comment-based Help, see about_Comment_Based_Help.
XML-Based Help for Scripts
Create an XML-based Help topic, such as the type that is typically created for cmdlets. XML-based Help is required if you are translating Help topics into multiple languages.
Returning an exit value
On Windows, any number between [int]::MinValue and [int]::MaxValue is allowed.
Script scope and dot sourcing
Each script runs in its own scope. The functions, variables, aliases, and drives that are created in the script exist only in the script scope. You cannot access these items or their values in the scope in which the script runs.
To run a script in a different scope, you can specify a scope, such as Global or Local, or you can dot source the script.
The dot sourcing feature lets you run a script in the current scope instead of in the script scope. When you run a script that is dot sourced, the commands in the script run as though you had typed them at the command prompt. The functions, variables, aliases, and drives that the script creates are created in the scope in which you are working. After the script runs, you can use the created items and access their values in your session.
To dot source a script, type a dot (.) and a space before the script path.
After the UtilityFunctions.ps1 script runs, the functions and variables that the script creates are added to the current scope.
For more information about scope, see about_Scopes.
Scripts in modules
A module is a set of related PowerShell resources that can be distributed as a unit. You can use modules to organize your scripts, functions, and other resources. You can also use modules to distribute your code to others, and to get code from trusted sources.
For more information about modules, see about_Modules.
Other script features
PowerShell has many useful features that you can use in scripts.
PSCommandPath contains the full path and name of the script that called or invoked the current script.
PSScriptRoot contains the directory of the script that called or invoked the current script.
Написание и запуск сценариев в интегрированной среде сценариев Windows PowerShell
В этой статье описано как создавать, редактировать, выполнять и сохранять скрипты в области скриптов.
Создание и выполнение сценариев
Политика выполнения Windows PowerShell определяет, можно ли выполнять сценарии, загружать профили Windows PowerShell и файлы конфигурации. Политика выполнения по умолчанию, Restricted, запрещает выполнение сценариев и блокирует загрузку профилей. Чтобы изменить эту политику выполнения и разрешить загрузку и использование профилей, см. описание Set-ExecutionPolicy и about_Signing.
Создание файла сценария
Открытие существующего сценария
Нажмите кнопку Открыть. на панели инструментов или откройте меню Файл и выберите пункт Открыть. В диалоговом окне Открыть выберите файл, который требуется открыть. Открытый файл появится в новой вкладке.
Закрытие вкладки сценария
На вкладке файла, которую нужно закрыть, щелкните значок закрытия (X) или откройте меню File (Файл) и выберите Close (Закрыть).
Если файл был изменен с момента последнего сохранения, будет предложено сохранить или отменить изменения.
Отображение пути к файлу
На вкладке файла наведите курсор на его имя. Появится подсказка с полным путем к файлу сценария.
Запуск сценария
Нажмите кнопку Выполнить сценарий на панели инструментов или откройте меню Файл и выберите пункт Выполнить.
Выполнение части сценария
Остановка выполняемого сценария
Есть несколько способов остановить выполняемый скрипт.
Нажатие клавиш CTRL + C также сработает, если нет выделенного текста. В противном случае нажатие клавиш CTRL + C приведет к копированию выделенного текста.
Написание и редактирование текста в области сценариев
В области скриптов текст можно копировать, вырезать, вставлять, искать и заменять. Также можно отменить и повторить последнее выполненное действие. Для этого используются те же клавиши, как и во всех других приложениях Windows.
Ввод текста в области сценариев
Поиск текста в области сценариев
Поиск и замена текста в области сценариев
Переход к определенной строке текста в области сценариев
В области сценариев нажмите клавиши CTRL + G или выберите Go to Line (Перейти к строке) в меню Edit (Правка).
Введите номер строки.
Копирование текста в области сценариев
В области сценариев выделите текст, который требуется скопировать.
Вырезание текста в области сценариев
Вставка текста в области сценариев
Отмена действия в области сценариев
Повторное выполнение действия в области сценариев
Сохранение сценария
Звездочка рядом с именем скрипта обозначает, что файл не был сохранен после изменения. После сохранения звездочка исчезает.
Сохранение сценария
Сохранение сценария с определенным именем
Сохранение сценария в кодировке ASCII
Следующая команда сохраняет новый сценарий в кодировке ASCII и с именем MyScript.ps1:
Следующая команда заменяет текущий файл сценария на файл с таким же именем, но в кодировке ASCII:
Следующая команда возвращает кодировку текущего файла:
Интегрированная среда скриптов Windows PowerShell поддерживает следующие параметры кодировки: ASCII, BigEndianUnicode, Unicode, UTF32, UTF7, UTF8 и Default. Значение параметра Default зависит от системы.
Интегрированная среда скриптов Windows PowerShell не изменяет кодировку файлов скриптов при использовании команд «Сохранить» или «Сохранить как».
How to Run a PowerShell Script
For more technical explainers on PowerShell, read our updated 2021 report: PowerShell 101: A Technical Explainer for IT Pros .
As you probably know, PowerShell is Microsoft’s latest Windows operating system (OS) shell and scripting tool . A shell is a program that provides a user interface for the OS. When we’re talking about PowerShell, the «shell» part usually refers to its command-line interface (CLI). A CLI is a basic user interface that lets you enter a command (or a series of commands) at a prompt. When you press Enter, the shell performs an action, then the CLI displays the prompt again and waits for another command. (See also, « Getting Started with PowerShell «).
However, PowerShell’s secure by default philosophy prevents all scripts from running, so double-clicking a PowerShell script from Windows Explorer won’t execute it. Also, PowerShell doesn’t execute scripts from the current directory. The good news is that you don’t have to be a PowerShell guru if all you want to do is understand how to run PowerShell scripts. Simply follow these steps:
1. Install Windows PowerShell
2. Set PowerShell’s Execution Policy
As I mentioned previously, PowerShell is secure by default. The first implication of this philosophy is that PowerShell won’t execute scripts until you explicitly give it permission to do so. PowerShell has four execution policies that govern how it should execute scripts:
To display the current execution policy, you need to enter the command
at a PowerShell prompt (which will look like PS C:\> assuming the current location is C:\). To set the execution policy, enter the command
where policy is one of the policy names (e.g., RemoteSigned).
Setting the execution policy requires administrator permissions. In Vista and later, you must run PowerShell with elevated permissions if you’re already an administrator and User Account Control (UAC) is enabled. To run PowerShell under elevated permissions in Vista and later, right-click its shortcut and choose Run as administrator, as Figure 1 shows.
If you’re logged on to XP or Windows 2003 as a standard user, you can right-click the PowerShell shortcut, choose Run as, and enter administrator account credentials.
I recommend setting the execution policy to RemoteSigned because this execution policy lets you write and run scripts on your own computer without having to sign them with a code-signing certificate. You’ll still be prevented from running a script downloaded from the Internet unless you explicitly unblock it first. To set the RemoteSigned execution policy, enter the following command at a PowerShell prompt:
Microsoft also provides an administrative template (.adm file) for managing PowerShell’s execution policy through a Group Policy Object (GPO), which you can download from the «Administrative Templates for Windows PowerShell» web page.
3. Run Your PowerShell Scripts
For these reasons, I recommend running PowerShell scripts from a PowerShell command window instead.
Another important detail to keep in mind when running scripts is that PowerShell doesn’t run them from the current directory. Instead, it uses the Path. (The Path is a comma-delimited list of directories, stored in the Path environment variable, that Windows searches for executable files.) If you type a script’s name (but not its location) and the script isn’t found in the Path, PowerShell won’t run it, even if the script is in the current directory. This is another aspect of PowerShell’s secure by default philosophy. PowerShell doesn’t run scripts in the current directory, to prevent the scenario in which an attacker puts a bogus script in the current directory with the same name as a commonly used command. If PowerShell ran scripts from the current directory first, a user might unwittingly run the rogue program by accident. By ignoring scripts in the current directory, PowerShell avoids this potential problem.
If you enter these commands at the PowerShell prompt
PowerShell won’t run HelloWorld.ps1, even though the current location is C:\Scripts. (Note that I included the prompts you’d see, for demonstration purposes. You wouldn’t type these prompts when entering the commands.) Instead of the second command, you need to type one of the following commands:
Because PowerShell doesn’t execute scripts from the current directory, I recommend that you create a directory, add this directory to your Path, and store your PowerShell scripts in this directory. That way, you can avoid any problems.
The final detail you need to remember when running PowerShell scripts is that you need to handle spaces differently than you did in Cmd.exe. When a script’s pathname contains spaces, you have to surround it with double quotes («) to run it in Cmd.exe. For example, in Cmd.exe, you’d type:
to run a script named C:\Program Files\Scripts\HelloWorld.cmd. Quoting a script’s path to run it won’t work in PowerShell, because the presence of double quotes causes PowerShell to evaluate the pathname as an expression rather than a command. If you simply type the script’s name in quotes like you did in Cmd.exe, PowerShell assumes the pathname is a string and outputs the pathname instead of running the script. To work around this, you can use PowerShell’s invocation operator, &, to execute the quoted string as a command, as in
Because you must use the & operator and quotes to execute a script that has spaces in its pathname, I recommend that you don’t use spaces in your scripts’ names when creating your own scripts. In addition, if you create a directory in which to store scripts, make sure you leave out spaces in its name as well.
Running PowerShell Scripts Made Easy
You don’t need to be a PowerShell or scripting language expert to easily run PowerShell scripts. Simply follow these three steps and you’ll be running PowerShell scripts in no time.
How to Run PowerShell Scripts
PowerShell scripts are a powerful and flexible way of automating administrative and repetitive tasks. They can be written with only a text editor and a basic knowledge of the cmdlets that are available. However, running scripts written by others or downloaded from the Internet can be a risky activity – the level of access that a PowerShell script has to your system is extensive, and this is why their execution is blocked by default in Windows.
The information below describes how to safely enable the execution of scripts, and the specifics of how to run them when that initial configuration is complete. It is beyond the scope of this article to provide a complete tutorial on PowerShell or writing PowerShell scripts – courses containing much more information about setting up your systems to run PowerShell scripts, and even a complete getting started tutorial for beginners to PowerShell are available at Udemy.com.
Setting the Execution Policy
The PowerShell Script Execution Policy is a system-wide configuration setting that allows (or disallows) the execution of PowerShell scripts, depending on where they came from and who they are published by.
There are four different levels for this setting:
All PowerShell scripts can be run. For security reasons this is not usually recommended.
The execution policy can be changed from the PowerShell console, using the cmdlet Set-ExecutionPolicy followed by one of the four levels above. You may need to run the console as an administrator in order to change the configuration setting.
For home users, and for people in the process of writing scripts, the RemoteSigned policy protects the system from downloaded scripts, but does allow users to run their own work. To enable the RemoteSigned policy, type the following statement in a PowerShell console and press Enter:
Although less convenient, AllSigned offers significant extra security. It can be particularly useful for system administrators as it not only protects the computer from downloaded scripts, but also prevents users from writing and running their own. To run scripts under the AllSigned execution policy, they must be signed by a trusted publisher with a code-signing certificate from a trusted certification authority.
Signing Scripts
Digital signatures are more useful than their real-world counterparts. In addition to verifying authenticity (that the script comes from the person or publisher that it claims to), they also verify integrity (that the script has not been modified since it was signed).
For a signature to be accepted by PowerShell, it must come from a trusted source and you can buy code-signing certificates from organizations such as Verisign and Thawte. However, if you have sufficient control over the systems that need to run your scripts, you can generate your own signing certificate for free. When deploying a self-signed script across a network, you must first create your own authority and then you will need to add that authority as a trusted certification authority on every machine that will execute your scripts.
The processes involved in creating a certification authority, issuing code-signing certificates, and managing these certificates are too lengthy to detail here. However, the steps can be summarized as:
Running a PowerShell Script from the Console
After the script has completed, any variables or functions that are declared in it will be cleared from memory. In some cases this is not the desired outcome, and it can be avoided by “dot sourcing” – starting the call with a dot, and then placing the file path and file name in quotes:
Running a PowerShell Script from another PowerShell Script
A PowerShell script can run another script using the same syntax as used in the console. However, when scripting it is often useful to hold file names in variables, particularly if they are referenced often in the script. This is done by using a variation of the “dot sourcing” technique described above. For example:
Finally, the Invoke-Expression cmdlet can also be used to call scripts. However, given the relative simplicity of the examples so far, there is little need to use a cmdlet for such a basic process. Invoke-Expression is capable of much more than running other scripts – for example, running commands and blocks of code from strings – and you can see examples of its use in the PowerShell help system:
Running a PowerShell Script from Windows
Double-clicking a script in Windows File Explorer or the Desktop view, usually causes the script to open in the system’s default text editor. However, a script can be started without first opening the PowerShell console by right-clicking it and then clicking Run with PowerShell.
To change how all PowerShell scripts are treated when double-clicked:
In certain circumstances, you may need the PowerShell console to stay open after the script has ended. To do this, use a shortcut to the script instead:
Scheduling PowerShell Scripts
Scripts can be useful for a wide variety of tasks and it can often be helpful to schedule execution of scripts so that they run on a regular basis without the intervention of the system administrator or users. This can be done using the Windows Task Scheduler.
To schedule a PowerShell script to run at a predefined interval:
Источники информации:
- http://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scripts?view=powershell-7.2&viewFallbackFrom=powershell-7.1
- http://docs.microsoft.com/ru-ru/powershell/scripting/windows-powershell/ise/how-to-write-and-run-scripts-in-the-windows-powershell-ise?view=powershell-7.2&viewFallbackFrom=powershell-7.1
- http://www.itprotoday.com/powershell/how-run-powershell-script
- http://blog.udemy.com/run-powershell-script/