Posts tagged “Powershell

Get-SBADUser function added to AZSBTools PowerShell module


Get-SBADUser function has been added to the AZSBTools PowerShell module to provide details on Active Directory user objects. This comes in handy when you need to list AD users but do not have Active Directory PowerShell module or do not have the necessary permissions to login to a Domain Controller.

  • This function must be run from a domain-joined computer
  • This function does not require or depend on the Active Directory PowerShell module
  • This function does not require permission/rights to login or connect to a Domain Controller
  • Other than console output, the function will return no output if the provided group does not exist
  • If a user samaccountname is specified as a parameter the function will return output similar to:
  • If the function is used without any parameters, it will return information on all AD users in the current domain

To use the AZSBTools PowerShell module which is available in the PowerShell Gallery, you need PowerShell 5. To view your PowerShell version, in an elevated PowerShell ISE window type

$PSVersionTable

To download and install the latest version of AZSBTools from the PowerShell Gallery and its dependencies, type

Set-PSRepository -Name PSGallery -InstallationPolicy Trusted

To trust the Microsoft PowerShell Gallery repository, then

Install-Module AZSBTools,Az -Force -AllowClobber -Scope CurrentUser

AZSBTools contains functions that depend on Az module, and they’re typically installed together.

To load the AZSBTools, and Az modules type:

Import-Module AZSBTools,Az -DisableNameChecking

To view a list of cmdlets/functions in AZSBTools, type

Get-Command -Module AZSBTools

To view the built-in help of one of the AZSBTools functions/cmdlets, type

help <function/cmdlet name> -show

such as

help New-SBAZServicePrincipal -show


Get-SBADGroupMembers function added to AZSBTools PowerShell module


Get-SBADGroupMembers function has been added to the AZSBTools PowerShell module to provide member list information for Active Directory group objects including members of sub-groups. This function does not depend on or require Active Directory PowerShell module or the necessary permissions to login to a Domain Controller.

  • This function must be run from a domain-joined computer
  • This function does not require or depend on the Active Directory PowerShell module
  • This function does not require permission/rights to login or connect to a Domain Controller
  • The function returns output similar to:

So this function’s emphasis is not on the provided group information such as it’s DN (Distinguished Name), OU (Organizational Unit), … Group properties can be obtained via the Get-SBADGroup function. The emphasis of Get-SBADGroupMembers is on a group’s member users, and whether a user is a direct member of the given group, or a member of a subgroup.

The ‘MemberOf’ field provides that visibility by listing the group hierarchy of each member user separated by dots. In the example above, testuser2 is member of testgroup2.testgroup1 which indicates that he’s a member of testgroup2 AD group which is a member of testgroup1 AD group. In the same example above, testuser1 is a direct member of testgroup1 AD group.


To use the AZSBTools PowerShell module which is available in the PowerShell Gallery, you need PowerShell 5. To view your PowerShell version, in an elevated PowerShell ISE window type

$PSVersionTable

To download and install the latest version of AZSBTools from the PowerShell Gallery and its dependencies, type

Set-PSRepository -Name PSGallery -InstallationPolicy Trusted

To trust the Microsoft PowerShell Gallery repository, then

Install-Module AZSBTools,Az -Force -AllowClobber -Scope CurrentUser

AZSBTools contains functions that depend on Az module, and they’re typically installed together.

To load the AZSBTools, and Az modules type:

Import-Module AZSBTools,Az -DisableNameChecking

To view a list of cmdlets/functions in AZSBTools, type

Get-Command -Module AZSBTools

To view the built-in help of one of the AZSBTools functions/cmdlets, type

help <function/cmdlet name> -show

such as

help New-SBAZServicePrincipal -show


Get-SBADGroup function added to AZSBTools PowerShell module


Get-SBADGroup function has been added to the AZSBTools PowerShell module to provide details on Active Directory group objects including its members. This comes in handy when you need to list AD group members but do not have Active Directory PowerShell module or do not have the necessary permissions to login to a Domain Controller.

  • This function must be run from a domain-joined computer
  • This function does not require or depend on the Active Directory PowerShell module
  • This function does not require permission/rights to login or connect to a Domain Controller
  • The function will return no output if the provided group does not exist
  • If a group is specified as a parameter the function will return output similar to:
  • If the function is used without any parameters, it will return information on all AD groups in the current domain:

