Profiling a Script

Last summer, Ed Wilson was looking for help with a small part of the book he was finishing up, Windows PowerShell 2.0 Best Practices. The topic he was working on was, “How do I know this script is safe to run?” Which is a great question and one with greater significance as more administrators come to PowerShell and are tempted to run scripts created elsewhere while not having perhaps all the experience and training to fully appreciate what might happen. I offered some comments on some things I would do. I also decided to write a script (trust me) that an administrator could run that would analyze a PowerShell script and produce a report, or profile, for that script.

The version I provided for the book was supposed to be clearly marked as a work in progress.  I’ve worked with it on and off since then and it is still a work in progress, but I wanted to offer up the latest version for Ed’s readers and for the PowerShell community.


























































































































































































































































































































































































































The script, Get-ScriptProfile.ps1 requires PowerShell 2.0 and essentially is a giant string parser. It works pretty well with basic PowerShell 1.0 scripts. The basic syntax is to run the profile script and pass it a PowerShell script as a parameter.

PS C:\> c:\scripts\get-scriptprofile foo.ps1

The profiling script will report:

  • Whether the script is signed and the state of the signature
  • If a v2 script, any requirements
  • What parameters the script takes
  • The lines of the script where those parameters are used
  • The names of any internally defined functions
  • Any invoked PowerShell cmdlet, alias or function

All of this information is written to the pipeline more or less as a page but you can pipe the results to Out-File if you wish. Get-ScriptProfile also has a –code parameter which will append the script contents to the output.

The invoked commands section is perhaps the most useful. Within the script I use Get-Command to get all the currently available commands and then simply look for those commands throughout the script. If I was an admin analyzing a script, I’d be looking out for cmdlets that Stop or Remove.

This is far from a perfect and final tool, and perhaps it can’t be. The download version of the script has a short ToDo list. Many of the items are related to handling PowerShell 2.0 scripts.  If you have a suggestion or solution, I hope you’ll let me know.

One thought on “Profiling a Script

  1. Pingback: Tweets that mention Profiling a Script | The Lonely Administrator -- Topsy.com

Comments are closed.