Azure Powershell

Documentation: Getting started with azure powershell

1. command lets: ex: get-command, get-azvm, get-azFirewall

2. verb-noun

3. verb: actions: get, set, etc

4. noun: resource types: vms, data factories, databases

5. command lets are inside modules that get loaded


Get-Command -Verb Get -Noun AzVM* -Module Az.Compute

1. verb: get

2. noun: command

3. options: -verb, -noun, -module

4. module: az.compute

*May be they are case sensitive! don't know yet

The module az.datafactory is documented here

Approved verbs are here

Working with managed identity through powershell for a data factory

Mastering azure cloud shell: article

1. When I invoked shell.azure.com it has created all the necessary assets like the storage account, resource group etc.

2. However it created it in a different location than I wanted.

3. i also don't know if this storage account is specific to a user or a group of users like at a subscription level!!

4. these are still things that need to be figured out

1. You search

2. how do you search? you use the following search commandlet

3. Get-command -verb get -noun *azdatafactory*

4. that will search for get commands whose name includes something to do with data factories

5. Then you can locate the documentation page for that commandlet. You can locate these command lets in the links provided in this document around azure powershell urls

Here is another way to search the available commandlets

Go here first:

Yet another way is

Then locate "Reference" on the left hand side to identify each module and commandlets with in that module and examples for each commandlet

1. Azure Cloud Shell is assigned per unique user account and automatically authenticated with each session

2. You can always remove the Cloud Shell by deleting the Azure resource group, which you used during that setup process.

3. One of the great features of Cloud Shell is that you will find many tools already installed; one of them is SSH. If you want to connect to your VM directly from the Azure portal using SSH, you can fire up Cloud Shell and do so. This makes managing Linux much more comfortable. You can create and deploy and manage virtual machines directly from your web browser.

4. Looks like there is some sort of a cloud drive that is attached. Need to know more here.

5. It has an editor based on the Visual Studio Code open-source project Monaco

6. A PowerShell provider allows any data store to be exposed like a file system as if it were a mounted drive. In other words, the data in your data store can be treated like files and directories so that a user can navigate data via cd or dir. SHiPS is a PowerShell provider. To be more precise it?s a provider utility that simplifies developing PowerShell providers.


//This will locate a datafactory
$df = Get-AzDataFactoryV2 
  -ResourceGroupName "some-resource-group" 
  -Name "some-datafactory-1"

//Notice the V2 at the end of Get-AzDatafactorV2

Use Get-AzDataFactoryV2 and not Get-AzDataFactory


Get-AzDataf

Now type tab to see the prompts

> $df = ....some code that locates the data factory
> $df (this will print that object now)

> $df.

//Notice the .

//Then press tab

DataFactoryId      Identity           
ProvisioningState  ResourceGroupName  
Equals             GetType

DataFactoryName    Location           
RepoConfiguration  Tags               
GetHashCode        ToString

Identity is a property

GetType is a method

So

1. $df.Identity

2. $df.GetType()


$df = Get-AzDataFactoryV2 -ResourceGroupname(name) -Name (datafactoryname)
$df.Identity

PrincipalId                          TenantId
-----------                          --------
2c97254a-a956-412a-8521-88bf61e6f956 e2ba767a-b27a-4f1d-b91a-309caf328df6

Get-AzADServicePrincipal -Objectid (principalid)

//You will get

ServicePrincipalNames : ....
ApplicationId         : app-id-is-here
ObjectType            : ServicePrincipal
DisplayName           : factory-name
Id                    : principal-id

thats why I had to jump the powershell hoops

Powershell extension for VSCode

Powershell itself is documented here

There is something here


//what is that command again with a Resource?
Az-GetCommand *azResource*

//ok I see it
Get-AzResource

//what kind of an object is an AzResource
//You can AzResource as a table with columns
Get-AzResource | Get-member

//Displays the members of Get-AzResource

//Explore the powershell core commands
Get-Command -module *core
Get-Module
Get-help
Get-command 
etc.

//Expore utility commands
Get-Command -module *utility
Get-member is here in this module

//Get all resources
Get-azResource

//Take a resource id of one of them
$res = Get-azResource -ResourceId res-id

//Print it out
$res

/*
You will notice that not all
properties are printed
*/

//You can explicity print it
//for example
$res.properties

//you can then also do
$res.properties.state

//You can then tell if this resource
//is running or not

Name                  MemberType
----                  ----------
Equals                    Method
GetHashCode               Method
GetType                   Method
ToString                  Method
ChangedTime             Property
CreatedTime             Property
ETag                    Property
ExtensionResourceName   Property
ExtensionResourceType   Property
Id                      Property
Identity                Property
Kind                    Property
Location                Property
ManagedBy               Property
Name                    Property
ParentResource          Property
Plan                    Property
Properties              Property
ResourceGroupName       Property
ResourceId              Property
ResourceName            Property
ResourceType            Property
Sku                     Property
SubscriptionId          Property
Tags                    Property
Type                    Property