To see group members including sub-groups use the Get-SBADGroupMembers function.


To use the AZSBTools PowerShell module which is available in the PowerShell Gallery, you need PowerShell 5. To view your PowerShell version, in an elevated PowerShell ISE window type

$PSVersionTable

To download and install the latest version of AZSBTools from the PowerShell Gallery and its dependencies, type

Set-PSRepository -Name PSGallery -InstallationPolicy Trusted

To trust the Microsoft PowerShell Gallery repository, then

Install-Module AZSBTools,Az -Force -AllowClobber -Scope CurrentUser

AZSBTools contains functions that depend on Az module, and they’re typically installed together.

To load the AZSBTools, and Az modules type:

Import-Module AZSBTools,Az -DisableNameChecking

To view a list of cmdlets/functions in AZSBTools, type

Get-Command -Module AZSBTools

To view the built-in help of one of the AZSBTools functions/cmdlets, type

help <function/cmdlet name> -show

such as

help New-SBAZServicePrincipal -show


Resizing managed VM disks in Azure


Executive summary:

  • As of 7 March 2019, Microsoft allows resizing data and OS managed disks up via PowerShell and the Azure Portal
  • Microsoft does not allow resizing managed disks down
  • Disk resizing requires VM shutdown and restart

Microsoft charges for the entire amount of allocated disk space of managed disks.

Also see the example in this post.

This is a major difference compared to unmanaged disks where Microsoft charges only for used disk space. IT professionals now have to walk a tight rope in terms of disk capacity in Azure. On one hand you need a minimum amount of free disk space on each disk to guard against running out of disk space scenarios, on the other hand you need to keep the overall disk size as small as possible to avoid the high disk cost. Currently Microsoft charges for managed disk capacity as follows (East US, standard LRS)

For example, if we have a VM with 100 GB data disk – 50 GB are used, we’re billed for S10 which is the next size up in the amount of $5.89/month.

As data grows over time, we may need to expand this disk. We can resize a managed data disk using Powershell as follows:

First we declare the needed variables, and authenticate to our Azure subscription:

#Requires -Version 5
#Requires -Modules AzureRM,AZSBTools

# Install-Module AZSBTools

$LoginName           = 'myname@domain.com'
$SubscriptionName    = 'my subscription name'
$Location            = 'EastUS'
$UseCase             = 'TestMD2'

$VMParameterList = @{
    Name                = "$UseCase-VM"
    ResourceGroupName   = "$UseCase-RG"
    Location            = $Location
    VirtualNetworkName  = "$UseCase-Vnet"
    SubnetName          = "$UseCase-Subnet"
    PublicIpAddressName = "$UseCase-PiP"
    OpenPorts           = @(80,3389)
    Credential          = (Get-SBCredential 'myVMAdmin') 
    Size                = 'Standard_D1_v2'       # Get-AzureRmVMSize -Location $Location
    DataDiskSizeInGb    = 128 
}

Login-AzureRmAccount -Credential (Get-SBCredential $LoginName) | Out-Null # -Environment AzureCloud 
Get-AzureRmSubscription -SubscriptionName $SubscriptionName -WA 0 | 
    Set-AzureRmContext | Out-Null 

Next we provision our test VM:

$Duration = Measure-Command { $VM = New-AzureRmVM @VMParameterList }
Write-Log 'Done in',"$($Duration.Hours):$($Duration.Minutes):$($Duration.Seconds) hh:mm:ss" Green,Cyan
Write-Log ' OS Disk (Managed): size',"$($VM.StorageProfile.OsDisk.DiskSizeGB) GB",'- Underlying storage',$VM.StorageProfile.OsDisk.ManagedDisk.StorageAccountType Green,Cyan,Green,Cyan
$VM.StorageProfile.DataDisks | foreach { 
    Write-Log ' Data Disk (Managed): Lun',$_.Lun,'- size',"$($_.DiskSizeGB) GB" Green,Cyan,Green,Cyan
} 

