[英]Looking for a regex can that pull the list of all the cmdlets used inside a Powershell script
I am doing something like this:我正在做这样的事情:
$ScriptContent = get-content "C:\Users\admin\Desktop\Scripts\SFB.ps1"
$ScriptContent -match '(?<N>.*)-(?<V>.*)'
Using regex to identify command invocations in PowerShell is a lost cause, consider just hooking straight into the parser engine instead (see inline comments):使用正则表达式来识别 PowerShell 中的命令调用是一个失败的原因,请考虑直接挂钩到解析器引擎(请参阅内联注释):
$scriptPath = "C:\Users\admin\Desktop\Scripts\SFB.ps1"
# Parse the script
$AST = [System.Management.Automation.Language.Parser]::ParseFile((Resolve-Path $scriptPath).ProviderPath, [ref]$null, [ref]$null)
# Now we use the AST to find all command invocations
#AST.FindAll({
$args[0] -is [System.Management.Automation.Language.CommandAst]
}, $true) |ForEach-Object {
# The first element is always the name
$command = $_.CommandElements[0]
# if the command name is a constant string, resolve it's value
if($command -is [System.Management.Automation.Language.StringConstantExpressionAst]){
$commandName = $command.Value
$known = $true
} else {
# Otherwise, note that the name can only be known at runtime
$commandName = "'{0}'" -f $command.Extent
$known = $false
}
# output new object with the information
[pscustomobject]@{
Name = $commandName
Constant = $known
File = $scriptPath
Line = $command.Extent.StartLineNumber
}
}
If your script looks like this:如果您的脚本如下所示:
Get-Process
& "Get-Service"
$a = "Get-Item"
. $a 'C:\Windows'
You should expect the following output:您应该期待以下 output:
Name Constant File Line
---- -------- ---- ----
Get-Process True C:\Users\admin\Desktop\Scripts\SFB.ps1 1
Get-Service True C:\Users\admin\Desktop\Scripts\SFB.ps1 3
'$a' False C:\Users\admin\Desktop\Scripts\SFB.ps1 7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.