【发布时间】:2017-01-13 12:37:01
【问题描述】:
我正在尝试创建一个仅请求 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');"
然后我遇到了以下问题:
错误:
术语“=New-Object”未被识别为 cmdlet 的名称, 函数、脚本文件或可运行的程序
我尝试了另一个脚本,它也可以作为 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"
错误:
无效的赋值表达式。作业的左侧 运算符必须是可以分配给变量的东西 或财产。在 line:1 char:102
根据get-host 命令我有powershell v 2.0。上面的一行脚本有什么问题?
【问题讨论】:
-
powershell ... -Command "&{$webclient = ...}" -
@AnsgarWiechers 谢谢,但不幸的是,在这种情况下调用运算符 (&) 对我没有帮助,我得到了同样的错误:/
-
那是因为您是从 PowerShell 运行命令行,而不是像您说的那样将其作为计划任务运行。如果您需要从交互式控制台运行它,请使用 CMD 模拟一个更类似于计划任务的环境。
-
是的,你是对的!它在 powershell 中不起作用,但在 cmd 中起作用。我认为在哪里测试脚本并不重要。太感谢了!如果您希望我将此问题标记为已解决,请复制您的第一条评论作为答案。