and we get output like:

Next we RDP to the test VM and write test data to the data disk:

$IPv4Address = (Get-AzureRmPublicIpAddress -ResourceGroupName $VM.ResourceGroupName -Name "$UseCase-PiP").IpAddress  
mstsc /v:$IPv4Address

After login to the VM, we partition and format the data disk:

and write test data to drive f:

Back in Powershell, we resize the data disk. This requires stopping the VM and starting it back up:

$DataDisk = Get-AzureRmDisk -ResourceGroupName $VM.ResourceGroupName -DiskName $VM.StorageProfile.DataDisks[0].Name
Write-Log 'Data disk size:',"$($DataDisk.DiskSizeGB) GB",'stopping VM..' Green,Cyan,Green -NoNew
$VM | Stop-AzureRmVM -Force | Out-Null
do { Start-Sleep -Seconds 10 } while (
    (Get-AzureRmVM -ResourceGroupName $VM.ResourceGroupName -Name $VM.Name -Status).Statuses[1].DisplayStatus -ne 'VM deallocated'
)
Write-Log 'Done' Cyan
Write-Log 'Resizing disk',$VM.StorageProfile.DataDisks[0].Name,'to 250 GB' Green,Cyan,Green -NoNew
New-AzureRmDiskUpdateConfig -DiskSizeGB 250 | Update-AzureRmDisk -ResourceGroupName $VM.ResourceGroupName -DiskName $VM.StorageProfile.DataDisks[0].Name
Write-Log 'Done' Cyan
$DataDisk = Get-AzureRmDisk -ResourceGroupName $VM.ResourceGroupName -DiskName $VM.StorageProfile.DataDisks[0].Name
Write-Log 'New data disk size:',"$($DataDisk.DiskSizeGB) GB" Green,Cyan
Write-Log 'Starting VM',$VM.Name Green,Cyan -NoNew
$VM | Start-AzureRmVM | Out-Null
Write-Log 'Done' Green
mstsc /v:$IPv4Address

and we get output like

Back in the VM we see the new disk size:

We extend the volume to use all provisioned space:

And validate the data.

We cannot however use the same process in reverse to down size a disk.

We can resize the volume down inside the VM:

In Computer Management/Disk Management, we shrink the volume down to 60 GB

Note: To reduce storage cost, shrink the volume to a size that’s just below a billing size. The current billing disk sizes are 32 GB, 64 GB, 128 GB, 256 GB, 512 GB, 1 TB, 2 TB, 4 TB, 8 TB, 16 TB, and 32 TB

Shrinking the disk in Windows:

Back in PowerShell, after shutting down and deallocating the VM, if we try resize the disk down:

We can also resize the OS disk up but not down:


Remove-AzureRMVMBackup function added to AZSBTools PowerShell module


Remove-AzureRMVMBackup function has been added to the AZSBTools PowerShell module to simplify the task of locating and deleting Azure VM backups. The function also disables backup for the provided VM. This function works with both ARM and classic ASM VMs

This is helpful to do before deleting a retired Azure VM.

Remove-AzureRMVMBackup

This function will disable backup of the provided VM. It will also delete existing backups (recovery points – files) of the VM.

Example:

$ParameterList = @{
    LoginName = 'sam@dmain.com'
    SubscriptionName = 'my subscription name'
    VMName = 'Widget3VM'
}
Remove-AzureRMVMBackup @ParameterList

 


To use the AZSBTools PowerShell module which is available in the PowerShell Gallery, you need PowerShell 5. To view your PowerShell version, in an elevated PowerShell ISE window type

$PSVersionTable

To download and install the latest version of AZSBTools from the PowerShell Gallery and its dependencies, type

Set-PSRepository -Name PSGallery -InstallationPolicy Trusted

To trust the Microsoft PowerShell Gallery repository, then

Install-Module AZSBTools,AZ -Force -AllowClobber

AZSBTools contains functions that depend on AZ modules, and they’re typically installed together.

To load the AZSBTools, and AZ modules type:

Import-Module AZSBTools,AZ -DisableNameChecking

