我們的需求是當(dāng)想要列出腳本中所有變量。
這里定義了一個(gè)函數(shù) 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編輯器,接著已交互方式運(yùn)行Get-Variable.
你將獲取當(dāng)前打開(kāi)腳本的變量清單。
如果你用包含了腳本代碼的變量去替換掉 “$psise.CurrentFile.Editor.Text”。你可以直接在編輯器外部運(yùn)行這個(gè),照這樣,我們可以使用Get-Content加載任何腳本到變量,同時(shí)使用這個(gè)加載變量到上面代碼中。
支持3.0及以后
在開(kāi)發(fā)過(guò)程中,經(jīng)常需要用到環(huán)境變量(比如當(dāng)前計(jì)算機(jī)名、登錄的用戶名、Path環(huán)境變量等),那么在PowerShell中如何知道有哪些環(huán)境變量呢?又該如何獲取指定環(huán)境變量的值呢?
PowerShell通過(guò)環(huán)境變量提供者(Environment Provider)讓我們可以訪問(wèn)環(huán)境變量。默認(rèn)情況下,PowerShell創(chuàng)建了一個(gè)驅(qū)動(dòng)器(名稱為env)來(lái)與Environment Provider打交道。所以,我們可以通過(guò)env這個(gè)驅(qū)動(dòng)器來(lái)處理與環(huán)境變量相關(guān)的操作。
1、列出所有的環(huán)境變量
我們可以使用“Get-ChildItem env:”來(lái)獲取所有的環(huán)境變量列表。洪哥本機(jī)的運(yùn)行結(jié)果如下:
代碼如下:
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
新聞熱點(diǎn)
疑難解答
圖片精選