0

尝试使用我从 Github 获取的以下 Powershell 脚本将数据推送到 Ducksboard 仪表板。该函数运行良好,但是我需要输入一个变量作为数据的一部分。在对函数的两个调用中,包含在实际值 44 中的函数可以正常工作,但是如果我用它代替我的变量 $qtybord 函数就会失败。我已经尝试了多种选项来克服单引号内的 var 但无法使其工作 - 任何人都可以帮助我吗?

# Squirt data to Duscksboard
    function Execute-DucksboardApi
    {
      param(
        [string] $url = $null,
        [string] $data = $null,
        [string] $apikey = $null,
        [string] $contentType = "application/json",
        [string] $codePageName = "UTF-8",
        [string] $userAgent = $null
      );

      if ($url -and $data -and $apikey)
      {
        [System.Net.WebRequest]$webRequest = [System.Net.WebRequest]::Create($url);
        $webRequest.ServicePoint.Expect100Continue = $false;
        [System.Net.NetworkCredential]$credentials = New-Object System.Net.NetworkCredential($apikey, 'ignored');
        $webRequest.Credentials = $credentials.GetCredential($url, 'Basic');
        $webRequest.PreAuthenticate = $true;
        $webRequest.ContentType = $contentType;
        $webRequest.Method = "POST";
        if ( $userAgent )
        {
          $webRequest.UserAgent = $userAgent;
        }

        $enc = [System.Text.Encoding]::GetEncoding($codePageName);
        [byte[]]$bytes = $enc.GetBytes($data);
        $webRequest.ContentLength = $bytes.Length;
        [System.IO.Stream]$reqStream = $webRequest.GetRequestStream();
        $reqStream.Write($bytes, 0, $bytes.Length);
        $reqStream.Flush();

        $resp = $webRequest.GetResponse();
        $rs = $resp.GetResponseStream();
        [System.IO.StreamReader]$sr = New-Object System.IO.StreamReader -argumentList $rs;
        $sr.ReadToEnd();
      }
    }

    $qtybord = 44

    Execute-DucksboardApi -url 'https://push.ducksboard.com/v/123752/' -data '{"value": $qtybord}' -apikey 'tu2j3d3epqytWZD1haHnjJSJ1NqBrmvPe5SONc0VYge4BbIPi0'

Execute-DucksboardApi -url 'https://push.ducksboard.com/v/123752/' -data '{"value": 44}' -apikey 'tu2j3d3epqytWZD1haHnjJSJ1NqBrmvPe5SONc0VYge4BbIPi0'

*

4

2 回答 2

0

试试这个:

-data "{`"value`": $qtybord}"

或者

-data "{""value"": $qtybord}"

在单引号变量中不展开,在双引号中您需要转义字符串内的双引号。

于 2013-03-20T12:46:55.850 回答
0

所以让 -data 参数取 $data 而不是 $data = '{"value": ' + $qtyboard + '}' 或者只是在 -data 之后将整个东西包装在括号中。

此外,如果您使用的是 PowerShell v3,则可以使用以下内容:

$data = New-Object -Type PSObject -Property @{
   value = $qtyboard
} | ConvertTo-JSON
于 2013-03-20T12:48:02.153 回答