To view a list of cmdlets/functions in AZSBTools, type

Get-Command -Module AZSBTools

To view the built-in help of one of the AZSBTools functions/cmdlets, type

help <function/cmdlet name> -show

such as

help New-SBAZServicePrincipal -show


Unmanaged Azure Disk Snapshot functions added to AZSBTools PowerShell module to View, Add, Delete


3 new functions have been added to the AZSBTools PowerShell module to view, add, and delete snapshots of unmanaged Azure disks

The AzureRM.Compute PowerShell module (v 5.9.1 as of 1 Jan 2019) provides the Get-AzureRmSnapshotNew-AzureRmSnapshot,  and Remove-AzureRmSnapshot cmdlets to handle disk snapshots of managed disks. Although the same snapshot capabilities are available for unmanaged disks, there are no PS cmdlets to provide similar functionality for unmanaged disk snapshots.

Managed versus unmanaged disks

Managed Disks handle the storage account creation/management to avoid hitting the 20k IOPS standard storage account limit for example (no more than 40 standard disks in the same Storage Account @ 500 IOPS each). This is a pretty nice feature but it comes at a steep price. Consider Standard LRS USEast region pricing for example. A 1 TB data disk (S30) is $40.96/month

If we use 10 GB of this disk we pay $41/month even if we power off and deallocate the VM. We still pay the $41/month for this 1 TB disk including the 990 GB unused space.

In comparison, the same 1 TB unmanaged disk using the same 500 IOPS with 10 GB of used space costs $0.45/month (10 GB * $0.045 per GB).

This is because we’re billed only for the 10 GB used space not the 1023 GB allocated space, whether the VM is up and running or powered off and deallocated.

In short, managed disks come at the cost of paying for allocated space not used space. Given that used space is often as little as 1% of the allocated space, I highly recommend against using managed disks at this time (1 Jan 2019)

Well, using my own advise I find it hard to use unmanaged disks via PowerShell to perform routine Azure infrastructure management tasks such as:

  • Determine the amount of used disk space (separate post on that)
  • Manage disk snapshots; list, create, delete (the subject of this post)
  • Convert managed to unmanaged disk (separate post on that)

The functions Get-AzureRMUnmanagedDiskSnapshot, New-AzureRMUnmanagedDiskSnapshot, and Remove-AzureRMUnmanagedDiskSnapshot have been added to the AZSBTools module to simplify management of unmanaged disk snapshots via PowerShell. These functions do not affect the VM lease on its disk(s), do not require VM shutdown, and do not interfere with VM operation.

Get-AzureRMUnmanagedDiskSnapshot

This function will list disk snapshots for a given unmanaged disk. This applies to unmanaged ARM disk snapshots only not classic ASM disks or managed ARM disks. This function depends on the AzureRM and Azure PowerShell modules available in the PowerShell Gallery. To install required module: Install-Module AzureRM, Azure 

Example:

$ParameterList = @{
    LoginName = 'sam@dmain.com'
    SubscriptionName = 'my subscription name'
    StorageAccountName = 'storfluxwidget3vm'
    ContainerName = 'vhds'
    BlobName = 'Widget3VM-20181226-093810.vhd'
}
Get-AzureRMUnmanagedDiskSnapshot @ParameterList

