Viser opslag med etiketten Powershell. Vis alle opslag
Viser opslag med etiketten Powershell. Vis alle opslag

fredag den 30. maj 2014

System Center Service Manager Automation

I’ve never worked with SCSM before, but a few weeks back I was asked to implement some automation processes using Microsoft Orchestrator (also a new product for me).

One of the jobs needed to add a user to a group, and you would expect something so simple would be easy. But after reading this guide, I ended up with this

image

Are you freaking kidding me ? My life is just to short for that, so after a while I ended up with this instead

image

The main problem lies in the fact that you need to fetch a lot of related objects. You start by sending the GUID of the Automation job inside SCSM. You then get the related objects, and finally you fetch the real AD objects. The job will of course fail if the user is already member of the group, so feel free to add 5-10 more steps for check group members ships too. Gaaaahhh

So lets look at the PowerShell script instead. First a little back ground. To run PowerShell scripts you need to install a Management pack. I choose Orchestrator Integration Pack for PowerShell Script Execution . Next we need a way to “talk” with SCSM from PowerShell, and I choose SMLETS for that. You need to be aware you can run into some issues with “double hob” when running the PowerShell scripts, so I choose to configure an service account and configure the PowerShell scripts to run on the SCSM server, and the use CredSSP as authentication scheme.

image

And we of course need to pass the GUID of the automation job in SCSM to the PowerShell script

image

And now to the good part. I’ve attached 2 scripts like the “normal” examples you find while goggling. “Add self to group” and “add user to group”. The first assumes an AD Group object has been associated with the Service Request. The latter, assumes an AD User Object and AD Group Object has been associated with the Service Request. You could associate the objects with either the Automation Request or Service Request, doesn’t really matter, the script is easy to modify for either.

As an added bonus you will also find some scripts for handling office 365 subscripts, users, licenses and management of SharePoint Online Service users in a federated environment. And notes about how to call Orchestrator run books from PowerShell completely dynamically with parameters.
(download link)

[CmdLetBinding(DefaultParameterSetName="None")]
param (
[Parameter(Mandatory=$true)][string]$ActivityGuid
)

$logscope = "AddUserToGroup"
$logname = "log"
. 'C:\Runbook\ServiceManager\functions\Initialization.ps1'
WriteHost "ActivityGuid: $ActivityGuid" -class $logscope

# Get current RunBook Activity in Service Manager
$runbook = Get-SCSMObject $ActivityGuid

# Dynamicly find related object (should only be one, of type Service Request )
$serviceRequest = (Get-SCSMRelationshipObject -ByTarget $runbook).SourceObject

$relationClass = Get-SCSMRelationshipClass System.WorkItemRelatesToConfigItem$
$scsmobjects = Get-SCSMRelatedObject -SMObject $ServiceRequest -Relationship $relationClass
$aduser = $null;$adgroup = $null;
foreach($scsmobject in $scsmobjects)
{
$adobject = Get-ADObject $scsmobject.DistinguishedName
if($adobject.ObjectClass -eq 'user')
{
$aduser = Get-ADUser $scsmobject.DistinguishedName
WriteHost "Found user in ad as $($aduser.Name) $($aduser.UserPrincipalName)" -class $logscope
} elseif($adobject.ObjectClass -eq 'group') {
$adgroup = Get-ADGroup $scsmobject.DistinguishedName
WriteHost "Found group in ad as $($adgroup.Name) $($adgroup.UserPrincipalName)" -class $logscope
}
}

if($aduser -and $adgroup)
{
WriteHost "Ensuring $($aduser.UserPrincipalName) is a member of '$($adgroup.Name)'" -class $logscope
# and now. The moment we have all been wating for .. Tadaaaaa, drum roll, blow the trompets, scream hale-juja, and add the user to the group!
Add-ADGroupMember -Identity $adgroup -Members $aduser
} else {
WriteHost "Failed locating user or group in ad!" -class $logscope
Throw "Failed locating user or group in ad!"
}

WriteHost "--Completed--" -class $logscope

XenApp hotfix management

One thing I never understood is how to figure out what patches are needed on a XenApp server. And it has always annoyed me with the whole process of needing to download everything and never knowing what fixes need a reboot.

So a few days ago I started searching for something smarter. Here someone made a script to get the patches but it only works with newer versions of PowerShell, and here someone made a complete solution. but, I like the ability to get status back and it doesn’t seem to check if a patch is actually needed. So I combined the two, into one PowerShell script that also works in PowerShell 2.0.
( download link )

Set-Location 'c:\'
$snapin = Get-PSSnapin | where {$_.name -eq 'Citrix.Common.Commands'}
if($snapin -eq $null){ Add-PSSnapin Citrix.Common.Commands }
$snapin = Get-PSSnapin | where {$_.name -eq 'Citrix.XenApp.Commands'}
if($snapin -eq $null){ Add-PSSnapin Citrix.XenApp.Commands }

function installXenappHotfix([string]$HotfixName, [string]$hotfixpath ){
$exitcode = (Start-Process -FilePath "msiexec.exe" -ArgumentList "/qb /passive /norestart /p `"$hotfixpath`"" -Wait -Passthru).ExitCode
if($exitcode -eq 3010){
$exitcode = 1604
#Write-Host 'Restart needed, so restarting. doh!'
#restart-computer -force -throttlelimit 10; exit $exitcode
#exit $exitcode
return $exitcode
}
if($exitcode -ne 0){
Write-Host ('Unknown exitcode: ' + $exitcode)
#exit $exitcode
return $exitcode
}
return 0
}


function installXenappHotfixWithIsNeededCheck([string]$HotfixName, [string]$hotfixpath ){
# Get current computername and XenServer object
$computername = $env:computername

$isInstalled = $false;
try {
foreach($hotfix in (Get-XAServerHotFix -ServerName $computername)){
if($hotfix.HotfixName -eq $HotfixName){ $isInstalled = $true; }
}
# IMA service proberly not running.
} catch {
if($_.invocationinfo) {
status ($_.Exception.Message + "`n `n" + $_.InvocationInfo.PositionMessage)
} else {
status $_.ToString()
}
return 1604
}
if($isInstalled -eq $false){
Write-Host ('Missing ' + $HotfixName)
$exitcode = (Start-Process -FilePath "msiexec.exe" -ArgumentList "/qb /passive /norestart /p `"$hotfixpath`"" -Wait -Passthru).ExitCode
if($exitcode -eq 3010){
$exitcode = 1604
Write-Host 'Restart needed, so restarting. doh!'
#restart-computer -force -throttlelimit 10; exit $exitcode
#exit $exitcode
return $exitcode
}
if($exitcode -ne 0){
Write-Host ('Unknown exitcode: ' + $exitcode)
#exit $exitcode
return $exitcode
}
} else {
# Write-Host ($HotfixName + ' ok')
return 0
}
}

function Get-URLContent ($url) {
$client = new-object System.Net.WebClient
#$client.DownloadFile( $url, [IO.Path]::GetTempFileName() )
return $client.downloadString($url)
}
function Get-URLFile ($url, $saveas) {
$client = new-object System.Net.WebClient
#$client.DownloadFile( $url, [IO.Path]::GetTempFileName() )
$client.DownloadFile( $url, $saveas )
}

function CheckXenappHotfix() {
# XenApp 6.5 : $url = "http://support.citrix.com/product/xa/v6.5_2008r2/hotfix/general/?rss=on"
# XenApp 6.0 : $url = "http://support.citrix.com/product/xa/v6.0_2008r2/hotfix/general/?rss=on"
# XenApp 5.0 : $url = "http://support.citrix.com/product/xa/v5.0_2008/hotfix/general/?rss=on"

# PVS 6.1 : $url = "http://support.citrix.com/product/provsvr/pvsv6.1/hotfix/general/?rss=on"
}

