Did you find this summary helpful?
Thank you for your feedback
PowerShell is the standard for automating configuration on Windows servers, and Otter was designed to seamlessly integrate with it — whether that means running your existing scripts across dozens of servers, leveraging scripts built by the community, or a custom combination of both.
While you definitely don’t need to be a scripting guru to use Otter, learning how to incorporate scripts into Otter will enable you to automate virtually any aspect of Windows, at the click of a button.
Adding Existing Scripts to Otter
Otter can create a GUI for your scripts so that it becomes easy to run complex PowerShell scripts by defining script parameters that include descriptions, help text, dropdown, or checkbox inputs, and more.
The best way to do this is creating a Job Template that runs your script against target servers. You can also use an ad-hoc Job to run the script without a template.
See the Create a GUI for Scripts with Input Forms for step-by-step guide on this in Otter.
If you are executing PowerShell from OtterScript, all the PowerShell operations have a PreferWindowsPowerShell parameter that can be set also. This parameter will default to use $PreferWindowsPowerShell.
Using OtterScript to Orchestration Scripts
Once you’ve added PowerShell Scripts to Otter, you can use an OtterScript Orchestration to run those scripts on different servers in a complex manner, whether that means targeting servers sequentially, in parallel, or even with branching and iterating (looping) logic.
Although OtterScript is based on programming logic, you do not need to be a coder to use OtterScript, which offers both a text editor and a low-code visual editor.
Using PSCall to Run PowerShell
You can call your scripts using the PSCall Operation. If you use PowerShell’s Comment-based Help, you’ll get descriptions for script arguments when editing in visual mode, similar to running the script using a Job.
Collecting & Verifying with PowerShell
PSVerify verify-hotfix-installed
(
HotFixID: KB4532938
);
PSVerify verify-hotfix-installed
(
HotFixID: KB4483843
);
Remedating Drift with PowerShell
In addition to verifying the configuration of your servers, Otter can use your existing PowerShell scripts to reconfigure your servers into your desired state using an operation called PSEnsure.
This is a bit different than PowerShell’s Desired State Configuration (DSC), and it’s a simpler alternative that lets you use basic PowerShell commands.
PowerShell Script ASset
PowerShell Desired State Configuration (DSC) offers quite a few open-source modules that you can use to configure different features of Windows Servers. With PSDsc, you can invoke DSC Resources in nearly the same manner as a native DSC statement.
PSDsc xWebAppPool (
Name: AccountsAppPool,
Ensure: present
);
These declarative-style statements are essentially Ensure Operations, and thus will collect, report, and remediate drift just like the Built-in Operations.
Inline Execution of PowerShell
Through PSExec and Swim Strings, you can run scripts text directly from your OtterScript.
Otter will seamlessly replace variables within this script string, so in the example below $ApplicationName might be defined as a Configuration Variable.
PSExec Example
OtterScript is not a general-purpose programming language, and thus doesn’t have built-in support for things like arithmetic. You could, of course, write a custom variable function to support this, but PSEval is much easier:
For example, if you wanted to convert the value stored in one variable ($minutes) to milliseconds. You could PSEval the simple expression $minutes * 60 * 1000:
set $milliseconds = $PSEval($minutes * 60 * 1000);
Цифровая подпись у PowerShell скрипта (файла *.PS1) позволяет при запуске удостовериться, что скрипт подписан доверенным издателем и его код не был изменен. Для подписи кода PowerShell скрипта вам нужно получить сертификат типа Code Signing. Такой сертификат можно:
Таким образом, у вас должен файл сертификата с закрытым ключом в формате .PFX (с X509. Импортируйте этот сертификат в локальное хранилище компьютера:
Если вы хотите использовать самоподписанный сертификат, его можно сгенерировать с помощью PowerShell:
$certFile = New-SelfSignedCertificate -Subject “Certificate to sign PowerShell sсripts” -Type CodeSigningCert -DnsName $env:computername -CertStoreLocation cert:LocalMachinemy
Подписать код PowerShell скрипта с помощью сертификата
Вывести список доступных сертификатов для подписывания кода скриптов PowerShell в указанном хранилище:
Get-ChildItem cert:LocalMachinemy -CodeSigningCert
Выбрать сертификат можно по его отпечатку:
Чтобы подписать код указанного PowerShell скрипта, выполните:
$PSScript = “C:PSHardwareReadiness.ps1″$TimestampServer = “http://timestamp.verisign.com/scripts/timstamp.dll”Set-AuthenticodeSignature -FilePath $PSScript -Certificate $signcert -TimestampServer $TimestampServer
Если вы попытаетесь использовать обычный сертификат для подписывания скрипта, появится ошибка:
Set-AuthenticodeSignature : Cannot sign code. The specified certificate is not suitable for code signing.
При подписывании файла PowerShell скрипта, командлет Set-AuthenticodeSignature добавляет в конец текстового файла PS1 блок сигнатуры цифровой подписи, обрамленный специальными метками:
Блок сигнатуры содержит хэш скрипта, который зашифрован с помощью закрытого ключа.
В свойствах PS1 файла на вкладке Digital Signatures появится информация о наличии подписи у скрипта и информация о сертификате.
Запуск подписанных PowerShell скриптов в Windows
По умолчанию настройки политики выполнения PowerShell скриптов в Windows блокируют запуск любых PS1 скриптов (режим Restricted) и при запуске скрипта появится ошибка.
File C:PSHardwareReadiness.ps1 cannot be loaded because running scripts is disabled on this system.
Чтобы разрешить запуск только подписанных PowerShell скриптов, нужно изменить настройки политики на AllSigned. Настройки политики выполнения можно изменить:
Проверьте настройки политики выполнения:
Если попробовать запустить сейчас подписанный PowerShell скрипт, появится ошибка:
File C:PSHardwareReadiness.ps1 cannot be loaded. A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider.
Для запуска подписанного PowerShell скрипта, нужно добавить отпечаток сертификата в корневые доверенные сертификаты. Можно скопировать сертификат из секции Personal в хранилища Trusted Root Certification Authority и Trusted Publisher с помощью графической консоли
Certlm.msc
(скопируйте сертификат из Personal хранилища и вставьте его в корневые).
Теперь подписанный PowerShell скрипт будет запускаться без предупреждений.
Чтобы проверить действительность подписи PowerShell скрипта, выполните команду:
Таким образом, после любой модификации кода подписанного PS1 скрипта его нужно заново переподписать. Также скрипт перестанет запускаться после истечения срока действия сертификата, поэтому за этой датой также нужно следить.
Рекомендуется подписывать все PowerShell скрипты, выполняющиеся с повышенными привилегиями администраторов домена или серверов, а также скрипты, которые запускаются на компьютерах пользователей через GPO.
2 min. read
Do you want to run PowerShell script from CMD because it might not be available on your system? Or do you just want to incorporate PowerShell functionality without rewriting the entire script into a CMD batch file? If your answer is “Yes” to any of these questions, this article will help!
How To Run a PowerShell Script from CMD
When running a PowerShell script on CMD, the process may get interrupted due to the inappropriate settings for the Set-ExecutionPolicy feature.
There are two ways to resolve this error:
Now you know how to run a PowerShell script from CMD. This is a quick and convenient way to run advanced scripts on a rudimentary terminal.
Seasoned blogger & software reviewer with publications from MakeUseOf, AddictiveTips & AppleToolBox. He tests everything before writing about it.
Was this page helpful?
Let us know if you managed to solve your tech problem reading this article.
We’re happy to hear that!
You can subscribe to our newsletter to stay up to date with the latest news and best deals!
Do you have a suggestion?
We know how frustrating could be to look for an universal solution.
If you have an error which is not present in the article, or if you know a better solution, please help us to improve this guide.
(Image credit: Mauro Huculak)
On Windows 11 (or 10), PowerShell is a command-line interface (CLI) to run commands and scripts to automate tasks and change settings on your device, similar to Command Prompt. However, PowerShell is a more powerful CLI, offering more tools and flexibility. In addition, unlike Command Prompt, PowerShell is available across platforms, including Windows, macOS, and Linux.
A script is a collection of instructions written to a text file (using the “.ps1” extension) that PowerShell understands and executes in sequence to run different actions.
The only caveat is that the default security protocol prevents scripts from running on your computer. This means that when double-clicking a “.ps1” file, the system won’t do anything, and if you try to run the script within PowerShell, you will see the “cannot be loaded because running scripts is disabled on this system” error message. However, running scripts on your device is possible. You only need to enable the correct execution policy.
In this how-to guide, I will walk you through the steps to create and run your first script file on PowerShell using Visual Studio Code, Notepad, and the PowerShell Integrated Scripting Environment (ISE) console, whether you use Windows 10 or 11.
How to create PowerShell script file on Windows 11 and 10
It’s possible to create PowerShell script files using any text editor or the legacy ISE application. However, the Visual Studio Code editor is the preferred option for writing scripts moving forward.
Create a script with VS Code
Visual Studio Code (VS Code) is a free, extensible, cross-platform code editor that works to write virtually any programming language. And when adding the PowerShell extension, you get an interactive scripting editing experience, which even comes with IntelliSense (code-completion) support.
You can still use PowerShell ISE, but Visual Studio Code with the PowerShell extension is meant to be the new default experience. Also, consider that the legacy experience won’t get any new features and doesn’t support PowerShell 7 or future releases.
All the latest news, reviews, and guides for Windows and Xbox diehards.
Install VS Code
To install Visual Basic Code on Windows 11 (or 10), use these steps:
Once you complete the steps, you can continue installing the PowerShell extension for VS Code.
Install PowerShell extension
To install the PowerShell extension on VS Code, use these steps:
After you complete the steps, you can start writing PowerShell scripts from Visual Studio Code.
Create PowerShell script with Visual Studio Code
To create a script with Visual Basic Code on Windows 11 (or 10), use these steps:
Create PowerShell script with Notepad
To create a PowerShell script with the Notepad app, use these steps:
Create PowerShell script with Integrated Scripting Environment
You can also use the built-in PowerShell ISE app to code your scripts on Windows.
The Integrated Scripting Environment (ISE) is a complex tool, but you can get started using these easy steps:
How to run PowerShell script file on Windows 11 and 10
Whether you use Windows 11 or 10 on your computer, you must change the execution policy to run a script with PowerShell.
To change the execution policy to run PowerShell scripts on Windows 11 (or 10), use these steps:
After you complete the steps, the script will run, and if it was written correctly, you should see its output on the screen without issues.
PowerShell includes four execution policies that apply to the operating system:
PowerShell saves scripts in the .PS1 format. Feel free to use your own custom folder and file names. For our demonstration, we created both a file and a folder:
C:ScriptsMy First Script.ps1
Create a new file and add a cmdlet
Create the new .PS1 file, and add the Write-Host cmdlet (cmdlet is another word for command).
Write-Host “Hello, World!”
Save and try to run the script
Save your .PS1 file, and return to the PowerShell window. To run the script, the most common method is to call it in the PowerShell terminal. (You can also use the PowerShell ISE or VS CodeVS Code.)
& “C:ScriptsMy First Script.ps1”
Go ahead and try that command. You should get an error that says scripts are disabled on your system. This is for security reasons.
Modify the execution policy
In order to prevent malicious scripts from running on your system, PowerShell enforces an execution policy. To use our newly created script, we have to modify our execution policy to allow our PowerShell example script to run. There are four execution policies:
Since we have not digitally signed our new PowerShell example script, our options for the execution policy are limited to RemoteSigned and Unrestricted. We are going to change it to RemoteSigned.
The Set-ExecutionPolicy cmdlet asks to verify that you really want to change the execution policy. Go ahead and select Y for yes, then close and reopen your PowerShell window.
Run your script
After restarting the PowerShell window, try running your .PS1 script again.
It should write back, “Hello, World!” to the window:
Congratulations — you just wrote your first PowerShell script!
PowerShell examples for beginners
Or try clearing out a temp folder that is taking up space with unneeded documents:
Or test if a registry key is on a machine:
Those are all quick wins that you can grab out of the box. The entire world opens once you dive into modules and start with scripts against critical systems, like Azure, VMWare, AWS, or Active Directory.
Take your next steps with PowerShell
You now have the amazing power to create and run your own scripts and cmdlets.
Jordan had spent his life wondering why tasks he didn’t like to do had no options to complete themselves. Eventually he had to make that happen on his own. It turned out that he enjoyed making tasks complete themselves, and PDQ thought that is something he should talk about on the internet.