Powershell скрипт как служба
Запускаем Powershell скрипт как службу
Запустить скрипт в большинстве случаев поможет планировщик задач (Task Scheduler). Но предположим, у нас есть PowerShell скрипт, который работает в вечном цикле и/или реагирует на изменения системы в реальном времени. Такая ситуация сложилась со мной сегодня ночью, когда я писал скрипт обновления Secondary DNS на Bind9 из MS DNS.
Чтобы следить за изменениями, как и в обычном C# следует использовать FileWatcher. Вот такой простой скрипт следит за моей пользовательской папкой в вечном цикле:
Пилим свою службу Windows – руководство для «не настоящих программистов»

- Потребовалось создать сервис на fail2ban для Windows 2003., который работал с логами FileZilla и Apache, а при подозрении на брутфорс блокировал IP штатными средствами Windows — ipsec.
- Аналог телнет-сервера для домашних версий Windows. Понадобилось выполнять команды на удаленных рабочих станциях, которые были под управлением Windows 7 Home. По сути, вторая попытка поиграть в службы.
- Музыкальный проигрыватель для торгового зала под Windows. Задачу по ТЗ можно было решить при помощи mpd и пачки скриптов, но я решил — если уж делать скрипты, то почему бы и не «сваять» проигрыватель самому. За основу взял библиотеку BASS.dll.
- Когда выбирали веб-сервер с поддержкой загрузки файлов под Windows, одним из вариантов был HFS. Сам по себе работать он не может, поэтому пришлось «запихивать» его в службу. В результате решение не понравилось, и просто установили «тему» Apaxy на web-сервере Apache.
Способ первый. От Microsoft

Работа так называемого «сервера».

Настроенная служба.

Работающая служба.
- Утилиты старые, разработаны до изобретения PowerShell, UAC и прочих вещей.
- Srvany не контролирует работу приложения. Даже если оно выпадет в ошибку, служба продолжит свое дело как ни в чем не бывало.
- Придется донастраивать и копаться в реестре. Вы же помните, что копаться в реестре небезопасно?

Установка через PowerShell.

И вправду работает.

Настроить можно даже приоритет и использование ядер процессора.
Способ третий. AutoIT

Оно работает!
How to run a PowerShell script as a Windows service
Most PowerShell scripts aim to run a task and then exit. You’ll usually execute a script from the PowerShell console or perhaps trigger it periodically via the Windows Task Scheduler. However, you may want to run a script 24/7 and ensure it starts up again after a reboot or crash. To do this, the easiest option is to use NSSM.
About NSSM ^
If you’ve not heard about NSSM before, it’s a small service helper similar to the built-in program srvany. NSSM aims to make it extremely simple to configure any binary to run as a service and ensure it stays running. You can take a look at the NSSM website for more information about common use cases.
Example script ^
Take this example script below. This script runs a small web server using the Polaris framework. Polaris is a cross-platform, minimalist web framework written in PowerShell. Currently, this is not a Microsoft-supported module, but I encourage you to look at it if you are interested in experimenting with web servers and PowerShell commands. Like a normal web server, ours should run all the time, and we will use a Windows service to achieve this.
Installing Polaris ^
Currently, Polaris is not available in the PowerShell Gallery, so we’ll need to install it manually. Download the zip archive from the git repository, and extract the contents to C:\Program Files\WindowsPowerShell\Modules\Polaris.

Download the Polaris zip file
Your modules directory should look like this:

Polaris extracted to the modules folder
If we run this script manually, we can verify Polaris is running and serving requests at http://localhost:8080/helloworld. It will keep running until you press Ctrl+C.

Testing Polaris in the browser
Install NSSM ^
Now on to installing NSSM so we can configure our Windows service. If you are already using Chocolatey, you can install NSSM with the following:

Installing NSSM with Chocolatey
If you don’t have Chocolatey installed, you can download NSSM here.
Install the Windows service ^
After installing NSSM, we’ll need to run a few commands to install our web server script as a Windows service. You’ll need to run these next commands as an administrator.
We have to define a few variables. We’ll need the path to NSSM itself, the name of the service we want to create, the path to PowerShell, the path to our Polaris script, and the argument string we’ll pass to PowerShell.

