0

I have powershell script that reads output from powershell command line and saves it into a hash.

When I try to get "sender-ip", the output is blank.

Below is the code

$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

Here are the arguments passed into the script

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

And this is the output

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

The code seems correct, what is missing?

1 Answer 1

1

If you output the $my_hash.Keys property...

 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

...you'll see that, due to the way you're parsing the command line arguments, all but one of the keys is prefixed with a space character. The value you're looking for actually has key " Sender-IP"; there is no item with key "Sender-IP" in $my_hash.

To remove leading and trailing whitespace from all keys and values, you can use the String.Trim instance method in your last foreach loop like this...

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

    $my_hash.add($key, $value)
    write-host $key $value
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.