当前位置: 移动技术网 > IT编程>脚本编程>Shell > Powershell小技巧之获取变量列表

Powershell小技巧之获取变量列表

2017年12月08日  | 移动技术网IT编程  | 我要评论

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

这里定义了一个函数 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
computername                   zhanghong-book
comspec                        c:\windows\system32\cmd.exe
homedrive                      c:
homepath                       \users\zhanghong
java_home                      d:\javadevenv\jdk1.6.0_16
……

注意,get-childitem和dir是一个意思,后者是前者的别名。洪哥喜欢偷懒,所以直接用了dir。
上面,列出了所有的环境变量,有兴趣的朋友可以一一熟悉一下,以便后面在需要用到变量的值时去调用。

2、获取环境变量的值

语法:$env:<变量名>

举个例子,如果我想获取当前计算机名称,则用法如下:

复制代码 代码如下:

ps c:\users\zhanghong> $env:computername
zhanghong-book

注意,环境变量也是一种变量,所以在“env:”之前必须有powershell变量的专用前缀“$”。

关于powershell获取环境变量的值,本文就介绍这么多,希望对大家有所帮助,谢谢!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网