Provisioning sanitized data with SQL Clone and Data Masker. Watch now.

Automated Script: Check if a Clone exists before deleting it

I'm trialing a Proof of Concept for SQLClone and am in the last stages of automation. Via Octopus Deploy, I'm now provisioning databases however am having issues in cases where the DB in question has never been mounted to the server I'm deploying to, or has been deleted. The following line fails:

Get-SqlClone -Name $TargetDatabaseName -Location $SqlServerInstance | Remove-SqlClone | Wait-SqlCloneOperation

Because the clone doesn't exists, it can't delete it. I though the logical thing to do would be to wrap this in a statement to check that it has a clone before deleting, but the actual Get-SqlClone is throwing the error because it doesn't exist:

$CloneToDelete = Get-SqlClone -Name $TargetDatabaseName -Location $SqlServerInstance
if ($CloneToDelete)
{
$CloneToDelete | Remove-SqlClone | Wait-SqlCloneOperation
}

Is there a nice way of checking if a clone exists without throwing an error which breaks our deployment step? I'd rather not have to add try...catch blocks into the PowerShell as this isn't really an error and just means we should be able to move onto the clone part of the script if there is no clone to delete first:

$Image | New-SqlClone -Name $TargetDatabaseName -Location $SqlServerInstance | Wait-SqlCloneOperation

Thanks
Tagged:

Best Answer

  • ErdoganOzkocaErdoganOzkoca Posts: 19 Bronze 3
    edited January 31, 2018 4:23PM Answer ✓
    Hi,

    While using Get-SqlClone with Name and Location parameters, you make an exact search for clone. So, if there is no clone with given credentials, you will receive an error. To avoid this, there are two ways:
    1. Using try catch
    2. Getting all clones of a specific location and try to get your clone name from this list by using powershell
    (Get-SqlClone -Location $SqlServerInstance)

    There are 2 more usage of Get-SqlClone command. (But these usages can cause to delete more clones on your environment)
    1. You can use wildcard (*) with your clone name. For example:
    Get-SqlClone -Name 'clone_name*' -Location $SqlServerInstance
    With this command, you will receive all clones which starts with "clone_name" for the location you specified. If there is no clone starts with "clone_name", there will be no error message and you will receive null object.
    2. You can use Get-SqlClone command without using "Location" parameter. This usage, will return all clones with specified clone name regardless of location. If there is no clone with specified name, there will be no error message and you will receive null object.

    Best Regards

Answers

Sign In or Register to comment.