首页 > 开发 > PowerShell > 正文

Powershell小技巧之获取变量列表

2020-05-30 20:16:31
字体:
来源:转载
供稿:网友

我们的需求是当想要列出脚本中所有变量。

这里定义了一个函数 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加载任何脚本到变量,同时使用这个加载变量到上面代码中。

支持3.0及以后

在开发过程中,经常需要用到环境变量(比如当前计算机名、登录的用户名、Path环境变量等),那么在PowerShell中如何知道有哪些环境变量呢?又该如何获取指定环境变量的值呢?

PowerShell通过环境变量提供者(Environment Provider)让我们可以访问环境变量。默认情况下,PowerShell创建了一个驱动器(名称为env)来与Environment Provider打交道。所以,我们可以通过env这个驱动器来处理与环境变量相关的操作。

1、列出所有的环境变量

我们可以使用“Get-ChildItem env:”来获取所有的环境变量列表。洪哥本机的运行结果如下:

代码如下:
PS C:/Users/zhanghong> dir env:

Name                           Value
----                           -----
ALLUSERSPROFILE                C:/ProgramData
APPDATA                        C:/Users/zhanghong/AppData/Roaming
CommonProgramFiles             C:/Program Files/Common Files
CommonProgramFiles(x86)        C:/Program Files (x86)/Common Files

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表