Skip to content
Menu
The Lonely Administrator
  • PowerShell Tips & Tricks
  • Books & Training
  • Essential PowerShell Learning Resources
  • Privacy Policy
  • About Me
The Lonely Administrator

Updated PowerShell Script Profiler

Posted on January 15, 2014January 15, 2014

Last year I wrote a sidebar for the Scripting Guy, Ed Wilson and an update to his PowerShell Best Practices book. I wrote a script using the new parser in PowerShell 3.0 to that would analyze a script and prepare a report showing what commands it would run, necessary parameters, and anything that might pose a danger. I also wrote an article with the script for the Hey Scripting Guy blog.

Manage and Report Active Directory, Exchange and Microsoft 365 with
ManageEngine ADManager Plus - Download Free Trial

Exclusive offer on ADManager Plus for US and UK regions. Claim now!

During my PowerShell training class last week we were talking about how to look at someone else's code and figure out what it might do. I also demonstrated my script. During the coure of that demonstration I realized I needed to make a few revisions. Here is version 2 of Get-ASTScriptProfile.ps1.

#requires -version 3.0

#Get-ASTScriptProfile.ps1

<#
  ****************************************************************
  * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED *
  * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK.  IF   *
  * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, *
  * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING.             *
  ****************************************************************
#>

<#
.Synopsis
Profile a PowerShell Script
.Description
This script will parse a PowerShell script using the AST to identify elements 
and any items that might be dangerous. The output is a text report which by 
default is turned into a help topic stored in your Windows PowerShell folder
under Documents, although you can specify an alternate location.

DETAILS
The script takes the name of a script to profile. You can specify a ps1 or 
psm1 filename. Using the AST the script will prepare a text report showing 
you any script requirements, script parameters, commands and type names. You 
will see all commands used including those that can't be resolved as well as 
those that I thought might be considered potentially dangerous such as cmdlets 
that use the verbs Remove or Stop. Because some people might invoke methods 
from .NET classes directly I've also captured all typenames. Most of them will
probably be related to parameters but as least you'll know what to look for. 

The report won't detail parameters from nested functions but you'll still see 
what commands they will use. The script uses Get-Command to identify commands 
which might entail loading a module. Most of the time this shouldn't be an 
issue but you still might want to profile the script in virtualized or test 
environment. 

Any unresolved command you see is either from a module that couldn't be loaded
or it might be an internally defined command. Once you know what to look for 
you can open the script in your favorite editor and search for the mystery 
commands.

Note that if the script uses application names like Main or Control for function
names, they might be misinterpreted. In that case, search the script for the name,
ie "main". 

This version will only analyze files with an extension of .ps1, .psm1 or .txt.
.Parameter Path
The path to the script file. It should have an extension of .ps1, .psm1 or
.bat.
.Parameter FilePath
The path for the report file. The default is your WindowsPowerShell folder.
This paramter has aliases of fp and out.
.Example
PS C:\> c:\scripts\Get-ASTScriptProfile c:\download\UnknownScript.ps1 

This will analyze the script UnknownScript.ps1 and show the results in a
help window. It will also create a text file in your Documents\WindowsPowerShell 
folder called UnknownScript.help.txt.
.Example
PS C:\> c:\scripts\Get-ASTScriptProfile c:\download\UnknownScript.ps1 -filepath c:\work

This command is the same as the first example except the help file will be created
in C:\Work.

