支持3.0及以后
我们的需求是当想要列出脚本中所有变量。
这里定义了一个函数 Get-Variable:
function Get-Variable
{
$token = $null
$errors = $null
$ast = [System.Management.Automation.Language.Parser]::ParseInput($psise.CurrentFile.Editor.Text, [ref] $token, [ref] $errors)
# not complete, add variables you want to exclude from the list:
$systemVariables = '_', 'null', 'psitem', 'true', 'false', 'args', 'host'
$null = $ast.FindAll({ $args[0] -is [System.Management.Automation.Language.CommandAst] }, $true)
$token |
Where-Object { $_.Kind -eq 'Variable'} |
Select-Object -ExpandProperty Name |
Where-Object { $systemVariables -notcontains $_ } |
Sort-Object -Unique
}
将脚本加载到ISE编辑器,接着已交互方式运行Get-Variable.
你将获取当前打开脚本的变量清单。
如果你用包含了脚本代码的变量去替换掉 “$psise.CurrentFile.Editor.Text”。你可以直接在编辑器外部运行这个,照这样,我们可以使用Get-Content加载任何脚本到变量,同时使用这个加载变量到上面代码中。
原文地址:Getting a Variable Inventory
本文链接: https://www.pstips.net/getting-a-variable-inventory.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!
