我正在尝试生成一个包含(IF,Else)语句的powershell脚本。主要是由于不同版本如何调用Web请求的兼容性问题。
V < 2.0 : Uses [System.Net.WebRequest] for HTTP Requests
&安培;
V > 2.0 : Uses Invoke-WebRequest
这是我的代码:
$pcName="$ENV:COMPUTERNAME";
$psVers=$host.Version.Major;
if ($psVers -le 2)
{$request = [System.Net.WebRequest]::Create('http://xxx.co.kr');
$request.Method = "POST"; $request.ContentType = "application/x-www-form-urlencoded";
$bytes = [System.Text.Encoding]::ASCII.GetBytes("pcName=$pcName");
$request.ContentLength = $bytes.Length; $requestStream = $request.GetRequestStream();
$requestStream.Write( $bytes, 0, $bytes.Length ); $requestStream.Close();
$request.GetResponse();}
Else
{$POSTdata = @{pcName=$pcName}
Invoke-WebRequest -Uri http://xxx.co.kr -Method POST -Body $POSTdata};
以下是我从Powershell v-2.0收到的错误:
The term 'Else' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelli
ng of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:5
+ Else <<<<
+ CategoryInfo : ObjectNotFound: (Else:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
答案 0 :(得分:0)
删除Else关键字上方的空行:
$pcName="$ENV:COMPUTERNAME";
$psVers=$host.Version.Major;
if ($psVers -le 2)
{$request = [System.Net.WebRequest]::Create('http://xxx.co.kr');
$request.Method = "POST"; $request.ContentType = "application/x-www-form-urlencoded";
$bytes = [System.Text.Encoding]::ASCII.GetBytes("pcName=$pcName");
$request.ContentLength = $bytes.Length; $requestStream = $request.GetRequestStream();
$requestStream.Write( $bytes, 0, $bytes.Length ); $requestStream.Close();
$request.GetResponse();}
Else
{$POSTdata = @{pcName=$pcName}
Invoke-WebRequest -Uri http://xxx.co.kr -Method POST -Body $POSTdata};