Get-AzResource | Get-Member | Format-Table -Property name, membertype

Format-List
Format-Table
Format-Wide
Format-hex
Format-custom

//This prints in a list format
Get-AzResource

//You can change that
Get-AzResource | Format-Table

get-command
Get-Command -Verb Get -Noun AzVM* -Module Az.Compute
get-help
get-member
format-table 
format-table -Propert some-prop-name

get-help where -examples

Get-Service | Where-Object {$_.Status -eq "Stopped"}
Get-Service | where Status -eq "Stopped"

Get-Process | Where-Object {$_.WorkingSet -GT 25000*1024}
Get-Process | Where-Object WorkingSet -GT (25000*1024)

Get-Process | Where-Object {$_.ProcessName -Match "^p.*"}
Get-Process | Where-Object ProcessName -Match "^p.*"


-------- Example 4: Use the comparison statement format --------
Get-Process | Where-Object -Property Handles -GE -Value 1000
Get-Process | where Handles -GE 1000

--------- Example 5: Get commands based on properties ---------
# Use Where-Object to get commands that have any 
# value for the OutputType property of the command.
# This omits commands that do not have an OutputType 
#property and those that have an OutputType property, 
#but no property value.

Get-Command | where OutputType
Get-Command | where {$_.OutputType}

# Use Where-Object to get objects that are containers.
# This gets objects that have the 
#**PSIsContainer** property with a value 
# of $True and excludes all others.
Get-ChildItem | where PSIsContainer
Get-ChildItem | where {$_.PSIsContainer}

# Finally, use the Not operator (!) to 
#get objects that are not containers.
# This gets objects that do have 
#the **PSIsContainer** property and those 
#that have a value of $False for the **PSIsContainer** property.

Get-ChildItem | where {!$_.PSIsContainer}
# You cannot use the Not operator (!) in the 
#comparison statement format of the command.

Get-ChildItem | where PSIsContainer -eq $False

Here is more documentation on working with objects

-eq is equal to 1 -eq 1

-ne Is not equal to 1 -ne 2

-lt Is less than 1 -lt 2

-le Is less than or equal to 1 -le 2

-gt Is greater than 2 -gt 1

-ge Is greater than or equal to 2 -ge 1

-like Is like (wildcard comparison for text) "file.doc" -like "f*.do?"

-notlike Is not like (wildcard comparison for text) "file.doc" -notlike "p*.doc"

-contains Contains 1,2,3 -contains 1

-notcontains Does not contain 1,2,3 -notcontains 4


Get-AzResource | where {$_.name -like "*somename*"

//Tell me what is running in my account

$resources = Get-AzResource
foreach ($res in $resources) {
 $res1 = Get-AzResource -resourceid $res.resourceid
 if ($res1.properties.state -eq "Running")
 {
     $res1.name + " is running"
 }
}

Azure Cloudshell is documented here

where is the language reference for Microsoft Powershell?

Search for: where is the language reference for Microsoft Powershell?

There is some discussion on that here: SOF

Free ebooks for powershell

Here is a link to one of those books: PDF

what is $home in azure cloud shell?

Search for: what is $home in azure cloud shell?

How to create a new file in azure cloud shell editor?

Search for: How to create a new file in azure cloud shell editor?


{}

The default shell has the root as

Azure:
However for file shares do

cd $home

This will put me somewhere like

PS /home/satya

You will see here the files created by code

there is no icon or command

instead

On the command line 

make sure you are in 

PS /home/sayta> 

now type

code some-new-file.ps1

This creates a new file and opens it
in the editor

Azure cloud shell editor videos

Search for: Azure cloud shell editor videos

A good command: update-module powershell

Search for: A good command: update-module powershell

1. it is a linux based container

2. Understand azure dashboard and use one from the start

3. what is a file share in azure? Because cloudshell uses one.

4. wonder what cd $home different from cd cloudrive

5. dir seem to give diff results in bash and powershell

6. what is clouddrive/scripts? what is in there?

7. He may have created them before. There are .ps1 files and .cli files in his example

8. cli: seem to be just javascript objects

9. root directory in powershell is azure:\>

10. You can pipe to more all outputs

11. Get-module show me modules loaded

12. get-module -ListAvailable will show available modules. a longer list

13. Find-module *visualstudio will show visual studio module in the much longer registry

14. then you can do install-module...

1. cd $home is specific it seems to powershell

2. Not sure what $home here is.

3. Appears it is better to put files under the clouddrive directory

4. You can upload and download files from local drives through ui menus

5. Or use the Export-file commandlet

6. you can go to azure drive view by typing cd azure:. This is how you go there if you were to do cd $home and go to cloud drive.

7. Look into what Get-PSDrive is. Some kind of a provider. There are providers for file system, Azure, Environment, Function, Variables. Type Get-PSDrive to see this list

1. A cloudshell is really an entry point into a VM provided by azure. it creates a file share as well under a storage account using "file" as the storage type as opposed to blobs or a database. This storage is mounted on to the vm into a home directory and a sub directory called "clouddrive"

2. On this cloudshell vm not only can you see this "clouddrive" and other OS related directories (containing tools like git, java etc) but also a simulated directory tree under a drive called "azure:". This is provided by something calls SHiPS provider.

3. One can navigate azure: drive using a) dir b) cd ./some-.... c) tab to auto-fill long names in azure like subscriptions, resource groups, vms etc.

