Powershell无法读取哈希值

时间:2013-12-23 19:39:53

标签: powershell hash

我有powershell脚本,它从powershell命令行读取输出并将其保存为哈希值。

当我尝试获取“sender-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 个答案:

答案 0 :(得分: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"; "Sender-IP"中没有关键$my_hash的项目。

要从所有键和值中删除前导和尾随空格,您可以使用上一个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
}