Author : MD TAREQ HASSAN | Updated : 2021/09/25
Run a script in PowerShell cli
- Open PowerShell as administrator
cd [target folder]
(in which script is located)./[script_name].ps1
> Enter
Get function name
$MyInvocation.MyCommand.Name
(gives function name when used inside a function)
$rgResourceId = ''
try {
$rgResourceId = (Get-AzResourceGroup -Name $Name -ErrorAction Stop).ResourceId
}
catch {
$exceptionMessage = $Error[0].Exception.Message.Split("-")[1].Trim()
Write-Warning "[at function $($MyInvocation.MyCommand.Name)] -> Exception message: $exceptionMessage"
}
# To use script name too: $(Split-Path -Path $PSCommandPath -Leaf)
# Write-Warning "[$(Split-Path -Path $PSCommandPath -Leaf) at function $($MyInvocation.MyCommand.Name)] -> Exception message: $exceptionMessage"
Return single value from function and script
- PowerShell function and script returns all uncaptured output
Write-Output
return
(when a script returns value, and you are executing that script)- Any variable
$x
just sitting there - etc.
Write-Output
(alias: Echo) will send message as an Object through the pipeline. On the other handWrite-Host
/Write-Warning
/Write-Error
is only console-messages. so:- For normal messages, use
Write-Output
- For exception or error mesaages, use
Write-Warning
/Write-Error
- For normal messages, use
function test {
# do somethings here
$x = 10
# Use -> Write-Host or Write-Warning or Write-Error
# Do Not Use -> Write-Output
return x
}
$returnedVal = test
#returnedVal: 10
StackOverflow question: https://stackoverflow.com/questions/29556437/how-to-return-one-and-only-one-value-from-a-powershell-function
Show progress
-Verbose
flag will show updates when performing operation
$name = 'rg-xxx'
try {
Remove-AzResourceGroup -Name $name -Force -Verbose -ErrorAction Stop
Write-Host "Resource group '$Name' was deleted successfully`n"
}
catch {
$exceptionMessage = $Error[0].Exception.Message.Split("-")[1].Trim()
Write-Warning "Failed to delete resource group '$Name' (Error: $exceptionMessage)`n"
}
Using “-AsJob
” and for loop
$getSaSplat = @{
Name = $saName
ResourceGroupName = $rgName
}
$sa = $null
try {
$sa = Get-AzStorageAccount @getSaSplat -ErrorAction Stop
}
catch {
Write-Warning $Error[0]
}
if ($null -eq $sa) {
$newSaSplat = $getSaSplat + @{
Location = $rgLocation
SkuName = $saSku
Kind = $saKind
}
try {
Write-Host "Stoarge Account '$saName' does not exist, creating new...`r`n"
New-AzStorageAccount @newSaSplat -Tag $tagsHashTable -ErrorAction Stop -AsJob | Out-Null
Write-Host "`r`n-------------------------------------------------------------------------------------------`r`n"
#Start-Sleep -Seconds 1
$sa = Get-AzStorageAccount @getSaSplat -ErrorAction SilentlyContinue
while ('Succeeded' -ne ${sa}?.ProvisioningState) {
Write-Host "[$(Get-Date -DisplayHint Time)] Storage account is not created yet -> ProvisioningState: $(${sa}?.ProvisioningState) `r`n"
Start-Sleep -Seconds 3
$sa = Get-AzStorageAccount @getSaSplat -ErrorAction SilentlyContinue
}
Write-Host "`r`n-------------------------------------------------------------------------------------------`r`n"
Write-Host "Stoarge Account '$saName' has been created `r`n"
}
catch {
Write-Warning $Error[0]
}
}
else {
Write-Host "Stoarge Account '$saName' already exists `r`n"
}
Keep Shell Window Open After Running Script
$xyz = ""
# ... ... ...
echo $xyz
#
# Per-script Fix: Add a prompt for input to the end of your script file. e.g. Read-Host -Prompt "Press Enter to exit"
#
Read-Host -Prompt "Press Enter to exit"
StackOverflow answer: https://stackoverflow.com/a/24620771/4802664
Test SQL Server Connetion
#
# Collected from: https://mcpmag.com/articles/2018/12/10/test-sql-connection-with-powershell.aspx
#
function Test-SqlConnection {
param(
[Parameter(Mandatory)]
[string]$ServerName,
[Parameter(Mandatory)]
[string]$DatabaseName,
[Parameter(Mandatory)]
[pscredential]$Credential
)
$ErrorActionPreference = 'Stop'
try {
$userName = $Credential.UserName
$password = $Credential.GetNetworkCredential().Password
$connectionString = 'Data Source={0};database={1};User ID={2};Password={3}' -f $ServerName,$DatabaseName,$userName,$password
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection $ConnectionString
$sqlConnection.Open()
## This will run if the Open() method does not throw an exception
$true
} catch {
$false
} finally {
## Close the connection when we're done
$sqlConnection.Close()
}
}
#
# Get server instance (Computer\Instance), run follwoing command in SSMS
# SELECT @@servername + '\' + @@servicename
# Get server name only: SELECT @@servername
#
Test-SqlConnection -ServerName 'SqlServerName' -DatabaseName 'AdventureWorksLT2019' -Credential (Get-Credential)
Surpressing output
New-Item -Path 'c:\newfolder' -ItemType Directory | Out-Null
# https://stackoverflow.com/a/51698384/4802664
Out-Null -InputObject ($(1..1000) | ?{$_ -is [int]})
#
# Note
# [x] | Out-Null -> one at a time
# Out-Null -InputObject [x] -> whole thing as a single object
#
Get help
Get-Help [command]
Get-Help [command] -Full
Get-Help [command] -Parameter *
# Examples
Get-Help Start-Service -Full
Get-Help Start-Service -Parameter *