PowerShell
Subpages
Table of Contents
Â
- 1 Intro
- 2 Documentation
- 3 Cmdlet
- 4 PowerShell Modules
- 5 Visual Studio Add-Ons
- 6 My Public Repos
- 7 List Installed PowerShell Modules
- 8 How To Uninstall PowerShell Modules
- 9 Map An Azure File Share To A Drive
- 10 Tips And Tidbits
- 11 Get Running Directory
- 12 Get The Current Function Name
- 13 Directory And File Handling
- 13.1 Use -Filter
- 14 PowerShell Objects
- 15 Select
- 16 Test A Connection To IP And Port
- 17 Arrays
- 17.1 Simple Arrays
- 17.2 Multi-Dimensional Arrays
- 17.3 Hash Array
- 17.3.1 Create A Hash Array
- 18 Variables
- 19 Parameters
- 20 For-Loop
- 20.1 Multi-Line Text
- 20.1.1 Multi-Line Text
- 20.1 Multi-Line Text
- 21 Comparison Operators
- 22 Regular Expressions (RegEx)
- 23 Capturing All Output
- 23.1 Start-Transcript
- 24 Credential Prompting
- 25 Substituting A Token In A File
- 26 Executing Other Programs From IDE
- 27 Get An Access Token Using PowerShell
- 28 Testing A Connection (Similar to Ping)
- 29 Useful Tools
- 30 References
Â
Intro
Starting point to learn all about PowerShell
Documentation
Â
Microsoft's documentation:Â https://docs.microsoft.com/en-us/powershell/
PowerShell Gallery - The central repository for sharing and acquiring PowerShell code including PowerShell modules, scripts, and DSC resources
Â
Cmdlet
Create an Azure Resource using scripts in Azure PowerShell
A PowerShell command is called a cmdlet (pronounced "command-let"). A cmdlet is a command that manipulates a single feature. The term cmdlet is intended to imply "small command". By convention, cmdlet authors are encouraged to keep cmdlets simple and single-purpose.
Cmdlets follow a verb-noun naming convention; for example, Get-Process
, Format-Table
, and Start-Service
. There is also a convention for verb choice: "get" to retrieve data, "set" to insert or update data, "format" to format data, "out" to direct output to a destination, and so on.
Cmdlet authors are encouraged to include a help file for each cmdlet. The Get-Help
cmdlet displays the help file for any cmdlet.
Â
PowerShell Modules
Create an Azure Resource using scripts in Azure PowerShell
Cmdlets are shipped in modules. A PowerShell Module is a DLL that includes the code to process each available cmdlet. You'll load cmdlets into PowerShell by loading the module in which they're contained. You can get a list of loaded modules using the Get-Module
command:
PS C:\Users\Roger> get-module
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 2.7.2 Az.Accounts {Add-AzEnvironment, Clear-AzContext, Clear-AzDefault, Conn...
Script 0.0 chocolateyProfile {TabExpansion, Update-SessionEnvironment, refreshenv}
Manifest 3.1.0.0 Microsoft.PowerShell.Management {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Con...
Manifest 3.0.0.0 Microsoft.PowerShell.Security {ConvertFrom-SecureString, ConvertTo-SecureString, Get-Acl...
Manifest 3.1.0.0 Microsoft.PowerShell.Utility {Add-Member, Add-Type, Clear-Variable, Compare-Object...}
Manifest 3.0.0.0 Microsoft.WSMan.Management {Connect-WSMan, Disable-WSManCredSSP, Disconnect-WSMan, En...
Script 2.0.0 PSReadline {Get-PSReadLineKeyHandler, Get-PSReadLineOption, Remove-PS...
Az is the formal name for the Azure PowerShell module, which contains cmdlets to work with Azure features.
This module is an open-source component available on GitHub.
Â
Visual Studio Add-Ons
PowerShell Tools for Visual Studio from VS Market Place
My Public Repos
GitHub:Â Learning PowerShell (https://github.com/roger-cruz/learning-powershell)
Â
List Installed PowerShell Modules
Get-Module -ListAvailable
Directory: C:\Users\Roger\Documents\WindowsPowerShell\Modules
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 1.9.1 Az.Accounts {Disable-AzDataCollection, Disable-AzContextAutosave, Enab...
Script 1.9.0 Az.Accounts {Disable-AzDataCollection, Disable-AzContextAutosave, Enab...
Script 1.1.1 Az.Advisor {Get-AzAdvisorRecommendation, Enable-AzAdvisorRecommendati...
Script 1.1.3 Az.Aks {Get-AzAks, New-AzAks, Remove-AzAks, Import-AzAksCredentia...
Script 1.1.2 Az.Aks {Get-AzAks, New-AzAks, Remove-AzAks, Import-AzAksCredentia...
Script 1.1.4 Az.AnalysisServices {Resume-AzAnalysisServicesServer, Suspend-AzAnalysisServic...
Â
How To Uninstall PowerShell Modules
Adapted from here: How to uninstall Azure PowerShell modules
Â
Get-InstalledModule -Name Az -AllVersions -OutVariable AzVersions
($AzVersions |
ForEach-Object {
Import-Clixml -Path (Join-Path -Path $_.InstalledLocation -ChildPath PSGetModuleInfo.xml)
}).Dependencies.Name | Sort-Object -Descending -Unique -OutVariable AzModules
$AzModules |
ForEach-Object {
Remove-Module -Name $_ -ErrorAction SilentlyContinue
Write-Output "Attempting to uninstall module: $_"
Uninstall-Module -Name $_ -AllVersions
}
Â
I got an error:
Â
Find all modules' paths
Â
Follow the steps here: PowerShell 5.1 - How to uninstall module which is currently use
Â
Map An Azure File Share To A Drive
Â
Â
Tips And Tidbits
Change the error message's colors:Â https://winsmarts.com/fix-powershell-error-colors-14059255cd0
Test if a file exists
Get First 5 Lines Of A File
Start A NuGet Process And Wait For It To Finish
Get Running Directory
Â
Get The Current Function Name
Â
Directory And File Handling
Find all directories and subdirectories named "Output" and forcibly remove. In this example we pipe all of the directories and then filter using "where" to find the directories we want but you can also use the -Filter argument (see subsequent example).
You can also use the -Filter to find files matching a specific pattern (*.obj in the example below) and remove them.
Use -Filter
Another way to delete the directory and subdirectories, even if not empty (-Force)
Copy an entire directory, including subdirectories, to another location.
Â
PowerShell Objects
A real good article on manipulating objects, including how to get all of their members, properties:Â Â https://adamtheautomator.com/powershell-objects/
Convert object to JSON
You can output all objects as a comma-separated list via the -join command
Select
Use Select –ExpandProperty Name to have a stream of VALUES rather than a stream of OBJECTS
Test A Connection To IP And Port
Arrays
More info here: How-to: Create and use PowerShell Arrays
Simple Arrays
Mixed data types
Strongly typed array. Data types: string[], long[], bool[], int32[]
Multi-Dimensional Arrays
You can declare an MD array as shown here:
To iterate over it:
Hash Array
Create A Hash Array
Variables
Â
Use $ to declare a variable and = to assign a value.
Â
To obtain the value stored in a variable, use the $ prefix and its name
Variables can hold objects. For example, the following definition sets the adminCredential variable to the object returned by the Get-Credential cmdlet.
Â
Test For Undefined Or Empty String
Parameters
When you execute a script, you can pass arguments on the command line. You can provide names for each parameter to help the script extract the values.
Inside the script, you'll capture the values into variables. In this example, the parameters are matched by name:
You can omit the names from the command line. For example:
Inside the script, you'll rely on position for matching when the parameters are unnamed:
Â
For-Loop
Â
Â
Multi-Line Text
Multi-Line Text
Comparison Operators
The comparison operators are written -lt for "less than", -le for "less than or equal", -eq for "equal", -ne for "not equal", etc.
Regular Expressions (RegEx)
Capture the field inside parenthesis. Source:  Extract text from a string
Looks for ERROR at the beginning of the string in $result.
Capturing All Output
Use this command to capture the output of a script. Â
Start-Transcript
Unfortunately, output created by an EXE within the script is not captured by the Start-Transcript.
Credential Prompting
To prompt for credentials use:
Substituting A Token In A File
This replaces SUBSCRIPTION_ID with an actual ID.
Executing Other Programs From IDE
Executing another program within the PoSH IDE may give you this NativeCommandError:
This StackOverflow has a working answer:Â Error when calling 3rd party executable from Powershell when using an IDE
The error does not happen when the script is run directly, only when debugging it via IDE and only if an error is thrown.
Get An Access Token Using PowerShell
Â
Use a Windows VM system-assigned managed identity to access Resource Manager
get an access token for Azure Resource Manager.
extract the full response, which is stored as a JavaScript Object Notation (JSON) formatted string in the $response object.
extract the access token from the response.
call Azure Resource Manager using the access token.
Â
Â
Testing A Connection (Similar to Ping)
Useful Tools
PowerShell Script Analyzer and ISESteroids PSSharperÂ
References
Find the Directory Where Script Was Run:Â https://scriptingblog.com/tag/myinvocation-mycommand-path/
MS doc which covers a ranges of concepts about PowerShell:Â https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/?view=powershell-6