$hotfixurl = 'http://support.citrix.com/product/xa/v6.0_2008r2/hotfix/general/?rss=on'
$source = Join-Path (Get-Location).Path 'xa_hotfix'
if(! (Test-Path $source)) { New-Item -ItemType directory -Path $source | Out-Null }

$service = Get-Service imaservice
if($service.Status.ToString() -eq 'Stopped') {
Get-Service imaservice | Start-Service
}
try {
$computername = $env:computername
$installed = (Get-XAServerHotFix -ServerName $computername)
} catch {
if($_.invocationinfo) {
write-error ($_.Exception.Message + "`n `n" + $_.InvocationInfo.PositionMessage)
} else {
write-error $_.ToString()
}
}

write-progress -id 1 -Activity "Xenapp Hotfix Script" -Status "Fetch lastest xenapp hotfixes"
write-progress -id 2 -ParentId 1 -Activity "Xenapp Hotfix Script" -Status "Fetch $hotfixurl"

$hotfixes = @()
$xml = [xml](Get-URLContent $hotfixurl)
foreach($fix in $xml.rdf.item) {
write-progress -id 2 -ParentId 1 -Activity "Xenapp Hotfix Script" -Status "Fetch $($fix.link)"

$html = Get-URLContent $fix.link
$pattern = '(?<=.)/servlet/KbServlet/download/.+?(?=")'
$results = ($html | Select-String -Pattern $Pattern -AllMatches).Matches | select value
if($results) {
if($results -is [system.array]){ $results = $results[0] }
$url = ('http://support.citrix.com' + $results.Value)
$filename = [string][io.path]::GetFileName($url)
if($filename.Contains('.msp')) {
$HotfixName = [string][io.path]::GetFileNameWithoutExtension($filename)
if(! ($installed | ?{$_.HotfixName -eq $HotfixName})) {
$saveas = (Join-Path $source $filename)
if(! (Test-Path $saveas)) {
write-progress -id 2 -ParentId 1 -Activity "Xenapp Hotfix Script" -Status "Downloading $filename"
write-verbose "Downloading $filename"
Get-URLFile $url $saveas
} else {
write-progress -id 2 -ParentId 1 -Activity "Xenapp Hotfix Script" -Status "$filename has allready been downloaded"
write-verbose "$filename has allready been downloaded"
}
$hotfixes += $saveas
} else {
write-progress -id 2 -ParentId 1 -Activity "Xenapp Hotfix Script" -Status "$filename has allready been installed"
write-verbose "$filename has allready been installed"
}
} else {
write-progress -id 2 -ParentId 1 -Activity "Xenapp Hotfix Script" -Status "skipping $filename"
write-verbose "skipping $filename"
}
}
}

$needreboot = $false
$updateSystemInfo = new-object -com Microsoft.Update.SystemInfo
if($updateSystemInfo.rebootRequired){ $needreboot = $true }

write-progress -id 1 -Activity "Xenapp Hotfix Script" -Status "Installing missing xenapp hotfixes"
foreach($filename in $hotfixes) {
$HotfixName = [string][io.path]::GetFileNameWithoutExtension($filename)
write-progress -id 2 -ParentId 1 -Activity "Xenapp Hotfix Script" -Status "Installing $HotfixName"

$exitcode = installXenappHotfix $HotfixName $filename
# ERROR_SUCCESS_REBOOT_REQUIRED
if($exitcode -eq 3010){ $needreboot = $true; }
if($exitcode -eq 1642){
# some hotfixes will shut down the IMA service
# If you then start the service without rebooting it will not report the patch installed
# if that is NOT the case, go do some troubleshootnig to figure out what is wrong

Write-Warning "$HotfixName has allready been installed (ERROR_PATCH_TARGET_NOT_FOUND)"
$needreboot = $true
}
}

write-progress -id 2 -ParentId 1 -Activity "Xenapp Hotfix Script" -Status "n/a" -Completed
if($needreboot) {
write-progress -id 2 -ParentId 1 -Activity "Updating" -Status "Rebooting system"
Write-Warning "Reboot required"
Restart-Computer -Force
}

Windows Update with PowerShell

I’ve had a PowerShell script (rewritten from VBS) for a long time. It works and all, but once in a while when your testing stuff on fresh machines it would drive me nuts I couldn’t get a “status” like when your doing it though GUI.

Doing a progress bar while downloading is/was easy enough, but we all know it’s the installation that takes time, and that gave me a few issues. I finally figured out, I couldn’t re-use the installer, and sometimes it fails if you assign each update without first adding it to an “UpdateColl”. So, here it is (download link)

[CmdletBinding()]
Param
(
[switch]$skipReboot
)
Begin {
$Install = $true;
$EulaAccept = $true;

write-progress -id 1 -Activity "Windows Update" -Status "Initialising"
$UpdateSession = New-Object -ComObject 'Microsoft.Update.Session'
$UpdateSession.ClientApplicationID = 'Wingu Update Client'
}
Process {
write-progress -id 1 -Activity "Windows Update" -Status "Checking for available updates"
$UpdateSearcher = $UpdateSession.CreateUpdateSearcher()
$SearchResult = $UpdateSearcher.Search("IsInstalled=0 and Type='Software'") # and IsHidden=0
$UpdatesToDownload = New-Object -com Microsoft.Update.UpdateColl
foreach ($Update in $SearchResult.Updates)
{
[bool]$addThisUpdate = $false
if ($Update.InstallationBehavior.CanRequestUserInput)
{
#Write-Verbose "> Skipping: $($Update.Title) because it requires user input"
[bool]$addThisUpdate = $true
} else {
if (!($Update.EulaAccepted)) {
Write-Verbose "> Note: $($Update.Title) has a license agreement that must be accepted:"
$Update.AcceptEula() | Out-Null
[bool]$addThisUpdate = $true
} else {
[bool]$addThisUpdate = $true
}
}
if ([bool]$addThisUpdate) {
Write-Verbose "Adding: $($Update.Title)"
$UpdatesToDownload.Add($Update) | Out-Null
}
}
if ($UpdatesToDownload.Count -eq 0) {
Write-Verbose 'All applicable updates were skipped.'
return $false
}
$downloader = $updateSession.CreateUpdateDownloader()
foreach($update in $UpdatesToDownload) {
$counter += 1
write-progress -id 1 -Activity "Updating" -Status "Downloading $counter/$($UpdatesToDownload.count) updates"
if(!$update.IsDownloaded) {
write-progress -id 2 -ParentId 1 -Activity "Updating" -Status "Downloading $($update.Title) $([int]($update.MaxDownloadSize / 1MB))MB"
$updateCollection=New-Object -com Microsoft.Update.UpdateColl
$updateCollection.Add($Update) | Out-Null
$downloader.Updates = $updateCollection
$Result = $downloader.Download()
} else {
write-progress -id 2 -ParentId 1 -Activity "Updating" -Status "isready $($update.Title)"
}
}


$needreboot = $false
$updateSystemInfo = new-object -com Microsoft.Update.SystemInfo
if($updateSystemInfo.rebootRequired){ $needreboot = $true }
$counter = 0
foreach($update in $UpdatesToDownload) {
$counter += 1
write-progress -id 1 -Activity "Updating" -Status "Installing $counter/$($UpdatesToDownload.count) updates"
write-progress -id 2 -ParentId 1 -Activity "Updating" -Status "Installing $($update.Title)"
$updatesToInstall = New-object -com "Microsoft.Update.UpdateColl"
$updatesToInstall.Add($update) | out-null
$installer = $updateSession.CreateUpdateInstaller()
$updateCollection=New-Object -com Microsoft.Update.UpdateColl
$updateCollection.Add($Update) | Out-Null
if($installer.ForceQuiet -eq $false) { $installer.ForceQuiet=$true }
$installer.Updates = $updateCollection
$installationResult = $installer.Install()
if($installationResult.rebootRequired){ $needreboot = $true }
if($installationResult.HResult -eq 4) {
#$resultcode= @{0="Not Started"; 1="In Progress"; 2="Succeeded"; 3="Succeeded With Errors"; 4="Failed" ; 5="Aborted" }
Write-Warning "Failed installting $($update.Title) ResultCode $($installationResult.ResultCode) HResult $($installationResult.HResult)"
}
if($installationResult.HResult -eq 5) {
#$resultcode= @{0="Not Started"; 1="In Progress"; 2="Succeeded"; 3="Succeeded With Errors"; 4="Failed" ; 5="Aborted" }
Write-Warning "Aborted $($update.Title) ResultCode $($installationResult.ResultCode) HResult $($installationResult.HResult)"
}
}

if(!$needreboot) {
$arguments = @('/c wuauclt /reportnow')
Start-Process -FilePath "cmd.exe" -ArgumentList $arguments -Wait
}

if(!$skipReboot -and $needreboot){
write-progress -id 2 -ParentId 1 -Activity "Updating" -Status "Rebooting system"
Write-Warning "Reboot required"
Restart-Computer -Force
}
return $needreboot
}
End {
write-progress -id 1 -Activity "Updating" -Status "Windows Update Check Complete" -Completed
}

onsdag den 15. januar 2014

Managing CRM 2011 and 2013

I fixed a series of bugs and tested my CRM powershell module against both 2011 and 2013. Enjoy.

PSCRM.zip

Add-CRMRoleMember
Disable-CrmLanguage
Disable-CrmOrganization
Disable-CRMSystemUser
Enable-CrmLanguage
Enable-CrmOrganization
Enable-CRMSystemUser
Get-CrmAvailableLanguage
Get-CrmLanguage
Get-CrmOrganization
Get-CRMRole
Get-CRMSystemUser
Get-CRMSystemUserSettings
Get-CrmUsermappingFile
Import-CrmOrganization
New-CrmConfig
New-CRMCustomerAdminRole
New-CrmOrganization
New-CRMSystemUser
Remove-CrmOrganization
Remove-CRMRole
Remove-CRMRoleMember
Remove-CRMSystemUser
Select-CrmOrganization
Set-CRMSystemUser
Set-CRMSystemUserSettings

tirsdag den 14. januar 2014

Microsoft Dynamics Nav 2013 goodies

One of the cool things about Nav 2013 is the ClickOnce deployment. Running Nav in a multi Tenant depoyment with many customers can make this a bit of a headache. First of all you need several deployments, one for each customer (seems stupid when all you need is a different ClientUserSettings.config ( maybe we could create a iis module or something to handle this ? ) anyway, for now lets keep it like that. Next if you read this page they promise us gold in the form of having several installations at the same computer. That will not work following microsofts guide thou, you need to have different assemblyIdentity names for that to work. Thank god we have powershell …

 

$baseclientpath = 'C:\NAV2013R2\Install\RoleTailoredClient\program files\Microsoft Dynamics NAV\71\RoleTailored Client\'
$baseclientcommonpath = 'C:\NAV2013R2\Install\RoleTailoredClient\CommonAppData\Microsoft\Microsoft Dynamics NAV\71\'
$templatepath = 'C:\NAV2013R2\Install\ClickOnceInstallerTools\Program Files\Microsoft Dynamics NAV\71\ClickOnce Installer Tools\TemplateFiles\'
$clickoneroot = "C:\inetpub\wwwroot\ClickOnce\$tenantid\"
$clickoneDeployment = "$($clickoneroot)Deployment\"
$clickoneApp = "$($clickoneroot)Deployment\ApplicationFiles\"

#if ( (Test-Path $clickoneroot) -ne $true) {
Copy-Item $templatepath $clickoneroot -recurse -force

if ( (Test-Path "$($clickoneroot)default.html") -ne $true) {
Copy-Item "$($clickoneroot)NAVClientInstallation.html" "$($clickoneroot)default.html"
}

Write-Host "Remove Nav ClickOnce Client Application"
if ( (Test-Path $clickoneApp) -eq $true) { Remove-Item $clickoneApp -force -recurse }
Write-Host "Copy fresh Nav ClickOnce Client Application"
Copy-Item $baseclientpath $clickoneApp -recurse -force

Write-Host "Copy fresh templates"
Copy-Item "$($templatepath)Deployment\ApplicationFiles\Microsoft.Dynamics.Nav.Client.exe.manifest" $clickoneApp
Copy-Item "$($templatepath)Deployment\ApplicationFiles\Icon.ico" $clickoneApp
Copy-Item "$($templatepath)Deployment\Microsoft.Dynamics.Nav.Client.application" $clickoneDeployment
Copy-Item "$($baseclientcommonpath)ClientUserSettings.config" $clickoneApp


Write-Host "Remove OpenXml and ReportLayout"
Remove-Item "$($clickoneApp)Add-ins\OpenXml" -recurse -force
Remove-Item "$($clickoneApp)ReportLayout" -recurse -force
Remove-Item "$($clickoneApp)Finhlink.exe" -force
Remove-Item "$($clickoneApp)finsql.exe" -force
Remove-Item "$($clickoneApp)finsql.exe.config" -force

Write-Host "Update ClientUserSettings"
$xml = [xml](Get-Content "$($clickoneApp)ClientUserSettings.config")
($xml.configuration.appSettings.add | ?{$_.key -eq 'Server'}).value = $alternateId
($xml.configuration.appSettings.add | ?{$_.key -eq 'ClientServicesPort'}).value = $ClientServicesPort.ToString()
($xml.configuration.appSettings.add | ?{$_.key -eq 'ServerInstance'}).value = $navinstancename
($xml.configuration.appSettings.add | ?{$_.key -eq 'TenantId'}).value = $tenantid
($xml.configuration.appSettings.add | ?{$_.key -eq 'ClientServicesCredentialType'}).value = 'UserName'
($xml.configuration.appSettings.add | ?{$_.key -eq 'DnsIdentity'}).value = $navcertificatesubject
($xml.configuration.appSettings.add | ?{$_.key -eq 'HelpServer'}).value = $helpserver
($xml.configuration.appSettings.add | ?{$_.key -eq 'HelpServerPort'}).value = $helpserverport
($xml.configuration.appSettings.add | ?{$_.key -eq 'ProductName'}).value = $tenantproductname
$xml.Save("$($clickoneApp)ClientUserSettings.config")

$manifestfile = "$($clickoneApp)Microsoft.Dynamics.Nav.Client.exe.manifest"
$applicationfile = "$($clickoneDeployment)Microsoft.Dynamics.Nav.Client.application"
$baseclickoneurl = "https://$alternateId/ClickOnce/$tenantid"
$manifesturl = "$($baseclickoneurl)/Deployment/ApplicationFiles/Microsoft.Dynamics.Nav.Client.exe.manifest"
$codebaseurl = "$($baseclickoneurl)/Deployment/Microsoft.Dynamics.Nav.Client.application"

Write-Host "Update manifest file"
$xml = [xml](Get-Content $manifestfile)
$xml.assembly.assemblyIdentity.name = "Microsoft.Dynamics.Nav.$tenantid" # Microsoft.Dynamics.Nav.ClickOnceClient
$xml.assembly.assemblyIdentity.version = $clientversion
$xml.Save($manifestfile)

Write-Host "Update application file"
$xml = [xml](Get-Content $applicationfile)
$xml.assembly.description.publisher = 'Microsoft Corporation and Proinfo A/S'
$xml.assembly.description.product = $tenantproductname
$xml.assembly.assemblyIdentity.name = $tenantproductname
$xml.assembly.deployment.deploymentProvider.codebase = $codebaseurl
$xml.assembly.assemblyIdentity.version = $clientversion
$xml.assembly.dependency.dependentAssembly.assemblyIdentity.name = "Microsoft.Dynamics.Nav.$tenantid"
$xml.Save($applicationfile)


& C:\NAV2013R2\mage\mage.exe -Update $manifestfile -FromDirectory $clickoneApp

& C:\NAV2013R2\mage\mage.exe -update $applicationfile -appmanifest $manifestfile -appcodebase $manifesturl
Write-Host "Microsoft Dynamics Nav 2013 for $tenantid published at https://$alternateId/ClickOnce/$tenantid"
#}

lørdag den 23. februar 2013

SharePoint 2010 and claims based authentication made a little bit easier

updated 05/03-2013: Added support for extracting root cert from signing certificate
So you have ADFS 2.0 installed. Or your reading some guide about how to configure SharePoint to allow login in using Office 365 or Azure AD or any other kind of Secure Token Service. And 99,9% of them will tell you to copy 1 or more certificates, and run a lot of weird PowerShell command, and it all ends up with you being able to setup some awesome new login page here

image

Well, fear not. If your STS support generating a FederationMetadata.xml URL, you can now use this PowerShell Script to quickly setup your SPTrustedIdentityTokenIssuer . The script can also setup Uri mappings and configure the websites, but I do not recommend using that part in other than development/test environments. Make sure to modify the variables at the top.

I’ve updated the script. If your STS was using a self issued certificate, or a certificate from an internal CA, it wouldn’t be trusted by SharePoint, so added a bit of code to traverse the certificate chain, and then add the root certificate to the Trusted store and also add the root to the list of trusted certificates inside SharePoint

# URL for ADFS / ACS / Office 365 / SimpleSTS / Wingu Cloud ControlPanel / what ever

# $metadataurl = 'https://adfs.wingu.dk/FederationMetadata/2007-06/federationmetadata.xml' # ADFS
# $metadataurl = 'https://accounts.accesscontrol.windows.net/skadefro.onmicrosoft.com/FederationMetadata/2007-06/FederationMetadata.xml' # Azure AD
# $metadataurl = 'https://skadefro.accesscontrol.windows.net/FederationMetadata/2007-06/FederationMetadata.xml' # Azure ACS - Wont work, apperently the guy who made this, forgot to add the signing certificat .. :-(
# $metadataurl = 'https://simplests.wingu.dk/FederationMetadata.xml' # Simple STS
# $metadataurl = 'http://admin.wingu.dk/sts2/FederationMetadata/2007-06/federationmetadata.xml' # Wingu Cloud Control Panel
$metadataurl = 'https://simplests.wingu.dk/FederationMetadata.xml'


# This should really be NameID, but often people will use emails or UPN. choose what fits your needs
$IdentifierClaim = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"
# What claims do you want mapped. All will be exposed in the ClaimsToken, but what will show up in the people picker ?
$mapClaims = @('UPN', 'Role')

# Default realm. If you only have 1 website, you can add that here, but more correctly would be adding
# Each URI accessible on your farm, mapping it to a URN
# If your using Wingu Cloud Control Panal or SimpleSTS, urn:sps will automaticly be converte to a SharePoint signin URI
# urn:sps:http://spfarm01.cloudapp.net becomes http://spfarm01.cloudapp.net/_trust/
# if not, just use the full uri, like http://spfarm01.cloudapp.net/_trust/
# if you want several sharepoint sites to allow the user access without prompting for login each time,
# use one shared urn (not URI) for all those sites. There are certain restrictions, on how/where you can do that
$defaultrealm = 'urn:sps:https://sharepoint.domain.com'

# Be carefull with this. Not all STS' understand/support's this, and often the above is a simpler solution
# set this to true, will go though the list of sites in the farm and add an "urn:sps:URI" entry for each site
$autoGenerateProviderRealms = $false

# Dont, Dont, DONT ... D-O-N-T, use this
# This will add Windows and ALL identityProviders to all WebApplication's (except Central Admin) for the "default" zone.
$autoAddSTS = $false

$stsname = 'SimpleSTS'
$name = $stsname
$realm = $null
$stsd = $null
$asd = $null

$snapin = Get-PSSnapin | where {$_.name -eq 'Microsoft.SharePoint.PowerShell'}
if($snapin -eq $null){ Add-PSSnapin Microsoft.SharePoint.PowerShell }


function Get-medadata ($metadataurl) {
[void] [Reflection.Assembly]::LoadWithPartialName("Microsoft.IdentityModel")
$STSReader = New-Object Microsoft.IdentityModel.Protocols.WSFederation.Metadata.MetadataSerializer
$req = [System.Net.WebRequest]::Create($metadataurl)
$xmlreader = [System.Xml.XmlReader]::Create($req.GetResponse().GetResponseStream())
$metadata = $STSReader.ReadMetadata([System.Xml.XmlReader]$xmlreader)
$metadata
}

function Get-STS ($metadata) {
foreach($RoleDescriptor in $metadata.RoleDescriptors){
if($RoleDescriptor.GetType().FullName -eq 'Microsoft.IdentityModel.Protocols.WSFederation.Metadata.SecurityTokenServiceDescriptor'){
# metadata have a STS
$stsd = $RoleDescriptor
} elseif($RoleDescriptor.GetType().FullName -eq 'Microsoft.IdentityModel.Protocols.WSFederation.Metadata.ApplicationServiceDescriptor'){
# metadata have a Relying Party
$asd = $RoleDescriptor
}
}
$stsd
}
function Get-RelyingParty ($metadata) {
foreach($RoleDescriptor in $metadata.RoleDescriptors){
if($RoleDescriptor.GetType().FullName -eq 'Microsoft.IdentityModel.Protocols.WSFederation.Metadata.SecurityTokenServiceDescriptor'){
# metadata have a STS
$stsd = $RoleDescriptor
} elseif($RoleDescriptor.GetType().FullName -eq 'Microsoft.IdentityModel.Protocols.WSFederation.Metadata.ApplicationServiceDescriptor'){
# metadata have a Relying Party
$asd = $RoleDescriptor
}
}
$asd
}

function Get-GetCertificate ($stsd, $certificatetype) {
if( ($certificatetype -ne 'Signing') -and ($certificatetype -ne 'Encryption')){
Write-Error "CertificateType should be 'Signing' or 'Encryption'"
return
}
$has40 = [Reflection.Assembly]::LoadWithPartialName("System.IdentityModel")

$SigningCertificate = $null
foreach($key in $stsd.Keys){
if($key.Use -eq $certificatetype){
if($has40.GetName().Version.Major -eq 4){
#if .net 4.0 is install we can just do this, when System.IdentityModel v4.0.30319 is loaded
$bytes = $key.Keyinfo.GetX509RawData()
} else {
#but default, sharepoint 2010 only have version v2 loaded so, lets do it, the ugly way
$str = $key.Keyinfo.ToString()
$str = $str.Substring( $str.IndexOf('RawData = ') + 10)
$str = $str.Substring(0, $str.IndexOf(')'))

$bytes = ([system.Text.Encoding]::UTF8).GetBytes($str)
}
$SigningCertificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]([byte[]]$bytes)
}
}
$SigningCertificate
}

Function Ensure-SPProvider($name, $defaultrealm, $SigningCertificate, $SigninURL, $claims, $IdentifierClaim, $mapClaims){
$certificatename = "$($name) Signing Certificate"
$cert = get-SPTrustedRootAuthority | ?{($_.Certificate.Thumbprint -eq $SigningCertificate.Thumbprint) -or ($_.Name -eq $certificatename)}
if(!$cert){
Write-Host "Adding $($SigningCertificate.Thumbprint) as a Trust Certificate"
$cert = New-SPTrustedRootAuthority -name $certificatename -Certificate $SigningCertificate
} else {
$cert | Set-SPTrustedRootAuthority -Certificate $SigningCertificate
}
$chain = New-Object System.Security.Cryptography.X509Certificates.X509Chain
$chain.Build($SigningCertificate)
$SigningCertificateRoot = $chain.ChainElements[$chain.ChainElements.Count -1].Certificate

# Ensure Root Cert has been added to Trusted Store
$store = get-item cert:\LocalMachine\Root
$store.Open("ReadWrite")
$store.Add($SigningCertificateRoot )
$store.Close()

# And now, add it to SharePoint too
$rootcert = get-SPTrustedRootAuthority | ?{($_.Certificate.Thumbprint -eq $SigningCertificateRoot.Thumbprint)}
if(!$rootcert){
Write-Host "Adding $($SigningCertificateRoot.Thumbprint) as a Trust Certificate"
$rootcert = New-SPTrustedRootAuthority -name $SigningCertificateRoot.Subject -Certificate $SigningCertificateRoot
}

$IDClaim = $null
$claimsmappings = @()
foreach($claim in $claims) {
# http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name is reserved inside SharePoint (??? Why ?... really, WTF !!!!)
# http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid is only used in SharePoint 2013 ( not tested yet )
# its SharePoints internal STS job to handle the requiered fields
# http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod
# http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant

if($claim.ClaimType -eq 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name'){
$claimsmappings += New-SPClaimTypeMapping $claim.ClaimType -IncomingClaimTypeDisplayName $claim.DisplayTag -LocalClaimType 'http://simplests.wingu.dk/identity/claims/name'
} elseif($claim.ClaimType -eq 'http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod'){
# Skip
} elseif($claim.ClaimType -eq 'http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant'){
# Skip
} elseif($claim.ClaimType -eq 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier'){
$claimsmappings += New-SPClaimTypeMapping $claim.ClaimType -IncomingClaimTypeDisplayName $claim.DisplayTag -LocalClaimType 'http://simplests.wingu.dk/identity/claims/nameidentifier'
} else {
$claimsmappings += New-SPClaimTypeMapping -IncomingClaimType $claim.ClaimType -IncomingClaimTypeDisplayName $claim.DisplayTag -SameAsIncoming
}
if($IdentifierClaim -eq $claim.ClaimType){
$IDClaim = $claim.ClaimType
}
}

$ap = Get-SPTrustedIdentityTokenIssuer | ?{$_.name -eq $name}
if(!$ap){
$ap = New-SPTrustedIdentityTokenIssuer -Name $name -Description $name -Realm $defaultrealm -ImportTrustCertificate $SigningCertificate -ClaimsMappings $claimsmappings -SignInUrl $SigninURL -IdentifierClaim $IDClaim
}
# Ensure all claim mappins are there
#foreach($claim in $claims) {
# $hasClaim = $ap.ClaimTypes | ?{$_ -eq $claim.ClaimType}
# if(!$hasClaim) {
# Write-Host "adding ClaimType $($claim.DisplayTag) to $name"
# $ap.ClaimTypes.Add($claim.ClaimType)
# }
#}

#$ap.Update()
#Add-SPClaimTypeMapping -Identity $claim -TrustedIdentityTokenIssuer $ap
#$ap = Get-SPTrustedIdentityTokenIssuer | ?{$_.name -eq $name}

# if you only have 1 sharepoint site, and dont want to "bother" setting up
# Reply URL on your STS ( adfs - AD FS 2.0 Management -> Trust Releationships ->
# Relying Party Trusts -> Properties on RP Go to "Endpoints" tab -> WS-Federation Passive Endpoint
# Or SimpleSTS -> Management -> Relying Party -> Manage -> PassiveRequestorURI
# you can just override the $ap.DefaultProviderRealm
# but the correct way would be to list each unique URI with an associated URN in $ap.ProviderRealms
$ap.DefaultProviderRealm = $defaultrealm

$ap.ProviderUri = $SigninURL
#$ap.Name = $name
#$ap.DisplayName = $name


# If WReply is not set, sharepoint will not add return URL when sending user to login page
# if DefaultProviderRealm/$ap.ProviderRealms URN is not listed with a Return URL in the STS
# the STS will not know where to send the user. What's "correct" ? dont know.
# if your paranoid, leacing WReply $false, using URN's all the places, and keeping Passive Federation
# URL's in you STS would proberly be best, but let's ensure we can have both unique URI's, prober return URI's
# and unique'nes by using $ap.ProviderRealms
$ap.UseWReplyParameter = $true

# HomeRealm tells the STS how the user want to to login instead of prompting.
# ADFS will ask and save a cookie, for 3 months, most custom solutions, will prompt each time
# for instance SimpleSTS will allow you to choose each time from a list of all allowed providers
# Sharepoint will NEVER know what those homerealms could be.
# SharePoint's internet STS will normaly "strip" off HomeRealm ( WHR= ) but with the Juni RU this new
# parameter was added to allow adding HomeRealm in custom code (modules or custom login page) without loosing the WHR parameter
# http://blogs.msdn.com/b/chriskeyser/archive/2011/10/02/sharepoint-2010-claims-and-home-realm-discover-passing-whr-on-the-url-to-sharepoint.aspx
try {
$ap.UseWHomeRealmParameter = $true
} catch {
Write-Warning "SharePoint is not update, and wont allow setting UseWHomeRealmParameter, make sure you use uri:sp: as realms/AudienceURIs, or set PassiveRequestorURI to [SharePointURI]/_trust/"
$Error.Clear()
}
$ap.Update()

}
$metadata = Get-medadata $metadataurl
$stsrealm = $metadata.EntityId.Id
$stsd = Get-STS $metadata
#$asd = Get-RelyingParty $metadata
$SigningCertificate = Get-GetCertificate $stsd 'Signing'
#$encryptionCertificate = Get-GetCertificate $asd 'Encryption'
$claims = $stsd.ClaimTypesOffered

foreach($PassiveRequestorEndpoint in $stsd.PassiveRequestorEndpoints){
$SigninURL = $PassiveRequestorEndpoint.Uri.AbsoluteUri
}

Ensure-SPProvider $stsname $defaultrealm $SigningCertificate $SigninURL $claims $IdentifierClaim $mapClaims

if($autoGenerateProviderRealms -eq $true){
# We could use Get-SPWebApplication, and then Get-SPAlternateURL on each site
# we could also filter out only "external" sites, etc ....

$ap = Get-SPTrustedIdentityTokenIssuer | ?{$_.name -eq $stsname}
#$ap.ProviderRealms.Clear()
foreach($wa in Get-SPWebApplication){
$pr = $ap.ProviderRealms.keys | where {$_.AbsoluteUri -eq $wa.Url}
if(!$pr){ $pr = $ap.ProviderRealms.Add([uri]($wa.Url), "urn:sps:$($wa.Url)") }
}
$ap.Update()
}
if($autoAddSTS -eq $true){
$windowsap = New-SPAuthenticationProvider
#$aps = Get-SPAuthenticationProvider -Zone "Default" -WebApplication $wa
$aps = @()
$aps += $windowsap
foreach($ap in Get-SPTrustedIdentityTokenIssuer){
$aps += $ap
}
foreach($wa in Get-SPWebApplication){
Set-SPWebApplication -Identity $wa -Zone "Default" -AuthenticationProvider $aps # -Force
}
}

$ap = Get-SPTrustedIdentityTokenIssuer | ?{$_.name -eq $stsname}
Write-Host "ensure '$($defaultrealm) and each 'Value' is added to the Relying Party in the STS"
$ap.ProviderRealms

tirsdag den 13. november 2012

Azure PowerShell – Now with Provider Support

I got a little feedback on my PowerShell module WA, and have updated it to reflect some of those things. First of all, subscription handling was weird, so created the prober commands for that ( New-Subscription, Set-Subscription, Remove-Subscription, Get-Subscription, Select-Subscription ) . I also made some optimizing on Table/Row CmdLets, so should handle tables with many rows better. But the most important thing is I implemented a PowerShell Provider ( still working a a few tweaks here and there, but ill keep updating the binaries when needed )

First of all. I started creating the Provider in hopes of making copying files between your local file system and Azure more smooth and intuitive. After I had almost finished most of the work and was ready to start working on that part, I found out that Microsoft does not support cross provider copying. That sucks, but I had already started the work and it still works “cross” container/Storage account wise, and with my new parameters it also works with local file system (with a twist).

When you load the PowerShell module, you will now have access to a azure: drive. The root will contain a list of your subscriptions (and you can create/update/remove with new-item/set-item/remove-item) each representing a folder. If you go down on one of those you will get a list of Storage Accounts associated with that subscription. Again you can Create/Remove storage accounts to that subscription with New-Item/Remove-Item. You can also copy all content from one Storage Account to another with Copy-Item (Move-Item to work soon. Snapshots are not part of the copy, but can be handled individually )

image

All levels work with <tab> tabulator auto completion, to make it fast and smooth navigating around. If you jump down to a storage account and do a dir or Get-ChildItem you will get a list of BlobContainers and Table’s (queues will be added later). You can create new containers and tables with New-Item (default is containers)

image

But enough of that. Remember my long script to copy a storage account in part one ? This is how you can do that now

Copy-Item azure:\Pay-As-You-Go\wingu2 azure:\skadefro\copytest

Works with containers and single blobs too. So what about local files ?
New-Item is for uploading files. Get-Item / Get-ChildItem (or just dir) is for downloading file. Eksamples

# Upload a single file
New-Item -filename C:\temp\1.jpeg azure:\skadefro\copytest\ad01\1.jpeg
# Since we know the file name, you can also just specefy container
New-Item -filename C:\temp\1.jpeg azure:\skadefro\copytest\ad01
# Hell, if you allready are in the folder just use .
cd azure:\skadefro\copytest\ad01
New-Item -filename C:\temp\1.jpeg .

# want to upload a whole folder ?
New-Item -filename C:\temp azure:\skadefro\copytest\ad01
# or
cd azure:\skadefro\copytest\ad01
New-Item -filename C:\temp .
# What about all subfolders in that folder ?
# sure, this will also create the "folder" in azure
cd azure:\skadefro\copytest\ad01
New-Item -Recursive -filename C:\temp .

# want to upload a single file to a folder ?
# Since powershell keep messing with the folder paths, we need to use
# forwariding slash for folders.
New-Item -filename C:\temp\1.jpeg azure:\skadefro\copytest\ad01\test/1.jpeg
# or

# same goes the other way
# download a file
Get-Item -filename c:\temp\1.jpeg azure:\skadefro\copytest\ad01\1.jpeg
# or, since we allready know the file name,
Get-Item -filename c:\temp\ azure:\skadefro\copytest\ad01\1.jpeg

# Download all the files from the container
# this will create the folder structure localy also, if names contains /
Get-Item -filename c:\temp azure:\skadefro\copytest\ad01
# or the short version
cd azure:\skadefro\copytest\ad01
Get-Item -filename c:\temp .

# I know, Get-ChildItem is suppose to do that, but that works too
Get-ChildItem -filename c:\temp azure:\skadefro\copytest\ad01
# or
cd azure:\skadefro\copytest\ad01
Get-ChildItem -filename c:\temp .

# or the cool and lazy way,
dir azure:\skadefro\copytest\ad01 -filename c:\temp

So download a copy, test it out and feel free to give me some feedback

lørdag den 10. november 2012

PowerShell Provider fails with Remove-Item

This one was driving me nuts. Looked at tons of examples, tried every kind of combination of code, and tried goggling all kinds of variations and just couldn’t get this to work.

I’m working on implementing a PowerShell Provider and got to the part where I want to implement more than just Get-Item, Get-ChildItem … Clear-Item, Copy-Item, Move-Item, Rename-Item, Set-Item all works without any fuzz … but Remove-Item would constantly throw an PSNotSupportedException and in PowerShell

Remove-Item : Provider execution stopped because the provider does not support this operation.

You see this error if you don’t Override the function, but I was doing that, and that was kept me going around in circles. It never hit me, it could be another function I had to override to make it work *DOH* … If I also override RemoveItemDynamicParameters that would get hit, and PowerShell would respect my Parameter() decorations just fine, so this made no sense to me…. So, like in my former blog post I finally had enough, I override all functions and starting removing them one by one .. and that’s when I hit my jackpot. All I had to do was override HasChildItems.

Protected Overrides Function HasChildItems(path As String) As Boolean
' make code to check if item is an container or not
Return True
End Function

fredag den 9. november 2012

PowerShell provider relative path tab-completion issue

I’m playing around with implementing a PowerShell Provider. After a while I started having big issues when using <tab> auto completion. Google wasn’t at much help, but I did find someone else who had the same problem. it just didn’t sound correct that it’s a “bug”, considering I have seen other providers that works correctly. Like notfed on Stack Overflow I tried returning different information, without any luck, so I finally decided to override all functions in NavigationCmdletProvider and do a Trace.WriteLine to see what was going on. And in MakePath I got lucky. To be honest since I haven't been able to find any source code examples that actually work, I don’t know if this is the correct solution, but it works for me, so I’m happy

''' <summary>
''' Joins two strings with a provider specific path separator.
''' </summary>
''' <param name="parent">The parent segment of a path to be joined with the child.</param>
''' <param name="child">The child segment of a path to be joined with the parent.</param>
''' <returns>A string that contains the parent and child segments of the path joined by a path separator.</returns>
''' <remarks></remarks>
Protected Overrides Function MakePath(parent As String, child As String) As String
Trace.WriteLine("::MakePath(parent:=" & parent & ",child:=" & child & ")")
Dim res As String = MyBase.MakePath(parent, child)
Trace.WriteLine("::MakePath(parent:=" & parent & ",child:=" & child & ") " & res)
If parent = "." Then
'res = ".\" & child.Split("\").Last
If String.IsNullOrEmpty(Me.SessionState.Path.CurrentLocation.ProviderPath) Then
res = parent & PATH_SEPARATOR & child
Else
res = parent & PATH_SEPARATOR & child.Substring(Me.SessionState.Path.CurrentLocation.ProviderPath.Length + 1)
'res = parent & PATH_SEPARATOR & child.Replace(Me.SessionState.Path.CurrentLocation.ProviderPath & PATH_SEPARATOR, String.Empty)
End If
Trace.WriteLine("::**** TRANSFORM: " & res)
End If
Return res
End Function

torsdag den 8. november 2012

Azure PowerShell–The missing links

I attended Campus Days again this year, and doing one of the sessions one of the presenters told everyone you need to buy 3rd party products to take snapshots or copy Storage Blobs from one container/account to another. That doesn’t seem fair. I needed this functionality and have created a PowerShell module that can do all that, and a lot more, so I decided to share that, with the world.

I think its important to understand the reason I wrote this before I get flamed with comments and emails. When I began playing around with azure, doing a proof of concept setup together with a guy from Microsoft Denmark, I started creating a PowerShell module to manage it, but quickly came across a module that someone else had written than already did most of what I needed, so abandoned the project again. Several months later, when I was asked to start doing some more work with Azure, especially Persistent VM’s I found that Microsoft had adopted the PowerShell module that I had once used, and in that process removed several key features that I needed (but was once there) I also noticed the module was painfully slow to work with when handling Persistent VM’s, so I started writing my own. Half way though that process I got bored with it, and started mixing Microsoft's PowerShell with my own, just focusing on the things they miss. So you will find a lot of useful stuff, and some redundant stuff. In a real scenario you would probably end up using both (for instance, I've only written half of the code to create new VM’s, and that sure is is an important command, right ? ;-) )

Download the module and extract it somewhere, like c:\wa  Open PowerShell and load the module with

# If you just downloaded it, unblock files
Unblock-File C:\wa\Release\*
import-module C:\WA\Release\wa.psd1

First of all, I hate the way Microsoft handles working with different Subscriptions. (granted some of mine ended up working the same way in the end, but still ). So you load the module and connect to one of your subscriptions with

# Find your Management Certificate, or create one and upload it to azure
dir cert:\CurrentUser\my

# Tell WA module about the subscription and cert and give it a name
Select-Subscription -Name Pay-As-You-Go -SubscriptionId 1f6b36b5-d2ab-49e6-8674-2155a3ea4a55 -CertificateThumbprint AAF4E3017B3DE26E93601E1573FDAF44A3AA15E8

The module loads certificates from localmachine and localuser store, but most will have it in the user\my store. Name can be what ever makes sense to you, I normally use the name Azure also used within the management portal. This gets saved in HKLU\software\wa Registry and from now on, every time you start a new PowerShell prompt you can just use

Select-Subscription -Name Pay-As-You-Go 
# or list all, known subscription with
Get-Subscription
# This will also query azure about statistics data, so you can see if your about to hit your Core, HostedService or Storage Account limits.

If you only want to manage an storage account, you can ignore the above and connect directly to it, using

Select-StorageAccount -AccountName skadefro -AccountKey blahBlagBlah1234==

But if you loaded an subscription, you can let the module handle all that for you and just use the Storage account’s Service Name.

Select-StorageAccount -ServiceName Skadefro

Ok, So what can you do, that Microsoft’s version is missing. Well, managing Storage/Blob/Queue’s was the first show stopper for me, so now you can Create/modify/delete tables, select, insert, modify,delete rows from tables. You can add/update/remove blob containers, update ACL on containers and blobs. Add/Upload/download/snapshot/signature/lease/unlock/remove/copy blobs, both as Page and Block blobs. ( uploading is insanely fast with Page blob, and if you really want to tweak your VM’s, making sure page size fits the size you format your disks with makes a huge difference. )


The reason I’m sharing all this, is several people asked about snapshot’s and copying content from one storage account to another ( hell, even my favorite azure application Azure Explore, doesn’t support copying blobs from one container to another ) ill give a few examples of that.


First, snapshots. very simple

$storageacountname = 'wingu2'
$containername = 'public'
$filename = 'test.txt'
# select an StorageAccount if you got more than one.
# if you only have 1, that will always be selected
Select-StorageAccount -ServiceName wingu2
# Lets upload a text file
# we should place that in a container
$container = Get-Container $containername
if(!$container) { $container = New-Container $containername }
# Lets make it public, so we can show cross subscription/account
# copying later
if( (Get-ContainerACL $containername) -ne 'container'){ Set-ContainerACL $containername container }

# Create a test file, and upload it
if ( (Test-Path $filename) -eq $true) { Remove-Item $filename -confirm:$false }
$file = New-Item -ItemType file $filename
add-content $file '1. Hello world'
New-Blob $containername $filename
$blob = Get-Blob $containername $filename

#Now, lets take a snapshot
$snapshot = $blob | New-Snapshot

#Lets update the file
add-content $file '2. Hello world'
New-Blob $containername $filename

# This will return 1 result
Get-Blob $containername $filename

# This will return 2 result
Get-Blob $containername $filename -Snapshots

# Remove the snapshot, supply snapshot time or pipe the Object
#$snapshot | Remove-Blob

# Removing the file will also fail, since we have a snapshot
Get-Blob $containername $filename | Remove-Blob

# But we can force, deleting all snapshot with
Get-Blob $containername $filename | Remove-Blob -deletesnapshots

Next up, is copy blobs across containers or even storage accounts. If you want to move everything from one account to another, here's a crud but efficient way

Select-Subscription Pay-As-You-Go
Select-StorageAccount -ServiceName wingu2
$containers = @{}
foreach($container in Get-Container){
$containers += @{$container.Name=Get-Blob $container.Name}
# Could even update it to public and close it again after with
# Set-ContainerACL $container.Name container
}

Select-Subscription skadefro
Select-StorageAccount -ServiceName copytest
foreach($container in $containers.GetEnumerator()){
$c = get-container $container.Name
if(!$c){ $c = New-Container $container.Name }

foreach($blob in $container.Value){
Write-Host ("Copying '" + $blob.Name + "' to container '" + $c.Name + "'")
Copy-Blob -Uri $blob.Uri -Destinationuri ($c.Uri.ToString() + '/' + $blob.Name)
}
}


When I showed this to a friend, he quickly asked, what if I don’t want to make it public ? Well, we can use shared signature’s for that, so here’s another way, without requiring the containers to be public.

Select-Subscription Pay-As-You-Go
Select-StorageAccount -ServiceName wingu2
$containers = @{}
foreach($container in Get-Container){
$blobs = @{}
foreach($blob in (Get-Blob $container.Name)){
# By default, this cmdlet creates a 55 minute readonly adhoc signature
$url = $blob | Get-BlobSignature
$blobs += @{$blob.Name=$url}
}
$containers += @{$container.Name=$blobs}
}

Select-Subscription skadefro
Select-StorageAccount -ServiceName copytest
foreach($container in $containers.GetEnumerator()){
$c = get-container $container.Name
if(!$c){ $c = New-Container $container.Name }

foreach($blob in $container.Value.GetEnumerator()){
Write-Host ("Copying '" + $blob.Name + "' to container '" + $c.Name + "'")
Copy-Blob -Uri $blob.Value -Destinationuri ($c.Uri.ToString() + '/' + $blob.Name)
}
}

Another feature that is missing from Microsoft's azure module is the ability to work with tables and queues. So now you can use your favorite PowerShell prompt and work with them there (if that rocks your boat)

Select-StorageAccount -ServiceName wingu2
$tablename = 'testtable'
$table = Get-Table $tablename
if(!$table){
New-Table $tablename
} else {
Remove-Table $tablename
New-Table $tablename
}

# add using hashtable
New-Row $tablename -Columns @{ ID=1; Name='John Doe' }

# add using PSObject
$row = New-Object PSObject -Property @{ ID=2; Name='Jane Doe'; upn='jd@identity.local' }
New-Row $tablename $row

# add overriding RowKey
New-Row $tablename -Columns @{ ID=3; Name='Little Doe'; City='Aarhus' }

Get-Row $tablename

# We can search by Row Key and/or Partition key. Or just use PowerShell
$row = Get-Row $tablename | ?{$_.ID -eq 3}
# Add Age to the object
$row | Add-Member -Name 'Age' -Value 33 -MemberType Noteproperty
# Update row
$row | Set-Row $tablename

# Create new, based on another
$row.ID = 4
$row.Name = 'Bill Doe'
$row.upn = 'bill@identity.local'
$row | New-Row $tablename

Get-Row $tablename

Lastly, I short list of all the commands. Source code will be uploaded once I cleaned it up a bit, and added some help texts and such. Drop me an email if your interested before I'm done (its not highest on my priority list at the moment). Should probably also add some logic to handle async blob copy’s etc. you know.

Copy-WAStorageBlob
Get-WADeployment
Get-WADisk
Get-WAHostedService
Get-WALocation
Get-WAOperationStatus
Get-WAOS
Get-WAOSFamily
Get-WAOSImage
Get-WAServiceCertificate
Get-WAStorageAccount
Get-WAStorageAccountKeys
Get-WAStorageBlob
Get-WAStorageBlobLease
Get-WAStorageBlobSignature
Get-WAStorageContainer
Get-WAStorageContainerACL
Get-WAStorageContainerSignature
Get-WAStorageRow
Get-WAStorageTable
Get-WASubscription
Get-WASubscriptionCertificate
Get-WAVM
Get-WAAffinityGroup
New-WADeployment
New-WADisk
New-WAHostedService
New-WAOSImage
New-WAServiceCertificate
New-WAStorageAccount
New-WAStorageAccountKeys
New-WAStorageBlob
New-WAStorageBlobLease
New-WAStorageBlobSnapshot
New-WAStorageContainer
New-WAStorageRow
New-WAStorageTable
New-WASubscriptionCertificate
New-WAAffinityGroup
Remove-WADeployment
Remove-WADisk
Remove-WAHostedService
Remove-WAOSImage
Remove-WAServiceCertificate
Remove-WAStorageAccount
Remove-WAStorageBlob
Remove-WAStorageBlobLease
Remove-WAStorageContainer
Remove-WAStorageRow
Remove-WAStorageTable
Remove-WASubscriptionCertificate
Remove-WAAffinityGroup
Select-WAStorageAccount
Select-WASubscription
Set-WADeployment
Set-WADeploymentStatus
Set-WADisk
Set-WAHostedService
Set-WAOSImage
Set-WAStorageAccount
Set-WAStorageBlob
Set-WAStorageContainerACL
Set-WAStorageRow

# aliases registed though module manifest file in wa.ps1
New-Alias -name Select-Subscription -value Select-WASubscription
New-Alias -name Get-Subscription -value Get-WASubscription
New-Alias -name Get-OperationStatus -value Get-WAOperationStatus
#New-Alias -name Get-Location -value Get-WALocation

New-Alias -name Get-Deployment -value Get-WADeployment
New-Alias -name New-Deployment -value New-WADeployment
New-Alias -name Set-Deployment -value Set-WADeployment
New-Alias -name Set-DeploymentStatus -value Set-WADeploymentStatus
New-Alias -name Remove-Deployment -value Remove-WADeployment

New-Alias -name Get-AffinityGroup -value Get-WAAffinityGroup
New-Alias -name New-AffinityGroup -value New-WAAffinityGroup
New-Alias -name Set-AffinityGroup -value Set-WAAffinityGroup
New-Alias -name Remove-AffinityGroup -value Remove-WAAffinityGroup

New-Alias -name Get-Disk -value Get-WADisk
New-Alias -name New-Disk -value New-WADisk
New-Alias -name Remove-Disk -value Remove-WADisk
New-Alias -name Set-Disk -value Set-WADisk

New-Alias -name Get-OSImage -value Get-WAOSImage
New-Alias -name New-OSImage -value New-WAOSImage
New-Alias -name Set-OSImage -value Set-WAOSImage
New-Alias -name Remove-OSImage -value Remove-WAOSImage

New-Alias -name Get-VM -value Get-WAVM


New-Alias -name Get-ServiceCertificate -value Get-WAServiceCertificate
New-Alias -name New-ServiceCertificate -value New-WAServiceCertificate
New-Alias -name Set-ServiceCertificate -value Set-WAServiceCertificate
New-Alias -name Remove-ServiceCertificate -value Remove-WAServiceCertificate

New-Alias -name Get-Certificate -value Get-WASubscriptionCertificate
New-Alias -name New-Certificate -value New-WASubscriptionCertificate
New-Alias -name Remove-Certificate -value Remove-WASubscriptionCertificate

New-Alias -name Get-HostedService -value Get-WAHostedService
New-Alias -name New-HostedService -value New-WAHostedService
New-Alias -name Remove-HostedService -value Remove-WAHostedService
New-Alias -name Set-HostedService -value Set-WAHostedService

New-Alias -name Get-StorageAccount -value Get-WAStorageAccount
New-Alias -name Get-StorageAccountKeys -value Get-WAStorageAccountKeys
New-Alias -name New-StorageAccount -value New-WAStorageAccount
New-Alias -name New-StorageAccountKeys -value New-WAStorageAccountKeys
New-Alias -name Remove-StorageAccount -value Remove-WAStorageAccount
New-Alias -name Select-StorageAccount -value Select-WAStorageAccount
New-Alias -name Set-StorageAccount -value Set-WAStorageAccount

New-Alias -name Get-Blob -value Get-WAStorageBlob
New-Alias -name Get-BlobLease -value Get-WAStorageBlobLease
New-Alias -name Get-BlobSignature -value Get-WAStorageBlobSignature
New-Alias -name New-Blob -value New-WAStorageBlob
New-Alias -name New-BlobLease -value New-WAStorageBlobLease
New-Alias -name New-Snapshot -value New-WAStorageBlobSnapshot
New-Alias -name Copy-Blob -value Copy-WAStorageBlob
New-Alias -name Remove-Blob -value Remove-WAStorageBlob
New-Alias -name Remove-BlobLease -value Remove-WAStorageBlobLease
New-Alias -name Set-Blob -value Set-WAStorageBlob

New-Alias -name Get-Container -value Get-WAStorageContainer
New-Alias -name Get-ContainerACL -value Get-WAStorageContainerACL
New-Alias -name Get-ContainerSignature -value Get-WAStorageContainerSignature
New-Alias -name New-Container -value New-WAStorageContainer
New-Alias -name Remove-Container -value Remove-WAStorageContainer
New-Alias -name Set-Container -value Set-WAStorageContainer
New-Alias -name Set-ContainerACL -value Set-WAStorageContainerACL

New-Alias -name Get-Row -value Get-WAStorageRow
New-Alias -name New-Row -value New-WAStorageRow
New-Alias –name Set-Row –value Set-WAStorageRow


New-Alias
-name Remove-Row -value Remove-WAStorageRow

New-Alias -name Get-Table -value Get-WAStorageTable
New-Alias -name New-Table -value New-WAStorageTable
New-Alias -name Remove-Table -value Remove-WAStorageTable