简体   繁体   English

Powershell - $args 去掉逗号

[英]Powershell - $args strips out the comma

I am writing a script to interface with 3rd party software.我正在编写一个脚本来与 3rd 方软件交互。

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:当提供像ab=c,d这样的参数时,我发现$args具有以下数组布局:

[
  "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.到目前为止,这对我来说似乎没问题,但我不知道有关 powershell 的 CLI arg 解析的详细信息,所以这可能是错误的......如果我发现任何边缘情况,我会回来报告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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