2013-12-23 56 views
0

我有PowerShell腳本,從PowerShell命令行讀取輸出並將其保存到散列。Powershell無法讀取散列

當我嘗試獲取「發件人-IP」時,輸出爲空。

下面是代碼

$args = (($args | % { $_ -join ", " }) -join " ") 

foreach ($i in $args){ 
    $line_array+= $i.split(",") 
} 

foreach ($j in $line_array){ 
    $multi_array += ,@($j.split("=")) 
} 

foreach ($k in $multi_array){ 
    $my_hash.add($k[0],$k[1]) 
    write-host $k 
} 

$Sender_IP = $my_hash.Get_Item("sender-ip") 
Write-host 'sender-ip is' $Sender_IP 

這裏的參數傳遞到腳本

script.ps1 Manager Last Name=Doe, discover-location=null, protocol=Clipboard, Resolution=null, file-owner=user, Employee Type=External Employee, endpoint-file-path=null, Title=null, discover-extraction-date=null, Sender-IP=10.10.10.10, Manager Business Unit=IT Services, Manager Phone=414-555-5555, Username=user, Division=Contractor, file-created-by=DOMAIN\user, file-owner-domain=DOMAIN 

這是輸出

Manager Last Name Doe 
discover-location null 
protocol Clipboard 
Resolution null 
file-owner user 
Employee Type External Employee 
endpoint-file-path null 
Title null 
discover-extraction-date null 
Sender-IP 10.10.10.10 
Manager Business Unit IT Services 
Manager Phone 414-555-5555 
Username user 
Division Contractor 
file-created-by DOMAIN\user 
file-owner-domain DOMAIN 
sender-ip is 

的代碼似乎是正確的,缺什麼?

回答

1

如果輸出的$my_hash.Keys財產...

file-created-by 
discover-extraction-date 
Manager Phone 
Employee Type 
endpoint-file-path 
file-owner-domain 
Title 
Manager Business Unit 
discover-location 
Sender-IP 
Username 
file-owner 
Resolution 
Manager Last Name 
Division 
protocol 

...你會看到的是,由於順便說一下你解析命令行參數,但所有的關鍵之一就是前綴具有空間特徵。你正在尋找的價值實際上有鑰匙" Sender-IP"; $my_hash中沒有鑰匙"Sender-IP"的項目。

刪除前導和所有鍵和值尾的空白,你可以在你的最後foreach循環這樣的使用String.Trim instance method ...

foreach ($k in $multi_array) { 
    $key = $k[0].Trim() 
    $value = $k[1].Trim() 

    $my_hash.add($key, $value) 
    write-host $key $value 
} 
+0

謝謝......並有新年快樂! ! – Glowie