SherlockSpreadsheets
SherlockSpreadsheets

Reputation: 2370

List of commands or module dependencies in .ps1 script file

Is there some way to identify all cmdlets used in a script file? What I am trying to find out is find requirements for deployment to another environment. What modules have been used? Which version is installed? Then can review the list of command and know what to install in the new environment.

Let's use the below file as an example. Once I know the cmdlets then I can use get-command to find out the module/version installed. Reference: Find PowerShell cmdlets with Get-Command | 4sysops

Thanks for your advise.

Cmdlet dependencies (example output)

Cmdlets used in 'C:\myDir\---\PbiList_Reports_exportCsv.ps1'   
------

Get-AzStorageAccountKey
New-AzStorageContext 
Start-Transcript 
Write-Host 
New-Object 
Connect-PowerBIServiceAccount 
etc...

Cmdlet information (example output)

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Cmdlet          Get-AzStorageAccountKey                            3.6.0      Az.Storage
Cmdlet          Connect-PowerBIServiceAccount                      1.0.974    MicrosoftPowerBIMgmt.Profile
etc...

PbiList_Reports_exportCsv.ps1 (source input)

<#------------------------------------------------------
# 4,REPORT: Export list of all workspace reports 
# 
# Loop all workspaces. Retreive reports list. Export to blob storage.
# --> Account > Container > Blob
#------------------------------------------------------#>

# -------- Export files local dir --------
$Filepath = "C:\Users\me\Dropbox\00-PBI\ActivityLogs\"
$Transcript_file = $Filepath +"Logs\testlog_reports.txt"
$Reports_file = $Filepath +"AllReports.csv"
### $wsReportsAll | Export-csv -Path $Reports_file -NoTypeInformation
#

# -------- Export files to Azure blob --------
$Transcript_file = "testfun_reports.txt"
$Reports_file = "AllReports.csv"

# Get key to storage account
# Map to the reports BLOB context
# Copy the file to the storage account
$acctKey = (Get-AzStorageAccountKey -Name "myblob" -ResourceGroupName "myResource").Value[0] 
$storageContext = New-AzStorageContext -StorageAccountName "myblob" -StorageAccountKey $acctKey -Verbose


#### Print write-host to log file
Start-Transcript -Path "$Env:temp/$Transcript_file" -verbose # "C:\Users\me\Dropbox\00-PBI\ActivityLogs\Logs\testlog_reports.txt"
Write-Host "Today: ($Date).ToString("yyyy.MM.dd")" 


# -------- PBI Connection --------

Write-Host " PBI credentials ..." -ForegroundColor Yellow -BackgroundColor DarkGreen
## PBI credentials 
$password = "******" | ConvertTo-SecureString -asPlainText -Force
$username = "[email protected]" 
$credential = New-Object System.Management.Automation.PSCredential($username, $password)
Connect-PowerBIServiceAccount -Credential $credential


#-------- PBI Workspace Reports  -------
$wsReportsAll = @()

# Workspaces filtered to exclude PBI Personal and other PBI Groups
Write-Host " Workspace info ..." -ForegroundColor Yellow -BackgroundColor DarkGreen
$Groups = Get-PowerBIWorkspace -All -Scope Organization | SORT @{Expression="Type"; Descending=$True}, Name | 
    ?{
    ($_.Type -eq 'Workspace') `
    }

Write-Host(($Groups.count).ToString() + " workspace count")

foreach ($ws in $Groups) {
    # Variables
    $wsName = $ws.Name.ToString()
    $wsId = $ws.Id.ToString()
    
    # Workspaces
    $wsReports = Get-PowerBIReport -WorkspaceId $ws.Id
    $wsReports = $wsReports | SELECT *, @{Name = 'Workspace'; Expression = {$wsName}} , @{Name = 'WorkspaceId'; Expression = {$wsId}} 
    
    Write-Host("")
    Write-Host($ws.Name + "...")
    Write-Host(($wsReports.count).ToString() + " report count") -ForegroundColor Cyan -BackgroundColor DarkGreen

    $wsReportsAll += $wsReports
}

$wsReportsAll | SELECT Id, Name, WorkspaceId, Workspace, DatasetId  | ft -auto
$wsReportsCsv = ($wsReportsAll | ConvertTo-Csv -NoTypeInformation).ToString() 
$wsReportsAll | Export-csv "$Env:temp/$Reports_file"

# $wsReportsAll | Export-csv -Path $Reports_file -NoTypeInformation
Set-AzStorageBlobContent -File "$Env:temp/$Reports_file" -Container "myFolder" -BlobType "Block" -Context $storageContext -Force -Verbose

Stop-Transcript

Set-AzStorageBlobContent -File "$Env:temp/$Transcript_file" -Container "myFolder" -Blob "Logs/$Transcript_file" -BlobType "Block" -Context $storageContext -Force -Verbose

#****************
#****************

Upvotes: 0

Views: 1185

Answers (1)

JosefZ
JosefZ

Reputation: 30123

First, (optionally) apply Invoke-ScriptAnalyzer from the module ScriptAnalyzer to fix minor inconsistencies (in particular, apply the PSAvoidUsingCmdletAliases rule).

Then you can utilize the Parser Class, e.g. as follows:

# Define input script
$inputScript = '.\tests\PbiList_Reports_exportCsv.ps1'

("-" * 25) + ' ScriptAnalyzer'
Import-Module -Name PSScriptAnalyzer
Invoke-ScriptAnalyzer -Path "$inputScript" -ExcludeRule PSAvoidUsingWriteHost -Fix

# Empty collection for errors
$Errors = [System.Management.Automation.Language.ParseError[]]@()
# Empty collection for errors
$Tokens = [System.Management.Automation.Language.Token[]]@()

$Parsed = [System.Management.Automation.Language.Parser]::ParseFile(
                $inputScript,
                [ref]$Tokens,
                [ref]$Errors)

("=" * 25) + " Errors"
if ($Errors.Count -gt 0 ) {
    Write-Warning "$($Errors.Count) Errors found"
}

("≡" * 25) + " Commands"
$Commands = $tokens |
    Where-Object TokenFlags -eq "CommandName" |
        Sort-Object -Property Value -Unique
$Commands | Select-Object -ExpandProperty Value
### I can't do the following not having installed all modules
### $Commands | ForEach-Object { Get-Command -Name $_.Value }

Output: \SO\67519696.ps1

------------------------- ScriptAnalyzer

RuleName                            Severity     ScriptName Line  Message
--------                            --------     ---------- ----  -------
PSAvoidUsingConvertToSecureStringWi Error        PbiList_Re 39    File
thPlainText                                      ports_expo       'PbiList_Reports_exportCsv.ps1'
                                                 rtCsv.ps1        uses ConvertTo-SecureString with
                                                                  plaintext. This will expose secure
                                                                  information. Encrypted standard
                                                                  strings should be used instead.
PSUseDeclaredVarsMoreThanAssignment Warning      PbiList_Re 74    The variable 'wsReportsCsv' is
s                                                ports_expo       assigned but never used.
                                                 rtCsv.ps1
========================= Errors
≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡ Commands
Connect-PowerBIServiceAccount
ConvertTo-Csv
ConvertTo-SecureString
Export-csv
Format-Table
Get-AzStorageAccountKey
Get-PowerBIReport
Get-PowerBIWorkspace
New-AzStorageContext
New-Object
Select-Object
Set-AzStorageBlobContent
Sort-Object
Start-Transcript
Stop-Transcript
Where-Object
Write-Host

Upvotes: 3

Related Questions