.Notes
Version 2.0
Last Updated January 14, 2014
Jeffery Hicks (http://twitter.com/jeffhicks)

Learn more:
 PowerShell in Depth: An Administrator's Guide (http://www.manning.com/jones2/)
 PowerShell Deep Dives (http://manning.com/hicks/)
 Learn PowerShell 3 in a Month of Lunches (http://manning.com/jones3/)
 Learn PowerShell Toolmaking in a Month of Lunches (http://manning.com/jones4/)
 
.Inputs
None
.Outputs
Help topic
.Link
Get-Command
Get-Alias
#>

[cmdletbinding()]
Param(
[Parameter(Position=0,Mandatory,HelpMessage="Enter the path of a PowerShell script")]
[ValidateScript({Test-Path $_})]
[ValidatePattern( "\.(ps1|psm1|txt)$")]
[string]$Path,
[ValidateScript({Test-Path $_})]
[Alias("fp","out")]
[string]$FilePath = "$env:userprofile\Documents\WindowsPowerShell"
)

Write-Verbose "Starting $($myinvocation.MyCommand)"

#region setup profiling
#need to resolve full path and convert it
$Path = (Resolve-Path -Path $Path).Path | Convert-Path
Write-Verbose "Analyzing $Path"

Write-Verbose "Parsing File for AST"
New-Variable astTokens -force
New-Variable astErr -force

$AST = [System.Management.Automation.Language.Parser]::ParseFile($Path,[ref]$astTokens,[ref]$astErr)

#endregion

#region generate AST data

#include PowerShell version information
Write-Verbose "PSVersionTable"
Write-Verbose ($PSversionTable | Out-String)

$report=@"
Script Profile report for: $Path

******************
* PSVersionTable *
******************
$(($PSversionTable | Out-String).TrimEnd())

"@

Write-Verbose "Getting requirements and parameters"
$report+=@"

******************
*  Requirements  *
******************
$(($ast.ScriptRequirements | out-string).Trim())

******************
*  Parameters    *
******************
$(($ast.ParamBlock.Parameters | 
 Select Name,DefaultValue,StaticType,Attributes |
 Format-List | Out-String).Trim())
 
"@

Write-Verbose "Getting all command elements"

$commands = @()
$unresolved = @()

$genericCommands = $astTokens | 
where {$_.tokenflags -eq 'commandname' -AND $_.kind -eq 'generic'} 

$aliases = $astTokens | 
where {$_.tokenflags -eq 'commandname' -AND $_.kind -eq 'identifier'} 

Write-Verbose "Parsing commands"
foreach ($command in $genericCommands) {
    Try {
       $commands+= Get-Command -Name $command.text -ErrorAction Stop
    }
    Catch {
      $unresolved+= $command.Text
    }
}

foreach ($command in $aliases) {
Try {
       $commands+= Get-Command -Name $command.text -erroraction Stop |
       foreach { 
         #get the resolved command
         Get-Command -Name $_.Definition  
       }
    }
    Catch {
        $unresolved+= $command.Text
    }
}

Write-Verbose "All commands"
$report+=@"

******************
*  All Commands  *
******************
$(($Commands | Sort -Unique | Format-Table -autosize | Out-String).Trim())

"@

Write-Verbose "Unresolved commands"
$report+=@"

******************
*  Unresolved    *
******************
$($Unresolved | Sort -Unique | Format-Table -autosize | Out-String)
"@

Write-Verbose "Potentially dangerous commands"
#identify dangerous commands
$danger="Remove","Stop","Disconnect","Suspend","Block",
"Disable","Deny","Unpublish","Dismount","Reset","Resize",
"Rename","Redo","Lock","Hide","Clear"

$danger = $commands | where {$danger -contains $_.verb}

#get type names, some of which may come from parameters
Write-Verbose "Typenames"
$report+=@"

******************
*  TypeNames     *
******************
$($asttokens | where {$_.tokenflags -eq 'TypeName'} | 
Sort @{expression={$_.text.toupper()}} -unique | 
Select -ExpandProperty Text | Out-String)
"@

$report+=@"

******************
*  Warning       *
******************
$($danger | Format-Table -AutoSize | Out-String)
"@

#endregion

Write-Verbose "Display results"
#region create and display the result

#create a help topic file using the script basename
$basename = (Get-Item $Path).basename     
#stored in the Documents folder
$reportFile = Join-Path -Path $FilePath -ChildPath "$basename.help.txt"

Write-Verbose "Saving report to $reportFile"
#insert the Topic line so help recognizes it
"TOPIC" | Out-File -FilePath $reportFile -Encoding ascii 

#create the report
$report | Out-File -FilePath $reportFile -Encoding ascii -Append

#view the report with Get-Help and -ShowWindow
Get-Help (Join-Path -Path $FilePath -ChildPath $basename) -ShowWindow

#endregion

Write-Verbose "Profiling complete."

#end of script

One thing I discovered was that the AST didn't like parsing a file without an absolute and resolved path. I was running into errors because the script was on a PSDrive like Scripts: that resolved to C:\Scripts. The solution was to resolve it, in the event of using a path like .\file.ps1 and then convert the path.

$Path = (Resolve-Path -Path $Path).Path | Convert-Path

I also discovered that if the script contains functions with a name like Main or Control, the parser, at the least the way I am using it, will detect it as an application like main.cpl. There's a reason you should give your function a meaningful and standard name and try to avoid using a name that *might* be misinterepted. A function called Notepad probably isn't a good idea. I modified the help to indicate this potential misinterpretation. I'm not sure there's much else I can do.

The few other changes I made were for the sake of flexibility and clarity. I now include the PSVersion information in the report. Parameter information is now displayed as a list to avoid losing any data. I added a validation parameter for the script file so that you can only analzye a .ps1, .psm1 or .txt file.

Finally, I added a parameter so that you can specify the folder for the output file. The default is Documents\WindowsPowerShell. You don't specify the filename, just the path like C:\Scripts or $env:temp.

PS Scripts:\> .\Get-ASTScriptProfile.ps1 .\Convert-WindowsImage.ps1 -out c:\work

This will result in a help topic report like this:

script-profile-report
So download the new version and try it out on your scripts. Find some files online and try it out on them. Let me know what you think.


Behind the PowerShell Pipeline

Share this:

  • Click to share on X (Opens in new window) X
  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on Mastodon (Opens in new window) Mastodon
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on Pocket (Opens in new window) Pocket
  • Click to share on Reddit (Opens in new window) Reddit
  • Click to print (Opens in new window) Print
  • Click to email a link to a friend (Opens in new window) Email

Like this:

Like Loading...

Related

2 thoughts on “Updated PowerShell Script Profiler”

  1. Francois-Xavier Cat says:
    January 15, 2014 at 6:11 pm

    Great Article! thanks Jeffery!

  2. Pingback: Microsoft Most Valuable Professional (MVP) – Best Posts of the Week around Windows Server, Exchange, SystemCenter and more – #64 - Dell TechCenter - TechCenter - Dell Community

Comments are closed.

reports

Powered by Buttondown.

Join me on Mastodon

The PowerShell Practice Primer
Learn PowerShell in a Month of Lunches Fourth edition


Get More PowerShell Books

Other Online Content

github



PluralSightAuthor

Active Directory ADSI Automation Backup Books CIM CLI conferences console Friday Fun FridayFun Function functions Get-WMIObject GitHub hashtable HTML Hyper-V Iron Scripter ISE Measure-Object module modules MrRoboto new-object objects Out-Gridview Pipeline PowerShell PowerShell ISE Profile prompt Registry Regular Expressions remoting SAPIEN ScriptBlock Scripting Techmentor Training VBScript WMI WPF Write-Host xml

©2025 The Lonely Administrator | Powered by SuperbThemes!
%d