Install a script as a service
Validating the script ^
Now that we’ve installed our new service, we can test everything is working with Invoke-RestMethod.

Testing the web server with Invoke RestMethod
As with any Windows service, we can also set this to start automatically on boot or restart if it unexpectedly terminates.
Subscribe to 4sysops newsletter!
Conclusion ^
You might find running a PowerShell script as a service handy in many use cases. Hopefully I’ve just whetted your appetite on what you can do with services, NSSM, and PowerShell.
oze4/PaaWS-PowerShell-as-a-Windows-Service
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Run a PowerShell script as a Windows Service, using this PowerShell GUI script (with bonus uninstaller)
How to Run a PowerShell Script From the Command Line and More
Download a free trial of Veeam Backup for Microsoft 365 and eliminate the risk of losing access and control over your data!
Table of Contents
If you’re new to the PowerShell scripting language and want to learn how to run PowerShell script, you’ve come to the right blog post. This blog will be a tutorial covering common ways to run scripts and a few issues that may pop up.
Not a reader? Watch this related video tutorial!
Prerequisites
This article will be a walkthrough for you about how to run PowerShell on your local computer. If you’d like to follow along, please be sure you have the following prerequisites in place before starting this article.
- A Windows 10 computer with Administrator privileges.
- Windows PowerShell version 5 or higher. You can also use PowerShell v7. This tutorial will focus on Windows PowerShell since the Windows operating system already has it.
- Any text file editor
Dealing with the Execution Policy
If this is the first time you’re trying to execute a Windows PowerShell script, you may run into a common problem. PowerShell will probably return an error message stating that a script “cannot be loaded because running scripts is disabled on this system”.
PowerShell returns the error message above when you try to run a PowerShell with an execution policy set to Restricted, Remote Signed or All Signed.
Restricted
Restricted is the default policy set for Windows client computers. If you are using PowerShell for the first time, your default policy would probably be set to restrict all the scripts.
You can still execute individual commands in a terminal, but not a script file. The restriction includes any file ending with .ps1xml , .psm1 or .ps1 .
Unrestricted
Unrestricted allows you to run any script however, it warns you before execution if the script is downloaded from the internet. This policy is usually the default for any non-windows devices.
Remote Signed
Remote Signed policy allows you to run any script that is either (a) digitally signed or (b) any script written on your local computer with or without a signature.
If a script is downloaded from the internet and not signed, you would need to unblock the file. You can do so by right-clicking on the file and choosing Properties. Or, you could use the Unblock-File PowerShell cmdlet for that particular script file.
Using a Remote signed policy would be an ideal option when running a script downloaded from the internet.
All Signed
All signed requires all the scripts to be signed digitally by a trusted publisher. This includes the scripts downloaded from the internet and written locally on your computer.
Changing the PowerShell Execution Policy
To change the execution policy:
- Open Windows PowerShell with Run as Administrator to make sure you have the highest permission to make the policy changes.

