[玩转系统] 更新了 PowerShell 脚本分析器
作者:精品下载站 日期:2024-12-14 07:40:56 浏览:12 分类:玩电脑
更新了 PowerShell 脚本分析器
去年,我为脚本专家 Ed Wilson 编写了一个侧边栏,并更新了他的 PowerShell 最佳实践一书。我使用 PowerShell 3.0 中的新解析器编写了一个脚本,该脚本将分析脚本并准备一份报告,显示它将运行哪些命令、必要的参数以及可能构成危险的任何内容。我还为 Hey Scripting Guy 博客撰写了一篇包含该脚本的文章。
在上周的 PowerShell 培训课程中,我们讨论了如何查看别人的代码并弄清楚它可能会做什么。我还演示了我的脚本。在演示过程中,我意识到我需要做一些修改。这是 Get-ASTScriptProfile.ps1 的版本 2。
#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
我发现的一件事是 AST 不喜欢解析没有绝对路径和解析路径的文件。我遇到了错误,因为脚本位于类似 Scripts: 的 PSDrive 上,解析为 C:\Scripts。解决方案是解决它,如果使用 .\file.ps1 这样的路径,然后转换路径。
$Path = (Resolve-Path -Path $Path).Path | Convert-Path
我还发现,如果脚本包含名称如 Main 或 Control 的函数,解析器(至少以我使用它的方式)会将其检测为类似 main.cpl 的应用程序。您应该为函数指定一个有意义且标准的名称,并尽量避免使用“可能”被误解的名称,这是有原因的。称为记事本的功能可能不是一个好主意。我修改了帮助以表明这种潜在的误解。我不确定我还能做些什么。
我所做的其他一些更改是为了灵活性和清晰度。我现在将 PSVersion 信息包含在报告中。参数信息现在显示为列表以避免丢失任何数据。我为脚本文件添加了一个验证参数,以便您只能分析 .ps1、.psm1 或 .txt 文件。
最后,我添加了一个参数,以便您可以指定输出文件的文件夹。默认位置为 Documents\WindowsPowerShell。您无需指定文件名,只需指定路径,例如 C:\Scripts 或 $env:temp。
PS Scripts:\> .\Get-ASTScriptProfile.ps1 .\Convert-WindowsImage.ps1 -out c:\work
这将生成如下帮助主题报告:
猜你还喜欢
- 03-30 [玩转系统] 如何用批处理实现关机,注销,重启和锁定计算机
- 02-14 [系统故障] Win10下报错:该文件没有与之关联的应用来执行该操作
- 01-07 [系统问题] Win10--解决锁屏后会断网的问题
- 01-02 [系统技巧] Windows系统如何关闭防火墙保姆式教程,超详细
- 12-15 [玩转系统] 如何在 Windows 10 和 11 上允许多个 RDP 会话
- 12-15 [玩转系统] 查找 Exchange/Microsoft 365 中不活动(未使用)的通讯组列表
- 12-15 [玩转系统] 如何在 Windows 上安装远程服务器管理工具 (RSAT)
- 12-15 [玩转系统] 如何在 Windows 上重置组策略设置
- 12-15 [玩转系统] 如何获取计算机上的本地管理员列表?
- 12-15 [玩转系统] 在 Visual Studio Code 中连接到 MS SQL Server 数据库
- 12-15 [玩转系统] 如何降级 Windows Server 版本或许可证
- 12-15 [玩转系统] 如何允许非管理员用户在 Windows 中启动/停止服务
取消回复欢迎 你 发表评论:
- 精品推荐!
-
- 最新文章
- 热门文章
- 热评文章
[影视] 黑道中人 Alto Knights(2025)剧情 犯罪 历史 电影
[古装剧] [七侠五义][全75集][WEB-MP4/76G][国语无字][1080P][焦恩俊经典]
[实用软件] 虚拟手机号 电话 验证码 注册
[电视剧] 安眠书店/你 第五季 You Season 5 (2025) 【全10集】
[电视剧] 棋士(2025) 4K 1080P【全22集】悬疑 犯罪 王宝强 陈明昊
[软件合集] 25年6月5日 精选软件22个
[软件合集] 25年6月4日 精选软件36个
[短剧] 2025年06月04日 精选+付费短剧推荐33部
[短剧] 2025年06月03日 精选+付费短剧推荐25部
[软件合集] 25年6月3日 精选软件44个
[剧集] [央视][笑傲江湖][2001][DVD-RMVB][高清][40集全]李亚鹏、许晴、苗乙乙
[电视剧] 欢乐颂.5部全 (2016-2024)
[电视剧] [突围] [45集全] [WEB-MP4/每集1.5GB] [国语/内嵌中文字幕] [4K-2160P] [无水印]
[影视] 【稀有资源】香港老片 艺坛照妖镜之96应召名册 (1996)
[剧集] 神经风云(2023)(完结).4K
[剧集] [BT] [TVB] [黑夜彩虹(2003)] [全21集] [粤语中字] [TV-RMVB]
[实用软件] 虚拟手机号 电话 验证码 注册
[资源] B站充电视频合集,包含多位重量级up主,全是大佬真金白银买来的~【99GB】
[影视] 内地绝版高清录像带 [mpg]
[书籍] 古今奇书禁书三教九流资料大合集 猎奇必备珍藏资源PDF版 1.14G
[电视剧] [突围] [45集全] [WEB-MP4/每集1.5GB] [国语/内嵌中文字幕] [4K-2160P] [无水印]
[剧集] [央视][笑傲江湖][2001][DVD-RMVB][高清][40集全]李亚鹏、许晴、苗乙乙
[电影] 美国队长4 4K原盘REMUX 杜比视界 内封简繁英双语字幕 49G
[电影] 死神来了(1-6)大合集!
[软件合集] 25年05月13日 精选软件16个
[精品软件] 25年05月15日 精选软件18个
[绝版资源] 南与北 第1-2季 合集 North and South (1985) /美国/豆瓣: 8.8[1080P][中文字幕]
[软件] 25年05月14日 精选软件57个
[短剧] 2025年05月14日 精选+付费短剧推荐39部
[短剧] 2025年05月15日 精选+付费短剧推荐36部
- 最新评论
-
- 热门tag