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 }
| Windows | |
| PowerShell | |
| Install | |
| Basics | |
| Alias | |
| Functions | |
| Network | |
| Users | |
| Files | |
| REST API requests | |
| Errors |