To list snapshots in a given time frame, we filter on the SnapshotTime property of the output provided by this function. This function returns objects of type Microsoft.WindowsAzure.Storage.Blob.CloudPageBlob for each snapshot found that matches the provided storageaccount/container/blob parameters. The SnapshotTime property is of type DateTimeOffset which cannot be compared directly to DateTime type. To do the required filtering/comparison, we use the [DateTimeOffset].ToLocalTime{() method as in:

Get-AzureRMUnmanagedDiskSnapshot @ParameterList | 
    where { [DateTime]$_.SnapshotTime.ToLocalTime().ToString() -GE [DateTime]'2019-01-02 8:45' }

This will list snapshots taken at or after 2 Jan 2019 8:45 (am local time)

New-AzureRMUnmanagedDiskSnapshot

This function will create new disk snapshot for a given unmanaged disk.

Example:

$ParameterList = @{
    LoginName = 'sam@dmain.com'
    SubscriptionName = 'my subscription name'
    StorageAccountName = 'storfluxwidget3vm'
    ContainerName = 'vhds'
    BlobName = 'Widget3VM-20181226-093810.vhd'
}
New-AzureRMUnmanagedDiskSnapshot @ParameterList

Remove-AzureRMUnmanagedDiskSnapshot

This function will remove one or more disk snapshots for a given unmanaged disk. In addition to the 5 parameters LoginName, SubscriptionName, StorageAccountName, ContainerName, and BlobName that this group of functions take, this function also takes 2 additional parameters; FromDate and ToDate. These 2 parameters allow us to delete snapshots taken duing a given time frame.

Example:

$ParameterList = @{
    LoginName = 'sam@dmain.com'
    SubscriptionName = 'my subscription name'
    StorageAccountName = 'storfluxwidget3vm'
    ContainerName = 'vhds'
    BlobName = 'Widget3VM-20181226-093810.vhd'
}
Remove-AzureRMUnmanagedDiskSnapshot @ParameterList

This deletes all disk snapshots for the provided unmanaged disk in the provided StorageAccount/Container

 


To use the AZSBTools PowerShell module which is available in the PowerShell Gallery, you need PowerShell 5. To view your PowerShell version, in an elevated PowerShell ISE window type

$PSVersionTable

To download and install the latest version of AZSBTools from the PowerShell Gallery and its dependencies, type

Set-PSRepository -Name PSGallery -InstallationPolicy Trusted

To trust the Microsoft PowerShell Gallery repository, then

Install-Module AZSBTools,AzureRM -Force -AllowClobber

AZSBTools contains functions that depend on AzureRM modules, and they’re typically installed together.

To load the AZSBTools, and AzureRM modules type:

Import-Module AZSBTools,AzureRM -DisableNameChecking

To view a list of cmdlets/functions in AZSBTools, type

Get-Command -Module AZSBTools

To view the built-in help of one of the AZSBTools functions/cmdlets, type

help <function/cmdlet name> -show

such as

help New-SBAZServicePrincipal -show


Page File functions added to AZSBTools PowerShell module to Get, Set, Remove page file(s)


3 new functions have been added to the AZSBTools PowerShell module to view, create and modify page file settings on a Windows computer running Windows 2008/Windows 7 and above versions.

Get-PageFile

This simple function takes no parameters and returns a PS custom object for each page file that has the following 3 properties:

  • DriveLetter: such as ‘c’, or ‘e’, …
  • InitialSizeMB: such as 1024 (0 value indicates a system-managed page file)
  • MaximumSizeMB: such as 4096 (0 value indicates a system-managed page file)

For example:

Set-PageFile

This function changes the page file setting on a given drive letter to the specified initial and maximum size in MB. It takes one parameter that’s similar to the PS custom object returned by the Get-PageFile function.

The -PageFile parameter of the Set-PageFile function accepts a PS Custom Object containing the following 3 properties:

  • DriveLetter such as ‘c’
  • InitialSizeMB such as 1024 (0 value indicate system managed page file)
  • MaximumSizeMB such as 4096 (0 value indicate system managed page file)

This object can be constructed manually as in:

$PageFile = [PSCustomObject]@{
    DriveLetter   = 'c'
    InitialSizeMB = 0 
    MaximumSizeMB = 0 
}

or obtained from the Get-PageFile function

For example, to configure all page files on all drives to system managed size:

Get-PageFile | foreach { $_.InitialSizeMB = 0; $_.MaximumSizeMB = 0; $_ } | Set-PageFile

Note that changes to page file require a reboot to take effect. Rebooting is not part of this function.

Remove-PageFile

Finally this simple function will remove page file from a given drive. It takes one parameter being the drive letter such as ‘e’

The 3 functions can be used in user scripts to move page file from one drive to another. For example:

Set-PageFile -PageFile ([PSCustomObject]@{
    DriveLetter   = 'e' 
    InitialSizeMB = 0
    MaximumSizeMB = 0
})
Remove-PageFile 'c' -EA 0 


To use the AZSBTools PowerShell module which is available in the PowerShell Gallery, you need PowerShell 5. To view your PowerShell version, in an elevated PowerShell ISE window type

$PSVersionTable

To download and install the latest version of AZSBTools from the PowerShell Gallery and its dependencies, type

Set-PSRepository -Name PSGallery -InstallationPolicy Trusted

To trust the Microsoft PowerShell Gallery repository, then

Install-Module AZSBTools,AzureRM -Force -AllowClobber

AZSBTools contains functions that depend on AzureRM modules, and they’re typically installed together.

To load the AZSBTools, and AzureRM modules type:

Import-Module AZSBTools,AzureRM -DisableNameChecking

To view a list of cmdlets/functions in AZSBTools, type

Get-Command -Module AZSBTools

To view the built-in help of one of the AZSBTools functions/cmdlets, type

help <function/cmdlet name> -show

such as

help New-SBAZServicePrincipal -show


Azure Automation – getting started


Azure Automation allows Azure administrators to run PowerShell and other scripts against an Azure subscription. They provide several benefits versus running the same scripts from the user desktop computer including:

  • Scripts run in Azure and are not dependent on the end-user desktop
  • Scripts are highly available by design.
  • Scheduling is a built-in feature
  • Authentication is streamlined for both classic ASM and current ARM resources

To get started with Azure Automation;

  1. Create an Azure Automation account
  2. Install needed PowerShell modules
  3. Create, run, test, schedule scripts

Create an Azure Automation account

In the current portal, Create Resource > Monitoring and Management > Automation > Create

In the ‘Add Automation Account’ blade enter/select a name for the Automation Account, Azure Subscription, Resource Group, and Azure Location

Azure will take a few minutes to create the automation account and associated objects.

We can now run scripts against the Azure subscription selected above. Here are some examples:

Create a test script

In the Automation Account blade, click Runbooks

Click ‘Add a runbook’ link on the top to create a new runbook of type PowerShell

Azure creates the runbook/script, and opens the ‘Edit PowerShell Runbook’ blade

Type in the desired command, click Save, then ‘Test pane’

In the ‘Test’ blade, click ‘Start’. Azure will queue and execute the script

Notes:

  • This is not like the PowerShell ISE. There’s no auto-completion for one thing.
  • If Azure comes across a bad command, it will try to execute THE ENTIRE SCRIPT repeatedly, and is likely to get stuck.
  • This shell does not support user interaction. So, any cmdlet that would typically require a user confirmation/interaction of any type will fail. For example, Install-Module cmdlet will fail since it requires user approval/interaction to install PowerShellGet.

Install needed modules

To see available modules click ‘Modules’ in the Automation Account blade

Click ‘Browse Gallery’ on top and search for the desired module

These modules come for the Microsoft PowerShell Gallery.

Click on the desired module, view its functions, and click Import to import it to this automation shell

Now that the module is imported, we can use it in scripting in this particular automation shell:

 

 


Expand-Json cmdlet to expand custom PowerShell object in a more readable format added to AZSBTools PowerShell module


Microsoft Azure REST API version 2 (ARM – Azure Resource Manager) takes input request body and returns output in JSON format. Consequently, Azure PowerShell cmdelts and Azure CLI tend to use similar JSON objects for input, also known as ARM Templates.

For example, using this PowerShell cmdlet:

Get-AzureRmResource -ResourceId /subscriptions/xxxxx/resourceGroups

where xxxxx is your Azure subscription Id, may return output similar to:

Name : prod-mgt
ResourceId : /subscriptions/xxxxx/resourceGroups/prod-mgt
ResourceGroupName : prod-mgt
Location : eastus
SubscriptionId : xxxxx
Properties : @{provisioningState=Succeeded}

Name : TestAuto1
ResourceId : /subscriptions/xxxxx/resourceGroups/TestAuto1
ResourceGroupName : TestAuto1
Location : westeurope
SubscriptionId : xxxxx
Properties : @{provisioningState=Succeeded}

What the PowerShell cmdlet did is to send a GET request to the Azure Management API that looks partially like:

https://management.azure.com/subscriptions/xxxxx/resourceGroups?api-version=2014-04-01

Which returned JSON output similar to:

{
  "value": [
    {
      "id": "/subscriptions/xxxxx/resourceGroups/prod-mgt",
      "name": "prod-mgt",
      "location": "eastus",
      "properties": {
        "provisioningState": "Succeeded"
      }
    },
    {
      "id": "/subscriptions/xxxxx/resourceGroups/TestAuto1",
      "name": TestAuto1
      "location": "westeurope",
      "properties": {
        "provisioningState": "Succeeded"
      }
    }
  ]
}

In the course of working with Azure ARM templates, such as this template to create a Storage Account:

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "storageAccountType": {
      "type": "string",
      "defaultValue": "Standard_LRS",
      "allowedValues": [
        "Standard_LRS",
        "Standard_GRS",
        "Standard_ZRS",
        "Premium_LRS"
      ],
     "metadata": {
       "description": "Storage Account type"
     }
   }
  },
  "variables": {
    "storageAccountName": "[concat(uniquestring(resourceGroup().id), 'standardsa')]"
  },
  "resources": [
    {
      "type": "Microsoft.Storage/storageAccounts",
      "name": "[variables('storageAccountName')]",
      "apiVersion": "2016-01-01",
      "location": "[resourceGroup().location]",
      "sku": {
        "name": "[parameters('storageAccountType')]"
      },
      "kind": "Storage", 
      "properties": {
      }
    }
  ],
  "outputs": {
    "storageAccountName": {
      "type": "string",
      "value": "[variables('storageAccountName')]"
    }
  }
}

