PowerShell

Subpages


Table of Contents

 

 


Intro

Starting point to learn all about PowerShell


Documentation

 

 


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




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





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

 

  • 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