4. Get-Clouddrive is a command that tells the details of the mounted cloud drive

5. You can see the clouddrive as a directory in the azure portal under the "file" designation of the storage account. This file share then can be used to create new files or directories from the portal itself.

6. There appears to be an OS image in the storage account as well along with the tools that comprises the shell. (More research needed to speak more of this, but doesn't like such deeper knowledge is needed to understand the cloudshell.

7. In a way the "file" or file shares appear to be a similar kind of storage to "blobs" as a way to persist data. Of course there is difference.

1. Get_command gives details about a command. Looks like you can use comma separated list of these commands. An example

2. Get_command vi, emacs, nano, code: will provide commands that can invoke these commands from the command line of the shell

3. There is a plugin for VScode on your local machine. it is called "Azure Account". You can use this to "open." (via command pallette ctrl-shift-p) the azure cloud shell inside vscode without going to a browser. It is not clear yet if vscode so used will open files in local vscode (to be checked)

4. Get-Credentials is a commandlet that can be used to save userid/password credetials in a variable which can then be supplied to various other login commands as an input

What is equivalent to Get-ComputerInfo in azure cloudshell?

Search for: What is equivalent to Get-ComputerInfo in azure cloudshell?

Few cloudshell demo scripts from Git hub location of Thomas Maurer

A cloudshell blog

What is ITOpsTalk.com

Search for: What is ITOpsTalk.com

A link to ITOpsTalk.com

You can run powershell scripts from azure mobile portal as well.

Some powershell material from Pluralsight:John Savill

can you mount azure cloud drive as a local drive windows?

Search for: can you mount azure cloud drive as a local drive windows?

Documentation: How to use an azure file share on windows


Get-command
Get-Command -Verb Get -Noun AzVM* -Module Az.Compute
Get-Command vi, nano, code, emacs

Get-help Get-command

Get-member
Get-AzResource | Get-member 

Format-table 
Format-table -Propert some-prop-name
Get-AzResource | Format-table ..options

Where
Where-Object
Get-AzResource | Where-Object....

Get-Module #installed modules
Get-Module -ListAvailable #Show all available ones
Find-Module
Install-Module

Export-file
Get-CloudDrive
Get-Credentials

#doesnt appear to be in CloudShell
Get-ComputerInfo

1. Go to shell.azure.com

2. Locate the icon at the top for upload/download files

3. click on it

4. you will see a drop down

5. there is an item called "Manage file share"

6. that menu option will take you to the file share location in the portal in a separate browser window

Documentation: How to debug azure file share problems

command let for powershell version

Search for: command let for powershell version

here is a discussion on SOF on this

1. It is not a commandlet to get the version

2. Instead, apparently there are built in variables

3. $PSVersionTable will print the version

4. To know what variables are available use the commandlet Get-Variable


args                      
ConfirmPreference         
ConsoleFileName           
DebugPreference           
Error                     
ErrorActionPreference     
ErrorView                 
ExecutionContext          
false                     
FormatEnumerationLimit    
HOME                      
Host                      
InformationPreference     
input                     
MaximumAliasCount         
MaximumDriveCount         
MaximumErrorCount         
MaximumFunctionCount      
MaximumHistoryCount       
MaximumVariableCount      
MyInvocation              
NestedPromptLevel         
null                      
OutputEncoding            
PID                       
PROFILE                   
ProgressPreference        
PSBoundParameters         
PSCommandPath             
PSCulture                 
PSDefaultParameterValues  
PSEdition                 
PSEmailServer             
PSHOME                    
PSScriptRoot              
PSSessionApplicationName  
PSSessionConfigurationName
PSSessionOption           
PSUICulture               
PSVersionTable            
PWD                       
ShellId                   
StackTrace                
true                      
VerbosePreference         
WarningPreference         
WhatIfPreference

#Show all aliases
Get-Alias 

#Show aliases starting with letter g
Get-Alias g*

Get-Module | Format-Table -property name

Microsoft.PowerShell.Management
Microsoft.PowerShell.Utility   
PSReadline

Here is how to install azure powershell module

What is PSGallery?

Search for: What is PSGallery?

To see the examples, type: "get-help Set-AzContext -examples".

For more information, type: "get-help Set-AzContext -detailed".

For technical information, type: "get-help Set-AzContext -full".

For online help, type: "get-help Set-AzContext -online"

How to see current subscription in azure powershell

Search for: How to see current subscription in azure powershell

Get-AzContext


https://docs.microsoft.com/en-us
/powershell
/module
/az.accounts
/get-azcontext

Az.Accounts is an important module


#Login
Connect-AzAccount

#Get a list of valid subscriptions
Get-AzSubscription

#See what is your current subscription
Get-AzContext

#Change to the desired subscription
Set-AzSubscription -subscription "sub-name"

#See the current subscription again
Get-AzContext

//locate your directory
cd some-dir

//see files
dir test1.ps

//run it. This will not work
test1.ps

//but this will
./test1.ps

A .ps1 utility to debug file shares


Install-Module -Name Az -AllowClobber -Scope AllUsers

Az.Accounts
Az.Billing
Az.Storage
CimCmdlets
DnsClient
Microsoft.PowerShell.Management
Microsoft.PowerShell.Security
Microsoft.PowerShell.Utility
Microsoft.WSMan.Management
NetAdapter
NetSecurity
NetTCPIP
PackageManagement
PowerShellGet
PSReadline
SmbShare

Using Git in cloudshell via personal access token is first mentioned here

Using Git credentials in Azure cloudshell

Search for: Using Git credentials in Azure cloudshell

How to enter command with password for git pull?

String processing in Powershell

Search for: String processing in Powershell

Microsoft Devblogs: Variable expansion in strings and here-strings

windows powershell is documented here (not azure)

writing commandlets is here

writing functions is documented here

variable scope is documented here

Operators

If clause

More on functions and if statement

There are some howto guides here

Article: The Complete Guide to PowerShell Punctuation

calling functions through Grouping Expression in powershell

Search for: calling functions through Grouping Expression in powershell


#wrong
"Some string" + somefunc("hello")

#still wrong
"Some string" + somefunc "hello"

#still wrong
"Some string $(somefunc("hello")"

#Good: Group the func
"Some string" + (somefunc "hello")

#Good: Or another grouping
"Some string $(somefunc "hello")"

Comparison operators


function getEnvVariable($name)
{
    #Do this silently -ErrorAction ignore
    $value = Get-ChildItem -Path "Env:$name" -ErrorAction Ignore
    return $value
}

use the -ErrorAction Ignore

function setEnvVariaable ($name, $value)
{
    Set-Item -Path "Env:$name" -Value $value -ErrorAction Ignore
}

function main {

    $what = Read-Host -Prompt "What command: reset, show, set, otherwise"
    if ($what -eq "reset")
    {
        Write-Host "Resetting token"
        resetAccessToken
        return
    }
    elseif ($what -eq "show")
    {
        Write-Host "Showing the Access token that is in the enviornment"
        showAccessToken
        return
    }
    elseif ($what -eq "set")
    {
        Write-Host "Prompt and set the variable"
        clone
        return
    }
    Write-Host "Default. Nothing to be done"
}

Beware the behavior of implicit returns in powershell functions

Search for: Beware the behavior of implicit returns in powershell functions


#Call a function that returns a string
#normally....
$curDir = getCurDir

#You can do this instead
#as needed
[String]$curDir = getCurDir

#Then vscode will tell you
#the properties and functions of String class
#Example
$curDir.

Here is sample code article I posted on linkedin


#Get an element from an ordered dictionary
 function getADirectory ($seq) {
     [System.Collections.Hashtable]$d = $dirDictionary;
     [System.Collections.ICollection]$list = $d.Keys
     [string[]]$keyList = @($list.GetEnumerator())
     $keyList.Get($seq)
 }

We use hashtables, arrays and strings often in powershell script

It is good to know their types

This helps vscode to tell what methods are available on these variables

Especially the first time users

You can declutter the code later

These are useful not for maintenance but for first time coding

Once you are well vesed, you will remember the methods

For the reader that comes later, it is not necessary to know the types but just the method names. this is one way to navigate between typed and typeless environments

Sometime using commandlet | Get-Member will tell you

But it is not possible all the time

Look up the powershell language reference to see the type used

Typically this type looks like "System.Collections..Hashtable"

If the vscode won't tell you the type returned by say "GetEnumerator", just google that type name and that will point to a C# class reference in .net at microsoft. Now you can tell the types returned

Plug that type name in vscode editor. now the editor will tell you the methods that you can cross check from web reference


#Count number of aliases

alias | Measure-Object
alias | Measure-Object -Property name

Docs on Measure-Object

Language reference for module powershell.utility


#Investigate the object type of an alias

#Why retrieve all aliases? Just get a few

alias | Select-Object -First 5  | get-member