It may not be very clear what are the objects in the template and their hierarchy. Using the ConvertFrom-Json cmdlet of the Microsoft.PowerShell.Utility module produces a PS custom object with display similar to:

Get-Content E:\Scripts\ARMTemplates\Storage1.json | ConvertFrom-Json

$schema : https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#
contentVersion : 1.0.0.0
parameters : @{storageAccountType=}
variables : @{storageAccountName=[concat(uniquestring(resourceGroup().id), ‘standardsa’)]}
resources : {@{type=Microsoft.Storage/storageAccounts; name=[variables(‘storageAccountName’)]; apiVersion=2016-01-01; location=[resourceGroup().location]; sku=; kind=Storage; properties=}}
outputs : @{storageAccountName=}

This is better but it doesn’t show some of the information in the source JSON file/ARM template. The new Expand-Json cmdlet further expands the ConvertFrom-Json output:

Get-Content E:\Scripts\ARMTemplates\Storage1.json | ConvertFrom-Json | Expand-JSON


To use the AZSBTools PowerShell module which is available in the PowerShell Gallery, you need PowerShell 5. To view your PowerShell version, in an elevated PowerShell ISE window type

$PSVersionTable

To download and install the latest version of AZSBTools from the PowerShell Gallery and its dependencies, type

Install-Module POSH-SSH,SB-Tools,AZSBTools,AzureRM -Force

