我們的需求是當想要列出腳本中所有變量。
這里定義了一個函數 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
新聞熱點
疑難解答