Ищите регулярное выражение, которое может получить список всех командлетов, используемых внутри скрипта Powershell. - PullRequest
0 голосов
/ 21 апреля 2020

Я делаю что-то вроде этого:

$ScriptContent = get-content "C:\Users\admin\Desktop\Scripts\SFB.ps1"
$ScriptContent -match '(?<N>.*)-(?<V>.*)'

1 Ответ

0 голосов
/ 21 апреля 2020

Использование регулярных выражений для идентификации вызовов команд в 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...