解析单行 powershell 脚本中的错误

parse error in one-line powershell script

我正在尝试创建一个只请求 url 的单行 powershell 脚本。当我 运行 作为 ps1 文件时,脚本工作正常:

文件"test.ps1":

$webclient=New-Object "System.Net.WebClient"
$data=$webclient.DownloadString("https://google.com")

我 运行 这个脚本在 PS 控制台中是这样的:

PS C:\test.ps1 -ExecutionPolicy unrestricted

这个 运行 没有任何问题,但是当我尝试安排这个脚本并根据 these recommendations 使其成为单行时,即将 "" 替换为 '' 并用 ; 分隔命令,因此结果将是:

一行:

powershell -ExecutionPolicy unrestricted -Command "$webclient=New-Object 'System.Net.WebClient'; $data=$webclient.DownloadString('https://google.com');"

然后我遇到了以下问题:

错误:

The term '=New-Object' is not recognized as the name of a cmdlet, function, script file, or operable program

我尝试了另一个脚本,它也可以作为 ps1 文件工作,但不能作为单行文件工作:

$request = [System.Net.WebRequest]::Create("https://google.com")
$request.Method = "GET"
[System.Net.WebResponse]$response = $request.GetResponse()
echo $response

一行:

powershell -ExecutionPolicy unrestricted -Command "$request = [System.Net.WebRequest]::Create('https://google.com'); $request.Method = 'GET'; [System.Net.WebResponse]$response = $request.GetResponse(); echo $response"

错误:

Invalid assignment expression. The left hand side of an assignment operator needs to be something that can be assigned to like a variable or a property. At line:1 char:102

根据 get-host 命令,我有 powershell v 2.0。上面的一行脚本有什么问题?

将您想要 运行 的语句放入脚本块中,然后通过调用运算符 运行 该脚本块:

powershell.exe -Command "&{$webclient = ...}"

请注意,将此命令行粘贴到 PowerShell 控制台会产生误导性错误,因为 PowerShell(您将命令行粘贴到其中的那个)会将字符串中的(未定义的)变量扩展为空值,然后 auto-converted 为空字符串。如果你想像这样测试命令行,运行 它来自 CMD,而不是 PowerShell。

让脚本块以状态代码退出也是个好主意,例如

&{...; exit [int](-not $?)}

&{...; $status=$response.StatusCode.value__; if ($status -eq 200) {exit 0} else {exit $status}}