从url抓取参数并将其放到powershell变量中

时间:2018-08-21 15:01:14

标签: powershell

我在Windows框上运行了一个Powershell侦听器。 Powershell-Gallery中的代码:https://www.powershellgallery.com/packages/HttpListener/1.0.2

“客户端”使用以下示例URL调用侦听器: 使用Powershell,我可以这样做:

invoke-webrequest -Uri "http://127.0.0.1:8888/Test?id='1234'&param2='@@$$'&param3='This is a test!'"

我不知道如何将参数从url删除到Powershell中具有相同名称的变量。我需要将参数带到powershell变量以简单地回显它们。这是我最后缺少的部分。参数以&分隔,并且参数名区分大小写。

更详细地讲,URL中的id应该在一个名为$ id的powershell变量中,其值是1234。变量可以包含空格,特殊字符,数字,字母。它们区分大小写。参数值可以是“我的名字是“安娜”!我的宠物名字是“贝洛”。”以及所有“脏”字符,例如“%$”!{[()。

有人可以指出正确的方法来解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

有效网址中,$字符应转义到%24 网址转义形式的另一个“脏”字符%是%25 这意味着示例网址无效,并且应为:

$url = "http://127.0.0.1:8888/Test?id='1234'&param2='@@%24%24'&param3='This is a test!'"

然后执行以下操作

$url = "http://127.0.0.1:8888/Test?id='1234'&param2='@@%24%24'&param3='This is a test!'"

if ($url -is [uri]) {
    $url = $url.ToString()
}
# test if the url has a query string
if ($url.IndexOf('?') -ge 0) {
    # get the part of the url after the question mark to get the query string
    $query = ($url -split '\?')[1]    
    # or use: $query = $url.Substring($url.IndexOf('?') + 1)

    # remove possible fragment part of the query string
    $query = $query.Split('#')[0]

    # detect variable names and their values in the query string
    foreach ($q in ($query -split '&')) {
        $kv = $($q + '=') -split '='
        $varName  = [uri]::UnescapeDataString($kv[0]).Trim()
        $varValue = [uri]::UnescapeDataString($kv[1])
        New-Variable -Name $varname -Value $varValue -Force
    }
}
else {
    Write-Warning "No query string found as part of the given URL"
}

通过将新创建的变量写入控制台来证明这一点

Write-Host "`$id = $id"
Write-Host "`$param2 = $param2"
Write-Host "`$param3 = $param3"

在此示例中将打印

$id = '1234'
$param2 = '@@$$'
$param3 = 'This is a test!'

但是,我个人不想创建这样的变量,因为存在覆盖已存在的变量的风险。 我认为最好将它们存储在这样的哈希中:

# detect variable names and their values in the query string
# and store them in a Hashtable
$queryHash = @{}
foreach ($q in ($query -split '&')) {
    $kv = $($q + '=') -split '='
    $name = [uri]::UnescapeDataString($kv[0]).Trim()
    $queryHash[$name] = [uri]::UnescapeDataString($kv[1])
}
$queryHash

输出

Name                           Value
----                           -----
id                             '1234'
param2                         '@@$$'
param3                         'This is a test!'
相关问题