简体   繁体   中英

Powershell - $args strips out the comma

I am writing a script to interface with 3rd party software.

They send string in the format:

sender-ip=10.10.10.10, primary site location=peachtree street, created by=jsmith

However, when the script executes

Write-host $args

This is the output

sender-ip=10.10.10.10 primary site location=peachtree street created by=jsmith

How do I preserve the original input string with the commas?

EDIT:

Below is snippit of code

$args = $args.ToString()
write-host '$args is' $args

foreach ($i in $args){
   $line_array+= $i.split(",")
   write-host '$line_array is' $line_array

}

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

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

}


$Sender_IP = $my_hash.Get_Item("sender-ip")

When I execute code with

script.ps1 sender-ip=10.10.10.10, primary site location=peachtree street, created by=jsmith

I get

$args is System.Object[]
$line_array is System.Object[]
$Sender_IP is

It's interpreting that as multiple arguments. You need to quote the whole thing so it knows it just one argument:

&{Write-Host $args} sender-ip=10.10.10.10, primary site location=peachtree street, created by=jsmith
&{Write-Host $args} 'sender 10.10.10.10, primary site location=peachtree street, created by=jsmith'

sender-ip=10.10.10.10 primary site location=peachtree street created by=jsmith
sender 10.10.10.10, primary site location=peachtree street, created by=jsmith

When providing an arguments like ab=c,d , I found $args had the following array layout:

[
  "a",
  [
    "b=c",
    "d"
  ]
]

So to get the arguments back to having a comma, I'm using the following function:

function process_args {
  $newArgs = @()
  foreach ($arg in $args) {
    if ($arg -is [array]) {
      # collapse back any comma separated arguments to a string
      $newArgs = $newArgs + ($arg -join ",")
    } else {
      $newArgs = $newArgs + $arg
    }
  }
  return $newArgs
}

$args = process_args @args

Which leaves me with an array like:

[
  "a",
  "b=c,d"
]

This seems to have worked ok for me so far, but I don't know the details about powershell's CLI arg parsing so perhaps this is wrong... I'll report back if I find any edge cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM