3131# The script accepts the following command line parameters:
3232#
3333# -SubId [subscription_id] | [csv_file_name] (Accepts a .csv file with the list of subscriptions)
34- # -UseInRunbook (Required when executed as a Runbook)
34+ # -UseInRunbook [True] | [False] (Required when executed as a Runbook)
3535# -Server [protocol:]server[instance_name][,port] (Required to save data to the database)
3636# -Database [database_name] (Required to save data to the database)
3737# -Username [user_name] (Required to save data to the database)
3838# -Password [password] (Required to save data to the database, must be passed as secure string)
3939# -FilePath [csv_file_name] (Required to save data in a .csv format. Ignored if database parameters are specified)
4040#
41+ #
4142
4243param (
4344 [string ] $SubId ,
@@ -46,10 +47,38 @@ param (
4647 [SecureString ] $Password ,
4748 [string ] $Database ,
4849 [string ] $FilePath ,
49- [switch ] $UseInRunbook ,
50- [switch ] $IncludeEC
50+ [bool ] $UseInRunbook ,
51+ [bool ] $IncludeEC
5152)
5253
54+
55+ function Load-Module ($m ) {
56+
57+ # This function ensures that the specified module is imported into the session
58+ # If module is already imported - do nothing
59+
60+ if (! (Get-Module | Where-Object {$_.Name -eq $m })) {
61+ # If module is not imported, but available on disk then import
62+ if (Get-Module - ListAvailable | Where-Object {$_.Name -eq $m }) {
63+ Import-Module $m
64+ }
65+ else {
66+
67+ # If module is not imported, not available on disk, but is in online gallery then install and import
68+ if (Find-Module - Name $m | Where-Object {$_.Name -eq $m }) {
69+ Install-Module - Name $m - Force - Verbose - Scope CurrentUser
70+ Import-Module $m
71+ }
72+ else {
73+
74+ # If module is not imported, not available and not in online gallery then abort
75+ write-host " Module $m not imported, not available and not in online gallery, exiting."
76+ EXIT 1
77+ }
78+ }
79+ }
80+ }
81+
5382# The following block is required for runbooks only
5483if ($UseInRunbook ){
5584
@@ -72,6 +101,22 @@ if ($UseInRunbook){
72101
73102 Start-Sleep - Seconds 5
74103 }
104+ }else {
105+ # Ensure that the required modules are imported
106+ # In Runbooks these modules must be added to the automation account manually
107+
108+ $requiredModules = @ (
109+ " Az.Accounts" ,
110+ " Az.Compute" ,
111+ " Az.DatraFactory" ,
112+ " Az.Resources" ,
113+ " Az.Sql" ,
114+ " Az.SqlVirtualMachine"
115+ )
116+
117+ foreach ($module in $requiredModules ){
118+ Load- Module ($module )
119+ }
75120}
76121
77122# Subscriptions to scan
@@ -404,4 +449,5 @@ if ($useDatabase){
404449
405450 (ConvertFrom-Csv ($usageTable | % {$_ -join ' ,' })) | Export-Csv $FilePath - Append - NoType
406451 Write-Host ([Environment ]::NewLine + " -- Added the usage data to $FilePath --" )
407- }
452+ }
453+
0 commit comments