2015-01-14 201 views
2

我想在PowerShell中使用環境變量,但我發現的例子似乎並不奏效。這是我使用的測試腳本:Powershell環境變量

Get-ChildItem Env: 
Write-Host "************" 
$AlarmDatastore = Get-ChildItem Env:*VMWARE_ALARM_TARGET_NAME* 
Write-Host "Var = " $AlarmDatastore.value 
$Test = $env:VMWARE_ALARM_TARGET_NAME 
Write-Host "Test = " $Test 

腳本的輸出:

USERNAME      ADMIN.GABRI 
USERPROFILE     C:\Users\admin.gabri 
VMWARE_ALARM_ALARMVALUE  Current values for metric/state 
VMWARE_ALARM_DECLARINGSUMMARY ([Yellow metric Is above 10; Red metric Is a... 
VMWARE_ALARM_EVENTDESCRIPTION Alarm 'Alarm 10 percent test with script' on ... 
VMWARE_ALARM_ID    alarm-601 
VMWARE_ALARM_NAME    Alarm 10 percent test with script 
VMWARE_ALARM_NEWSTATUS   Red 
VMWARE_ALARM_OLDSTATUS   Gray 
VMWARE_ALARM_TARGET_ID   datastore-12587 
VMWARE_ALARM_TARGET_NAME  VCD-VMFS-095-FAST-VNX-5400-04 
VMWARE_ALARM_TRIGGERINGSUMM... Metric Disk Space actually used = 96 
windir       C:\Windows 
************ 
Var = VCD-VMFS-095-FAST-VNX-5400-04 
Test = 

爲什麼我只能使用獲得環境VAR:獲取ChildItem ENV:* VMWARE_ALARM_TARGET_NAME * ,而不是簡單地由$測試= $ ENV:VMWARE_ALARM_TARGET_NAME

+0

你爲什麼在gci中使用通配符?爲什麼不使用'Get-Item Env:\ VMWARE_ALARM_TARGET_NAME'?我想知道在使用'$ env'的時候,gci調用中可能沒有包含通配符嗎? – briantist

+0

我將代碼更改爲您的建議,這就是結果。 代碼: '$ Test2的= GET-項目ENV:\ VMWARE_ALARM_TARGET_NAME 寫主機 「的Test2 =」 $ Test2' 結果: GET-項目:找不到路徑 'ENV:\ VMWARE_ALARM_TARGET_NAME',因爲它不存在。 在G:\ DataStoreAlarms \ Scripts \ EnvTest.ps1:5 char:10 + $ Test2 = Get-Item Env:\ VMWARE_ALARM_TARGET_NAME + ~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~ + CategoryInfo:ObjectNotFound:Env:\ VMWARE_ALARM_TARGET_NAME:String)[Get-Item],ItemNotFoundException + FullyQualifiedErrorId:PathNotFound,Microsoft.PowerShell.Commands。 GetItemCommand – Gabrie

+0

如何:'gi env:* VMWARE_ALARM_TARGET_NAME * | fl *'? – briantist

回答

0

有幾件事情嘗試:

#Use ${ } for complex variable names 
${env:VMWARE_ALARM_TARGET_NAME} 

#Or as part of a print statement use env directly (with or without ${env:}): 
Write-Host "Test = $($env:VMWARE_ALARM_TARGET_NAME)" 

#At an interactive prompt see if it can be tab completed 
$env:VMWWARE #then tab to see if it shows up in auto complete 

另外,值得一看運行set時cmd.exe顯示的內容。在PowerShell類型中:

cmd 
set 
exit 

並查看輸出結果如何。

0

由於時間壓力,我不得不去與現在這個權利:

$AlarmTARGET_NAME = get-childitem Env:*VMWARE_ALARM_TARGET_NAME* 
$AlarmNAME = get-childitem Env:*VMWARE_ALARM_NAME* 
$AlarmEVENTDESCRIPTION = get-childitem Env:*VMWARE_ALARM_EVENTDESCRIPTION* 
$AlarmDECLARINGSUMMARY = get-childitem Env:*VMWARE_ALARM_DECLARINGSUMMARY* 
$AlarmVALUE = get-childitem Env:*VMWARE_ALARM_ALARMVALUE* 

不是很乾淨的代碼,但它的工作原理。 感謝所有的答覆。

Gabrie