Search PowerShell in Start Menu
2. When open, run the following PowerShell command to set your computer’s execution policy. The execution policy, as covered above, can be one of three different types. This tutorial is using a useful yet still secure execution policy of RemoteSigned.
Since this tutorial assumes you’ve downloaded from the Internet the GetServices.ps1 script file, set the execution policy to RemoteSigned.
The RemoteSigned execution policy forces you to cryptographically sign every PowerShell script downloaded from the Internet before PowerShell will run it on your system.
3. You should see an output requesting to confirm the action. Enter Y and hit enter to confirm the policy change.
At this point, follow the next steps to explore different methods to run the PowerShell script on your computer.
How to Run PowerShell Script
To demonstrate running a PowerShell script, you actually need a script file to run! If you don’t have one handy, download this ZIP file and extract the PS1 file within. You’ll find a simple script file inside called GetServices.ps1.
Every PowerShell script should end with a .ps1 extension.
Using the Console
Once you have a script ready, there are a few different ways you can execute a PowerShell script file. One of the most common ways is via the PowerShell console.
- Open the PowerShell console as shown above.
2. Navigate to the file system location your script is located using the Set-Location PowerShell cmdlet or the cd alias. This tutorial’s script is found in the C:\Temp directory.
3. Run the script using a dot ( . ) notation. PowerShell is a shell that also looks for command names. To differentiate between a PowerShell command and a script, you must preface the script with a dot. This dot represents the current directory.
How to Run a PowerShell Script from the Command Line via the PowerShell Location
If you can’t or would rather not run scripts via the PowerShell console, you can also do so with the good ol’ command line (command prompt).
To run scripts via the command prompt, you must first start up the PowerShell executable (powershell.exe), with the PowerShell location of C:\Program Files\WindowsPowerShell\powershell.exe and then pass the script path as a parameter to it.
You can run scripts with parameters in any context by simply specifying them while running the PowerShell executable like powershell.exe -Parameter ‘Foo’ -Parameter2 ‘Bar’ .
Once you open cmd.exe, you can execute a PowerShell script like below. This example is running the engine and passing it the script path of C:\Temp\GetServices.ps1.
Notice below that the example below is using the PowerShell location path to run the script. You’ll have to do this if the folder isn’t in your PATH somewhere.
The PowerShell location for PowerShell 7 uses a different executable named pwsh.exe typically located in C:\Program Files\PowerShell\7\pwsh.exe.
Below is a handy YouTube video that covers executing a script via a batch file which the cmd.exe executes.
Using the PowerShell ISE
If you create your own scripts or edit others’, you’ll probably be using a script editor like the PowerShell ISE or maybe Visual Studio (VS) Code. Since the ISE comes with Windows, let’s focus on that method for this tutorial.
To invoke a script via the ISE:
- Navigate to Start Menu, search for PowerShell ISE and open it.

Search PowerShell ISE in Start Menu
2. Click on File → Open and find your script.

Open Script using File Menu
3. With the script open, click on the green run button to execute the script. This button will invoke the script in the built-in PowerShell terminal at the bottom.

Run Script using PowerShell ISE
The Sample Script’s Output
A PowerShell script can sometimes return output. This happens when the script you’re executing is built to return objects which is a fundamental component of PowerShell.
If you run the sample GetServices.ps1 script, you will see the following. This script runs the Get-Service cmdlet which returns all of the services installed on your local Windows computer.
Running a PowerShell Script from Within a Script
Let’s say you have two scripts and you’d like one to call the other. Perhaps you have a script called GetUser.ps1 and one called ResetPassword.ps1. Inside of the GetUser.ps1 script, you’d like to execute the ResetPassword.ps1 to reset a user password.
Inside of the calling script (GetUser.ps1), you’d add a line to execute the other script just like you would call the script from the command line.
You can see below you have a couple of options. You should typically choose to run the other script within the same session or scope to simplify things unless you have a specific reason to run the script in another PowerShell session.
Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.
More from ATA Learning & Partners
Recommended Resources!
Recommended Resources for Training, Information Security, Automation, and more!
Get Paid to Write!
ATA Learning is always seeking instructors of all experience levels. Regardless if you’re a junior admin or system architect, you have something to share. Why not write on a platform with an existing audience and share your knowledge with the world?
ATA Learning Guidebooks
ATA Learning is known for its high-quality written tutorials in the form of blog posts. Support ATA Learning with ATA Guidebook PDF eBooks available offline and with no ads!
Руководство по Windows PowerShell для начинающих
В этой статье про PowerShell для начинающих мы посмотрим, как писать скрипты, которые помогают оптимизировать управление Windows-окружением.
PowerShell — это объектно-ориентированный программный движок и скриптовый язык с интерфейсом командной строки, предоставляющий широкие возможности для конфигурирования операционных систем семейства MS Windows. Он предлагает как чисто консольный интерфейс, так и полноценную среду разработки PowerShell ISE (Integrated Scripting Environment, встроенное скриптовое окружение) для скриптов.
Для запуска интерфейса командной строки введите powershell в меню «Выполнить» (WinKey + R). PowerShell ISE запускается с помощью команды «PowerShell ISE» в том же меню. ISE более предпочтительно, так как предоставляет более широкие возможности разработчику благодаря подсветке синтаксиса, функции автозаполнения кода и другим особенностям, присущим многим «большим» IDE.

