【问题标题】:Variable in Invoke-WebRequest -Uri pathInvoke-WebRequest -Uri 路径中的变量
【发布时间】:2019-09-16 09:59:04
【问题描述】:

我正在尝试将 MAC 地址和代码 (1,2,3,4) 传递给 Invoke-WebRequest。 手动命令可以正常工作,但我无法通过命令完成。

有效的手动命令是:

Invoke-WebRequest -Uri https://mywebsite.org/pcconfig/setstate.php?mac=F832E3A2503B"&"state=4

现在,当我将其分解为变量以与机器上的 mac 一起使用时,我会执行以下操作。

$LiveMAC = Get-NetAdapter -Physical |
           where Status -eq "Up" |
           Select-Object -ExpandProperty PermanentAddress

$Str1 = "https://mywebsite.org/pcconfig/setstate.php?mac=$LiveMAC"
$Str2 = $Str1 + '"&"' + 'state=4'
Invoke-WebRequest -Uri $Str2

当我运行上面的代码时,我没有看到红色的错误,它似乎正在处理但不起作用。

查看$Str2 我看到下面的输出,这似乎是正确的,但是当像上面那样传递它时它无法工作。

https://mywebsite.org/pcconfig/setstate.php?mac=F832E3A2503B"&"state=4

【问题讨论】:

    标签: powershell invoke-webrequest


    【解决方案1】:

    语句中的双引号

    Invoke-WebRequest -Uri https://example.org/some/sit.php?foo=x"&"bar=y
    

    屏蔽 PowerShell 的 & 符号,否则 PowerShell 会抛出一个错误,即保留裸露的 & 以供将来使用。避免这种情况的更规范方法是将整个 URI 放在引号中:

    Invoke-WebRequest -Uri "https://example.org/some/sit.php?foo=x&bar=y"
    

    无论哪种方式,传递给 Invoke-WebRequest 的实际 URI 都是

    https://example.org/some/sit.php?foo=x&bar=y

    没有引号。

    但是,在这样的代码 sn-p 中:

    $Str1 = "https://example.org/some/site.php?foo=$foo"
    $Str2 = $Str1 + '"&"' + 'state=4'
    

    您将文字双引号作为 URI 的一部分,因此传递给 cmdlet 的实际 URI 将是

    https://example.org/some/sit.php?foo=x"&"bar=y

    这是无效的。

    话虽如此,您仍然不需要字符串连接来构建您的 URI。只需将您的变量放在双引号字符串中:

    $uri = "https://example.org/some/sit.php?foo=${foo}&bar=y"
    

    如果您需要插入对象属性或数组元素的值,请使用子表达式

    $uri = "https://example.org/some/sit.php?foo=$($foo[2])&bar=y"
    

    或格式操作符

    $uri = 'https://example.org/some/sit.php?foo={0}&bar=y' -f $foo[2]
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-17
    • 2012-01-19
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    相关资源
    最近更新 更多