Functions in PowerShell

Содержание
Example
$profile
Run specific .exe file
Wait till Python is installed
Related Articles

Example

A function that will move user to a specific directory

function autotest { set-location "C:\AutoTest" }

function andrei { set-location "C:\Users\Andrei" }

If a function uses a path with spaces, they can be escaped using the ` character.

function appbin { set-location C:\Program` Files\App\bin }

Now, by executing the command andrei the user will get to Andrei's home directory

Изображение баннера

profile

To ensure that aliases and functions persist after a reboot, they must be added to the PowerShell profile settings file.

You can find its location using the command

$profile

C:\Users\Andrei\Documents\PowerShell\Microsoft.PowerShell_profile.ps1

If $profile shows a non-existent path, you can create the settings file manually.

New-Item -Path $profile -Force -ItemType "file"

The file can then be opened and edited in Notepad.

notepad $profile

function autotest { set-location "C:\AutoTest" } function andrei { set-location "C:\Users\Andrei" }

PowerShell needs to be restarted.

Launching a specific .exe file

Sometimes it's convenient to run .exe files using functions. Especially when their paths are inconvenient to type in the terminal. For example, they're from Program Files (x86)

An example of a function that runs Python which uses TestComplete in interactive mode.

notepad $profile

function tcpython { Start-Process -FilePath "C:\Program Files (x86)\SmartBear\TestComplete 15\x64\Bin\Extensions\Python\Python310\python.exe" }

Wait for Python to install

An example PowerShell script that uses a custom function to check for Python installation completion.

This can be useful if the installation is triggered by another script and you need to wait for it to complete before performing any further actions.

function Is-Py-Installed { Write-Output "Is-Py-Installed is running" $installed = Get-Command python -ErrorAction SilentlyContinue if ($installed) { $version = python --version 2>&1 Write-Host "Python version: $version" -f Green return 1 } else { Write-Host "Python is not yet installed on this device." -f Yellow return 0 } } $py_installed = 0 while ($py_installed -eq 0) { Write-Output "while loop is running" $py_installed = Is-Py-Installed Start-Sleep -Seconds 3.0 }

Article author: Andrei Olegovich

Похожие статьи
Windows
PowerShell
Install
Basics
Alias
Functions
Network
Users
Files
REST API requests
Errors

Поиск по сайту

Подпишитесь на Telegram канал @aofeed чтобы следить за выходом новых статей и обновлением старых

Перейти на канал

@aofeed

Задать вопрос в Телеграм-группе

@aofeedchat

Контакты и сотрудничество:
Рекомендую наш хостинг beget.ru
Пишите на info@urn.su если Вы:
1. Хотите написать статью для нашего сайта или перевести статью на свой родной язык.
2. Хотите разместить на сайте рекламу, подходящую по тематике.
3. Реклама на моём сайте имеет максимальный уровень цензуры. Если Вы увидели рекламный блок недопустимый для просмотра детьми школьного возраста, вызывающий шок или вводящий в заблуждение - пожалуйста свяжитесь с нами по электронной почте
4. Нашли на сайте ошибку, неточности, баг и т.д. ... .......
5. Статьи можно расшарить в соцсетях, нажав на иконку сети: