Friday, August 3, 2018

#Azure and #LogAnalytics: Move workspaces in bulk

I had a request from a customer recently to help them move all their Log Analytics workspaces into a new subscription, so wrote a quick script for this purpose.

This script in its current form will:

  • Connect to the specified subscription ($OldSub)
  • Get all the workspaces in that subscription
  • Move the workspaces to the specified subscription ($NewSub)
  • Prompt for confirmation for each workspace and run to completion for the workspace before starting with the next in the list
  • Write a log file of each workspace processed

Disclaimer: This script has been tested in a lab environment only. It is highly recommended that you test the script in a lab environment and adapt for your environment before using in production.

ETA: I had a reminder that I forgot to mention this. Some solutions cannot be moved with the workspace, and will need to be removed before the workspace can be moved.


Update the bits in yellow as appropriate for your environment.

############################################################################
#
#   Move-LogAnalytics-Worksspaces.ps1
#
#   Script by: Vanessa Bruwer
#
#
#   This script will move all the workspaces in a specific subscription
#   and assumes all workspaces are managed by resource manager
#
#
############################################################################

# Variables

$OldSub = "Name of the subscription currently hosting workspaces"
$NewSub = "Name of the subscription the workspaces need to be moved to"

$NewRG = "Name of the resource group in the new sub to manage the workspaces"


# We are going to create a log file for this process.
# These variables determine the log file name and location

$ReportDate = Get-Date -format "yyyy-M-dd"

$rnd = Get-Random -minimum 1 -maximum 1000
$ReportLocation = "C:\Temp"
$ReportName = "$ReportDate-$rnd-Azure-LogAnalyticsWorkspaceMoveLog.csv"
$SavetoFile = "$ReportLocation\$ReportName"


# Create the folder if it doesn't exist

If (!(Test-Path $ReportLocation)){
     New-Item -ItemType directory -Path $ReportLocation
}


# Open the content
$body = @()

$body += "WorkspaceName,WorkspaceID,OldSub,NewSub"

# Now the script work really starts


# Connect to the old subscription

Set-AzureRmContext -Subscription $OldSub


# Get the ID for the New Subscription

$NewSubID = (Get-AzureRmSubscription -SubscriptionName $NewSub).Id


# list all the workspaces in a subscription
$Workspaces = Get-AzureRmResource -ResourceType Microsoft.OperationalInsights/workspaces


foreach ($Workspace in $Workspaces)
{

$WSID = $Workspace.ResourceId
$WSName = $Workspace.Name


Move-AzureRmResource -DestinationSubscriptionID $NewSubID -DestinationResourceGroupName $NewRG -ResourceId $WSID

#write-host "$WSName has been moved to $NewSub"

$body += "$WSName,$WSID,$OldSub,$NewSub"


}

$body >> $SavetoFile

No comments:

Related Posts with Thumbnails