Использование регулярных выражений для идентификации вызовов команд в 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
}
}
Если ваш скрипт выглядит как это:
Get-Process
& "Get-Service"
$a = "Get-Item"
. $a 'C:\Windows'
Вы должны ожидать следующий вывод:
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