Среда разработки Windows PowerShell ISE
Написание и запуск скриптов
Скрипты сохраняются в виде файлов с расширением .ps1 . Несмотря на то, что PowerShell уже давно является нативной частью ОС Windows, вы не сможете запустить его скрипты простым двойным щелчком. Для этого надо кликнуть правой кнопкой по скрипту и выбрать «Запустить в PowerShell».
Также существуют системные политики, ограничивающие выполнение скриптов. Можно проверить текущие параметры политики, введя команду Get-ExecutionPolicy . Результатом будет одно из следующих значений:
- Restricted — выполнение скриптов запрещено. Стандартная конфигурация;
- AllSigned — можно запускать скрипты, подписанные доверенным разработчиком; перед запуском скрипта PowerShell запросит у вас подтверждение;
- RemoteSigned — можно запускать собственные скрипты или те, что подписаны доверенным разработчиком;
- Unrestricted — можно запускать любые скрипты.
Для начала работы необходимо изменить настройку политики запуска на RemoteSigned, используя команду Set-ExecutionPolicy :
После выполнения команды можно будет запускать свои скрипты
Командлеты
Командлеты — это команды с предопределённой функцией, подобные условным операторам в языках программирования. У них есть несколько ключевых особенностей:
- существуют системные, пользовательские и опциональные командлеты;
- результатом выполнения командлета будет объект или массив объектов;
- командлеты могут обрабатывать данные и передавать их другим командлетам с помощью конвейеров;
- командлеты нечувствительны к регистру, так что нет никакой разницы между Get-ADUser , get-aduser и gEt-AdUsEr ;
- в качестве разделителя используется символ ; .
Каждый командлет содержит в себе глагол и существительное, разделяемые дефисом. Например:
- Get-Process — отобразить текущие процессы, запущенные на компьютере;
- Get-Service — отобразить список служб и их статус;
- Get-Content — отобразить содержимое указанного файла, например Get-Content C:\Windows\System32\drivers\etc\hosts .
При необходимости список всех доступных командлетов можно вывести с помощью Get-Help-Category. Запомните эту команду — она крайне важна для тех, кто изучает PowerShell с нуля, так как помогает быстрее начать ориентироваться в его возможностях.

Результат выполнения команды Get-Help-Category
Также можно создавать свои командлеты, но эта тема выходит за рамки нашего руководства по PowerShell для начинающих.
Параметры
У каждого командлета есть несколько параметров, определяющих его работу. PowerShell ISE автоматически предлагает все доступные параметры с отображением их типа. Например, Get-Service-NameW* выводит список служб, у которых имя начинается с W . Если вы забыли, какие параметры у введённого командлета, воспользуйтесь Get-Member .
Например, Get-Process | Get-Member :

Список параметров командлета Get-Process
Если вы не нашли того, что нужно, или не уверены в том, как правильно задаются параметры, можно даже запросить примеры с помощью параметра -Examples . Встроенное руководство по PowerShell покажет, для чего используются разные параметры:

