Showing posts with label powershell. Show all posts
Showing posts with label powershell. Show all posts

Friday, 7 October 2016

Web request with HTTP authentication from Powershell

Web requests can be made from Powershell with HTTP authentication in the following 2 ways:

1. Using credential objects
$username = "foo"
$password = "bar" | ConvertTo-SecureString -asPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($username,$password)
$res = Invoke-WebRequest http://localhost:3000 -Credential $cred
$res.Content


2. Adding appropriate header
$acctname = "foo"
$password = "bar"
$params = @{uri = 'http://localhost:3000';
                   Method = 'Get'; #(or POST, or whatever)
                   Headers = @{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$($acctname):$($password)"));
           } #end headers hash table
   } #end $params hash table
$var = curl @params


Curl above is same as Invoke-WebRequest because on Windows, by default curl is just an alias to Invoke-WebRequest.


A JSON request with a body can be made as follows:

$res = Invoke-WebRequest http://localhost:3000/stores -Credential $cred -Method POST -Headers @{"Content-Type"="application/json"} -Body (ConvertTo-Json @{"Key"="Value"})

Thursday, 9 May 2013

Operating on each file in a directory in Windows Powershell

Recently, when I had to do some tasks on a Windows machine, I thought of trying out the Powershell. I had to process every file in a directory. In linux, I could easily do it on the command line so I tried to find out similar way for Windows. It turned out to be fairly simple actually.

$files=get-childitem .
foreach ($file in $files) { echo $file.fullname  }