AZSBTools contains functions that depend on POSH-SSH, SB-Tools, and AzureRM modules, and they’re typically installed together.

To load the POSH-SSH, SB-Tools, AZSBTools, and AzureRM modules type:

Import-Module POSH-SSH,SB-Tools,AZSBTools,AzureRM -DisableNameChecking

To view a list of cmdlets/functions in SB-Tools, type

Get-Command -Module AZSBTools

To view the built-in help of one of the AZSBTools functions/cmdlets, type

help <function/cmdlet name> -show

such as

help New-SBAZServicePrincipal -show


New-SBAZServicePrincipal cmdlet to create new Azure AD Service Principal added to AZSBTools PowerShell module


For the use case of running PowerShell scripts that perform tasks on objects in an Azure subscription, we need to be able to run such scripts under a user context other than the script author which is what typically happens during script development. A Service Principal is an Azure AD user intended for this purpose. The New-SBAZServicePrincipal function automates and simplifies the process of creating an Azure Service principal.

Parameters

The New-SBAZServicePrincipal function takes the following parameters

ServicePrincipalName

This parameter accepts one or more Service Principal names

Environment

This parameter accepts a value that represents which Azure cloud to create the SPN in. This parameter default to Azure Commercial cloud. As of 15 March 2018 that list is:

  • AzureCloud
  • AzureUSGovernment
  • AzureChinaCloud
  • AzureGermanCloud