Примеры использования командлета
Некоторые командлеты также могут вызываться с помощью алиасов. Например, вместо Get-Help можно просто написать Help — эта команда также вызовет встроенное руководство по PowerShell.
При написании больших скриптов или коллективной разработке можно пользоваться комментариями. Каждый комментарий начинается с символа # , а блок комментариев ограничивается комбинациями символов <# и #> в начале и в конце соответственно.
Конвейер
PowerShell позволяет осуществлять обмен данными между командлетами с помощью конвейера. Например:
- GetService | SortObject -property Status — сортировка запущенных служб по статусу;
- “Hello World!” | Out-File C:\ps\test.txt — запись текста в файл.
Можно использовать несколько конвейеров. Например, следующий скрипт выводит список имён всех служб за исключением остановленных:
Get-Service | WHERE <$_.status -eq “Running”>| SELECT displayname
Заключение
Это руководство для тех, кто изучает PowerShell с нуля, поэтому здесь раскрыты только базовые понятия и приёмы. После его прочтения у вас должно появиться представление о том, что собой представляет этот инструмент. Также мы рассмотрели варианты изменения политики выполнения скриптов, что такое командлет, как они обмениваются данными с помощью конвейера и как получить свойства нужного объекта. Помните, что в случае затруднений можно воспользоваться командлетом Get-Help — это одна из самых важных команд для начинающих изучать PowerShell.
Если пользуетесь не только Windows, но и Linux, посмотрите статью про команды терминала Linux для начинающих. В ней рассказывается про работу с процессами и файлами, навигацию, каналы, xargs, awk и grep.
Execute PowerShell from a ASP.NET Web Application

I had an interesting request come in to automate existing server-side PowerShell processes that have been initiated by server admins thus far locally on the server, using a web interface instead. Turns out, the admins want to offload the work back to the business users so it can be more on demand. Essentially, they want the non-techies to reuse what the techies have been using server side without having to involve 1) the techies, 2) the overhead of logging in to the server, or worse 3) the business users perform PowerShell commands server side (..and therefore running the risk of executing something incorrectly and/or making a security admin’s head explode).
No problem. Here’s a quick demo on how it can be done.
Our plan of attack will be to build a web form project using Visual Studio 2012 and .NET Framework 4.5. It will execute server side and scripts of PowerShell commands using the framework’s PowerShell class from the System.Management.Automation name space. The response I’ll handle as a string, and paint it to a Text box
First, create the Empty Web Application called PowerShellExecution.

Next, add a New Item… of Default web form named “Default.aspx” to the solution to align with the demo content below.
Now, copy and paste over the default Default.aspx code that’s generated with the below for the quick UI test:
Next, to get the System.Management.Automation name space included in our solution we need to install the System.Mangement.Automation package. To do that, under the Tools menu select Library Package Manager >> Package Manager Console

…within the Package Manager Console execute “Install-Package System.Management.Automation”
After a successful execution of that package install, you’ll want to add the reference to your Default.aspx.cs file:
I’m going to use a button’s onclick action to invoke the method that will perform the magic of submitting and reading the response from my PowerShell. The remaining item to address, that may vary on your circumstance, is how to handle the response from the PowerShell.
Remember, everything in PowerShell is returned as an object. We need to display our object back on the page as a string for this demo. You’ll need to be mindful of that when executing, as well as how or what you’re wanting your results displayed on the page.
To ensure that happens for me, I am going manage the output of my PowerShell execution by building a string out of the objects returned. I’ll paint those string casted results in a TextBox control called “ResultBox” using the StringBuilder class within in the System.Text name space. Therefore, I need to reference that name space as well in my code behind.
Below is my complete Default.aspx.cs code for the purposes of this demo. It includes the above references I discussed, the default page load, and especially the onclick method to support the execution details submitted to the Input control using the PowerShell class.
I sprinkled in comments for context:
Copy and paste that in and you’re ready to test…
Once rendered in your browser, type into the “PowerShell Command” window Get-Service | Out-String (or your favorite cmdlet for a test).

Remember, port everything to the Out-String cmdlet so it can be handled properly by the StringBuilder class. Otherwise, you’ll get stringbuilder output of the data type details of the objects returned by your cmdlet – one long get-member call, most likely not what you’re after.
If you’re wondering if you can run scripts that are on the local file system of the server, the answer is yes. Simply pass the script location an parameters in string form to the AddScript() method within Default.aspx.cs using double slashes format.
Contents of this test PowerShellScript.ps1 (same as what was used in the Input control):
(I removed the Input box control and test again the solution below)

Note: To run this on a server, the ApplicationPool hosting your application will have to have administrator rights.