简体   繁体   English

用户powershell脚本发布到URL?

[英]User powershell script to post to URL?

I have inherited the following Python script: 我继承了以下Python脚本:

import urllib2
a = urllib2.urlopen('http://mysite/mypage.aspx?action=dosomething')
a.read()
a.close()

and I would like to replace it with a powershell script. 我想用powershell脚本替换它。 I have googled a little but everything I find launches a browser window. 我用谷歌搜索了一下,但我发现的一切都启动了一个浏览器窗口。

This script is going to be scheduled, so I'd like to just "post and forget" if possible? 这个脚本将被安排,所以我想尽可能“发布并忘记”?

Any help very gratefully received :) 任何帮助非常感谢收到:)

Starting with PowerShell v3, you can use Invoke-WebRequest or its alias iwr . 从PowerShell v3开始,您可以使用Invoke-WebRequest或其别名iwr

iwr 'http://mysite/mypage.aspx?action=dosomething'

If you need the output the same as the Python script, use the Content property of the response. 如果您需要与Python脚本相同的输出,请使用响应的Content属性。

(Invoke-WebRequest 'http://mysite/mypage.aspx?action=dosomething').Content

As @stej wrote, the Python code looks like a GET, but if you do need POST you can use the Method parameter. 正如@stej所写,Python代码看起来像一个GET,但是如果你确实需要POST,你可以使用Method参数。

iwr 'http://mysite/mypage.aspx?action=dosomething' -Method Post

Function urlopen looks like HTTP GET. 函数urlopen看起来像HTTP GET。 Then you can use WebClient : 然后你可以使用WebClient

$w = New-Object net.webclient
$w.DownloadString('http://mysite/mypage.aspx?action=dosomething')

For HTTP POST I use this function: 对于HTTP POST,我使用此功能:

function Execute-HTTPPostCommand()
{
  param(
    [string] $url = $null,
    [string] $data = $null,
    [System.Net.NetworkCredential]$credentials = $null,
    [string] $contentType = "application/x-www-form-urlencoded",
    [string] $codePageName = "UTF-8",
    [string] $userAgent = $null
  );

  if ( $url -and $data )
  {
    [System.Net.WebRequest]$webRequest = [System.Net.WebRequest]::Create($url);
    $webRequest.ServicePoint.Expect100Continue = $false;
    if ( $credentials )
    {
      $webRequest.Credentials = $credentials;
      $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();
  }
}

Here is a script I wrote a while back that shows how to post tweets with Geotags. 这是我之前写的一个脚本,它显示了如何使用Geotags发布推文。 This uses WebClient. 这使用WebClient。

http://www.ravichaganti.com/blog/?p=979 http://www.ravichaganti.com/blog/?p=979

Pasting the code here for easy reference. 在此处粘贴代码以便于参考。

Function ByPass-Proxy {
    param ([string]$url)
    $webClient.Proxy.IsBypassed($url)
}

Function Get-GeoCoordinates {
    param ([String]$location)
    $baseURL = "http://maps.google.com/maps/geo?q="
    $apiKey = "Your API Key"
    $url = $baseURL + $location + "&output=xml&sensor=false&key=" + $apiKey
    $locCoords = (([xml]($WebClient.DownloadString($url))).kml.Response.Placemark.Point.coordinates)
    return $locCoords
}

Function Send-Tweet {
    param ([string]$Tweet,[string]$location)
    $geoCoord = Get-GeoCoordinates $location
    $long = $geoCoord.Split(",")[0]
    $lat = $geoCoord.Split(",")[1]
    $TwitURL = "http://twitter.com/statuses/update.xml"
    $WebClient.Credentials = $TwitCredentials
    #$str = [System.Text.Encoding]::UTF8.GetBytes( "status="  + $Tweet + "&lat=" + $lat + "&long=" + $long )
    $str = "status="  + $Tweet + "&lat=" + $lat + "&long=" + $long
    [System.Net.ServicePointManager]::Expect100Continue = $false
    $response = $WebClient.UploadString($TwitURL,$str)
    $response
}

function Get-Credential { 
## Grabbed this from http://poshcode.org/1480

[CmdletBinding(DefaultParameterSetName="Better")]
PARAM(
   [Parameter(Position=1,Mandatory=$false)]
   [Alias("Credential")]
   [PSObject]$UserName=$null,
   [Parameter(Position=2,Mandatory=$false)]
   [string]$Title=$null,
   [Parameter(Position=3,Mandatory=$false)]
   [string]$Message=$null,
   [Parameter(Position=4,Mandatory=$false)]
   [string]$Domain=$null,
   [Parameter(Mandatory=$false)]
   [switch]$GenericCredentials,
   [Parameter(Mandatory=$false)]
   [switch]$Inline
)

PROCESS {
   if( $UserName -is [System.Management.Automation.PSCredential]) {
      return $UserName
   } elseif($UserName -ne $null) {
      $UserName = $UserName.ToString()
   }

   if($Inline) {
      if($Title)    { Write-Host $Title }
      if($Message)  { Write-Host $Message }
      if($Domain) { 
         if($UserName -and $UserName -notmatch "[@\\]") { 
            $UserName = "${Domain}\${UserName}"
         }
      }
      if(!$UserName) {
         $UserName = Read-Host "User"
         if(($Domain -OR !$GenericCredentials) -and $UserName -notmatch "[@\\]") {
            $UserName = "${Domain}\${UserName}"
         }
      }
      return New-Object System.Management.Automation.PSCredential $UserName,$(Read-Host "Password for user $UserName" -AsSecureString)
   }
   if($GenericCredentials) { $Credential = "Generic" } else { $Credential = "Domain" }

   ## Now call the Host.UI method ... if they don't have one, we'll die, yay.
   ## BugBug? PowerShell.exe disregards the last parameter
   $Host.UI.PromptForCredential($Title, $Message, $UserName, $Domain, $Credential,"Default")
}
}

$global:webClient = New-Object System.Net.WebClient
$global:TwitCredentials = Get-Credential -title "Twitter Credentials" -message "Please enter your Twitter username/password"
If (!(ByPass-Proxy "http://www.twitter.com")) {
    $global:Webclient.proxy.Credentials = Get-Credential -title "Proxy Credentials" -message "Please enter username/password for Proxy authentication"
}

You can use the Webclient class from .NET, especially UploadString or UploadValues . 您可以使用.NET中的Webclient类,尤其是UploadStringUploadValues Do a New-Object System.Net.WebClient to get a webclient object, and the rest should be straightforward. 做一个New-Object System.Net.WebClient来获取一个webclient对象,其余的应该是直截了当的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM