Thursday, October 3, 2013

PowerShell Curl Awesomeness

I needed to translate a curl command into a PowerShell command the other day for some reporting that I need to get done with Rackspace's Cloud Files solution.

Before I could get started, I grabbed some of the Rackspace PowerShell bits at http://developer.rackspace.com/blog/powerclient-rackspace-cloud-api-powershell-client.html.  It turns out that, as of my time of need for this module from Rackspace, the module had no Cloud Files features in it.  So I rolled my own.  I was given a quick curl command from the fanatical support tech at Rackspace to grab the data I needed for my reports.  I'm working on learning PowerShell, so I decided to find a nice PowerShell way to get my curl goodies.  Most folks will say that you should use Invoke-RestMethod, but the problem with this approach is that it does not return any headers.  Rackspace returns the information I need in the header.  Instead, I need to use Invoke-WebRequest.  The return value has a Headers property that gives you access to the response headers.  So my cool little script looks like this:



function WriteOutFileStats($count, $byteCount){
Write-Host ([string]::Format("Files = {0:N0}", $count))
$gbCount = $byteCount / 1024 / 1024 / 1024
Write-Host ([string]::Format("Size(GB) = {0:N2}", $gbCount))
}

Write-Host "Rackspace------------------------------------------------------------------------------"
Import-Module PowerClient
Get-AuthToken
$rackspaceUrl = ""
foreach ($service in $token.access.serviceCatalog.service)
{
    if ($service.name -eq "cloudFiles")
    {
        foreach ($endpoint in $service.endpoint)
        {
            if ($endpoint.region -eq "ORD")
            {
                $rackspaceUrl = $endpoint.publicURL
            }
        }
    }
}
$resp = Invoke-WebRequest -Uri $rackspaceUrl -Headers $HeaderDictionary -Method Head
WriteOutFileStats $resp.Headers["X-Account-Object-Count"] $resp.Headers["X-Account-Bytes-Used"]
Write-Host (Get-Date)

No comments:

Post a Comment