To see the current list, use: (Get-AzureRMEnvironment).Name

Role

This parameter is used to assign Role/Permissions for the Service Principal in the current subscription.
The default value is ‘Owner’ role.
As of 16 March 2018 the following default roles are defined:
API Management Service Contributor
Application Insights Component Contributor
Automation Operator
BizTalk Contributor
Classic Network Contributor
Classic Storage Account Contributor
Classic Storage Account Key Operator Service Role
Classic Virtual Machine Contributor
ClearDB MySQL DB Contributor
Contributor
Cosmos DB Account Reader Role
Data Factory Contributor
Data Lake Analytics Developer
DevTest Labs User
DNS Zone Contributor
DocumentDB Account Contributor
Intelligent Systems Account Contributor
Log Analytics Contributor
Log Analytics Reader
Network Contributor
New Relic APM Account Contributor
Owner
Reader
Redis Cache Contributor
Scheduler Job Collections Contributor
Search Service Contributor
Security Manager
SQL DB Contributor
SQL Security Manager
SQL Server Contributor
Storage Account Contributor
Storage Account Key Operator Service Role
Traffic Manager Contributor
User Access Administrator
Virtual Machine Contributor
Web Plan Contributor
Website Contributor
For more details on roles, type in:

Get-AzureRmRoleDefinition | select name,description,actions | Out-GridView

Output

The New-SBAZServicePrincipal function returns a PS Object for each input Service Principal Name containing the following properties:
ServicePrincipalName
TenantId
Environment
Role

Details

The New-SBAZServicePrincipal function performs the following tasks for each provided Service Principal name:

  1. Create/Validate Azure AD App. The Azure AD App is required to create a Service Principal. It carries the same name and has an initial URL matching the same name as well
  2. Create/Validate Azure AD Service Principal. The user is prompted to enter the desired password for the SPN. The password is encrypted and saved in the user’s temp folder for use with future automations
  3. Assign the provided Role to the SPN for the current subscription. By default this is the ‘Owner’ role. This allows the created SPN to perform all tasks against the current subscription.

Registered Apps can be also viewed in the Azure portal under Azure Active Directory/App Registrations blade:

Example

$SPList = New-SBAZServicePrincipal -ServicePrincipalName PowerShell01,samtest1

This example creates 2 Service Prinsipals; PowerShell01 and samtest1 in the default Azure Commercial cloud, and assigns them the default Owner Role in the current subscription.

The New-SBAZServicePrincipal function first pops the Azure login Window to identify which subscription to use:

This function has been tested with both Azure Commercial and Azure US GOV clouds.

Next enter the desired password for each of the 2 provided Service Principals:

The function saves the encrypted password to the user temp folder for future use/automation.

It also display console output similar to:

The Service Principals can be used now to run other PowerShell scripts

The newly registered/validated Apps can also be viewed from the Azure Portal


To use the AZSBTools PowerShell module which is available in the PowerShell Gallery, you need PowerShell 5. To view your PowerShell version, in an elevated PowerShell ISE window type

$PSVersionTable

To download and install the latest version of AZSBTools from the PowerShell Gallery and its dependencies, type

Install-Module POSH-SSH,SB-Tools,AZSBTools,AzureRM -Force

AZSBTools contains functions that depend on POSH-SSH, SB-Tools, and AzureRM modules, and they’re typically installed together.

To load the POSH-SSH, SB-Tools, AZSBTools, and AzureRM modules type:

Import-Module POSH-SSH,SB-Tools,AZSBTools,AzureRM -DisableNameChecking

To view a list of cmdlets/functions in SB-Tools, type

Get-Command -Module AZSBTools

To view the built-in help of one of the AZSBTools functions/cmdlets, type

help <function/cmdlet name> -show

such as

help New-SBAZServicePrincipal -show