Most PowerShell examples for Tintri circulating online were written against the old Windows-only toolkit, and several of the parameter names in them no longer match. This post is written against the shipped help of the PowerShell Core Toolkit 5.1.0.1, so every cmdlet and parameter below is one the module actually exports.

Corrections to earlier posts on this site. I have used Connect-TintriServer -Server in several scripts here. The parameter is -HostName. I have also used Import-Module TintriPSToolkit; the module name is TintriPSCoreToolkit. And I referred to Get-TintriAlert, which is actually Get-TintriAlerts, plural. Those posts are being corrected. Confirm on your own install with Get-Command -Module TintriPSCoreToolkit.

01. What you are actually installing

ModuleTintriPSCoreToolkit, root assembly TintriPSToolkit.dll
Version5.1.0.1
PS editionsDesktop and Core, minimum PowerShell 5.0
Runtime.NET Framework 4.6 minimum, AMD64 only
Cmdlets158
Ships withNewtonsoft.Json, NodaTime, Quartz, Refit, SSH.NET, Tintri SDK and type libraries

The Core edition support is the part worth noticing. This runs on PowerShell 7, which means a Linux container in a pipeline, not just an admin’s Windows jump box. The ProcessorArchitecture = 'AMD64' line in the manifest is the constraint to check first if import fails on an ARM host.

02. The cmdlet surface, by domain

158 cmdlets across 23 verbs. Knowing the shape saves you guessing at names.

DomainRepresentative cmdlets
SessionConnect-TintriServer, Disconnect-TintriServer, Get-TintriServerSession, Set-TintriDefaultServer, Get-TintriApiVersion, Get-TintriCommand
VMs and vDisksGet-TintriVM, Get-TintriVMStat, Get-TintriVMVDiskStat, Get-TintriVDisk, Set-TintriVMQos, Set-TintriVMProperty, Restore-TintriVM, Sync-TintriVM
SnapshotsGet-TintriVMSnapshot, New-TintriVMSnapshot, Remove-TintriVMSnapshot
Snapshot schedulesGet/New/Set/Update/Clear-TintriVMSnapshotSchedule, Set-TintriVMSnapshotScheduleToDefault, Get-TintriDatastoreVMSnapshotSchedule
CloningNew-TintriVMClone, New-TintriVMCloneMany, New-TintriVMNameSequence, Get-TintriVMCustomizationSpec
ReplicationGet/New/Remove-TintriVMReplConfiguration, Suspend/Resume-TintriVMReplication, Get-TintriVMByReplStatus, Get-TintriSyncReplStat, New-TintriVMRemoteCopy, datastore replication paths
Service groupsGet/New/Set/Remove-TintriServiceGroup, members, rules, quota policies
Pools (scale-out)Get/New/Set/Remove-TintriPool, Add/Remove-TintriPoolMember, Get/Update/Reset-TintriPoolRecommendation, Approve-TintriPoolRecommendation
AlertsGet-TintriAlerts, Update-TintriAlert, Get/Set/Clear-TintriAlertThreshold, Get/New/Remove-TintriNotifyPolicy
ApplianceGet-TintriAppliance, DNS, SNMP, directory services, licences, IP addresses, Enable/Disable-TintriApplianceMaintenanceMode, Restart/Stop-TintriAppliance, Get-TintriApplianceUpgradeStatus
Database (TDB)Get-TintriDB, Get/Add/Update-TintriDBServer, file shares and access, New/Get/Remove-TintriDBSnapshot, New-TintriDBClone
SMBGet/New/Set/Remove-TintriSmbShare, Grant/Revoke-TintriSmbShareAccess
TasksGet-TintriTaskStatus, Stop-TintriTask, Get-TintriDashboard

Two useful discovery cmdlets that are easy to miss: Get-TintriCommand lists the module’s own cmdlets, and Get-TintriApiVersion tells you which REST API version the connected appliance is serving, which is exactly the version-matrix problem from the previous post solved in one call.

03. Connecting, with the parameters that exist

Import-Module TintriPSCoreToolkit

# three parameter sets, from the shipped help:
Connect-TintriServer -HostName <String[]> [-SetDefaultServer] [-UseCurrentUserCredentials]
                     [-IgnoreCertificateWarnings] [-Force]
Connect-TintriServer -HostName <String[]> [-Credential <PSCredential>] ...
Connect-TintriServer -HostName <String[]> [-UserName <String>] [-Password <String>] ...

# use the credential form. -Password takes a plaintext string, which
# means it lands in history and in the process table.
$cred = Get-Credential
Connect-TintriServer -HostName vmstore01.lab.local -Credential $cred `
                     -SetDefaultServer -IgnoreCertificateWarnings

# HostName is String[] - connect to the whole fleet in one call
$servers = Connect-TintriServer -HostName vmstore01,vmstore02,tgc01 -Credential $cred

Get-TintriServerSession        # what am I connected to
Get-TintriApiVersion           # which REST version is this appliance serving

The fleet primitive most people reimplement by hand: nearly every Get cmdlet accepts -SearchAllTintriServers. Connect to eleven appliances, then run one query across all of them. In an earlier post I wrote a threaded Python fleet poller to solve this; the toolkit had it built in. Worth knowing before you write the loop.

04. Alerts, with the filtering done server side

Get-TintriAlerts [-InboxAlerts] [-NewAlerts] [-ArchivedAlerts] [-AcknowledgedAlerts]
                 [-IncludeNotices] [-IncludeAll] [-Uuid <String>] [-Since <DateTime>]
                 [-TintriServer <ITintriServer>] [-SearchAllTintriServers]

# unacknowledged alerts across the entire connected fleet, last 24h
Get-TintriAlerts -NewAlerts -Since (Get-Date).AddDays(-1) -SearchAllTintriServers

My earlier fleet sweep pulled every alert and filtered acknowledged ones in code. -NewAlerts and -AcknowledgedAlerts do that at the source, and -Since bounds the window. Filter where the data lives.

05. The snapshot cmdlets, precisely

Get-TintriVMSnapshot [-SnapshotDescription <String>]
                     [-SnapshotConsistency <SnapshotConsistency>]
                     [-GetLatestSnapshot] [-SnapshotId <String>]
                     [-Since <DateTime>] [-Until <DateTime>]
                     [-VM <Object> | -Name <String> | -Uuid <String>]
                     [-TintriServer <ITintriServer>] [-SearchAllTintriServers]

New-TintriVMSnapshot -SnapshotDescription <String>
                     [-SnapshotConsistency <SnapshotConsistency>]
                     [-RetentionMinutes <Int32>]
                     [-ReplicaRetentionMinutes <Int32>]
                     [-PassThru] [-Force]
                     [-VM <Object> | -Name <String> | -Uuid <String>]

Remove-TintriVMSnapshot [-Snapshot <Snapshot> | -SnapshotId <String>
                        | -VM <Object> | -Name <String> | -Uuid <String>]
                        [-Force] [-WhatIf] [-Confirm]

Three things in that syntax change how you should write snapshot automation.

  • -RetentionMinutes on creation. This is the sprawl fix. A snapshot taken before a change window with a retention set expires by itself. Every stale manual snapshot you have ever found was created without it.
  • -Since and -Until on retrieval. Bound the query rather than pulling everything and filtering in the pipeline.
  • -WhatIf and -Confirm on removal. The cmdlet implements ShouldProcess properly, so a dry run is free. In an earlier post I said I would not automate snapshot deletion at all; with -WhatIf available, a guarded cleanup is defensible.

The shipped examples are worth reading for the idiom, which is pipeline-first:

# from the toolkit's own help
$vm = Get-TintriVm -name my-vm-1
$start = (Get-Date -year 2020 -month 7 -day 1)
$end   = (Get-Date -year 2020 -month 11 -day 30)
$snaps = Get-TintriVmSnapshot -Vm $vm -Since $start -Until $end

$vms = Get-TintriVM -refresh
New-TintriVMSnapshot -vm $vms[0] -SnapshotDescription snapshot_consistent `
                     -SnapshotConsistency VM_CONSISTENT -RetentionMinutes 100

Get-TintriVMSnapshot -Name "MyVM" | Where-Object { $_.Description -eq "to delete" } |
    Remove-TintriVMSnapshot

Note Get-TintriVM -Refresh. The toolkit caches inventory, so a script that creates a VM and immediately looks for it will not find it without a refresh. That is a common first-hour frustration.

06. What the toolkit deliberately does not do

There is no snapshot lock or unlock cmdlet in 5.1.0.1. The immutability feature is reachable only through the REST API, at POST /v310/snapshot/{uuid}/lock, and only with the Data Protection Admin role.

That gap is worth designing around rather than complaining about. It means a compromised automation host running the toolkit cannot remove immutability from your snapshots, because the capability is not in the module at all. If you need locking in a workflow, call REST directly with a separate DPA credential, and keep that credential out of the toolkit’s session.

07. A guarded snapshot sprawl cleanup

#requires -Version 7.0
<#
  tintri-snapshot-sprawl.ps1
  Fleet-wide snapshot audit with an optional guarded cleanup.

  Uses only cmdlets exported by TintriPSCoreToolkit 5.1.0.1.
  Defaults to reporting. -Cleanup still runs -WhatIf unless -Commit is given.
#>

[CmdletBinding(SupportsShouldProcess)]
param(
    [Parameter(Mandatory)][string[]]$HostName,
    [Parameter(Mandatory)][pscredential]$Credential,
    [int]$StaleDays = 30,
    [string]$DescriptionPattern,        # only remove matching descriptions
    [int]$MaxRemove = 50,
    [switch]$Cleanup,
    [switch]$Commit
)

Import-Module TintriPSCoreToolkit -ErrorAction Stop

$sessions = Connect-TintriServer -HostName $HostName -Credential $Credential `
                                 -IgnoreCertificateWarnings
if (-not $sessions) { throw "no appliance connected" }

try {
    Write-Host "connected to $($HostName -join ', ')" -ForegroundColor Cyan
    Get-TintriServerSession | Format-Table -AutoSize

    $cutoff = (Get-Date).AddDays(-$StaleDays)

    # -SearchAllTintriServers queries every connected appliance at once
    $vms = Get-TintriVM -SearchAllTintriServers -Refresh
    Write-Host "VMs across fleet: $($vms.Count)`n"

    $rows = foreach ($vm in $vms) {
        $snaps = Get-TintriVMSnapshot -VM $vm -ErrorAction SilentlyContinue
        if (-not $snaps) { continue }

        # -Until bounds the query to snapshots older than the cutoff
        $stale = Get-TintriVMSnapshot -VM $vm -Until $cutoff -ErrorAction SilentlyContinue

        [pscustomobject]@{
            VM          = $vm.VmwareVM.Name
            Appliance   = $vm.ApplianceName
            Total       = @($snaps).Count
            Stale       = @($stale).Count
            VmConsistent= @($snaps | Where-Object {
                              $_.Consistency -eq 'VM_CONSISTENT' }).Count
            OldestDays  = if ($snaps) {
                              [math]::Round(((Get-Date) -
                                (@($snaps) | Sort-Object CreateTime)[0].CreateTime
                              ).TotalDays, 1)
                          } else { 0 }
            StaleSnaps  = $stale
        }
    }

    $rows | Sort-Object OldestDays -Descending |
        Format-Table VM, Appliance, Total, Stale, VmConsistent, OldestDays -AutoSize

    $candidates = $rows | Where-Object { $_.Stale -gt 0 }
    Write-Host ("`nVMs with snapshots older than $StaleDays days: " +
                "$($candidates.Count)") -ForegroundColor Yellow

    if (-not $Cleanup) {
        Write-Host 'Report only. Add -Cleanup to preview removals.'
        return
    }

    # ---- cleanup path, deliberately narrow
    $toRemove = foreach ($c in $candidates) {
        foreach ($s in $c.StaleSnaps) {
            if ($DescriptionPattern -and $s.Description -notlike $DescriptionPattern) {
                continue      # never touch snapshots you did not name
            }
            [pscustomobject]@{ VM = $c.VM; Snapshot = $s }
        }
    }

    if (-not $DescriptionPattern) {
        Write-Warning ('No -DescriptionPattern given. Refusing to remove ' +
                       'snapshots indiscriminately. Supply a pattern such as ' +
                       '"pre-change-*" that matches only snapshots your own ' +
                       'process created.')
        return
    }

    if (@($toRemove).Count -gt $MaxRemove) {
        Write-Warning ("$(@($toRemove).Count) candidates exceeds -MaxRemove " +
                       "$MaxRemove. Narrow the pattern or raise the ceiling " +
                       'deliberately.')
        return
    }

    foreach ($t in $toRemove) {
        if ($Commit) {
            # ShouldProcess is implemented by the cmdlet
            Remove-TintriVMSnapshot -Snapshot $t.Snapshot -Confirm:$false
            Write-Host "REMOVED  $($t.VM)  $($t.Snapshot.Description)"
        } else {
            Remove-TintriVMSnapshot -Snapshot $t.Snapshot -WhatIf
        }
    }

    if (-not $Commit) {
        Write-Host ("`n$(@($toRemove).Count) snapshot(s) would be removed. " +
                    'Re-run with -Commit to apply.') -ForegroundColor Yellow
    }
}
finally {
    Disconnect-TintriServer -TintriServer $sessions -ErrorAction SilentlyContinue
}

The refusal to run without -DescriptionPattern is the important guard. A cleanup script that deletes anything older than N days will eventually delete the one snapshot somebody was relying on. Requiring a pattern means the script can only remove snapshots your own process named, which is the difference between automation and an incident.

08. Prevention beats cleanup

# the pattern that stops sprawl existing: retention at creation
function New-PreChangeSnapshot {
    param(
        [Parameter(Mandatory)]$VM,
        [Parameter(Mandatory)][string]$ChangeRef,
        [int]$KeepDays = 14,
        [switch]$Quiesce
    )
    $args = @{
        VM                  = $VM
        SnapshotDescription = "pre-change-$ChangeRef-$(Get-Date -f yyyyMMdd)"
        RetentionMinutes    = $KeepDays * 24 * 60
        PassThru            = $true
    }
    if ($Quiesce) { $args.SnapshotConsistency = 'VM_CONSISTENT' }
    New-TintriVMSnapshot @args
}

# description carries the change reference, retention expires it automatically,
# and the description pattern makes the cleanup script above safe to run
New-PreChangeSnapshot -VM $vm -ChangeRef CHG0042318 -KeepDays 14 -Quiesce

Two habits, and the sprawl problem largely stops existing. Put the change reference in the description so anyone can trace why a snapshot exists, and always set -RetentionMinutes so that forgetting to clean up is not an option.

Cmdlet names, parameter sets and the shipped examples above are taken from the help packaged with Tintri PowerShell Core Toolkit 5.1.0.1. Property names on returned objects, such as the snapshot description and creation time fields, should still be confirmed with Get-TintriVMSnapshot -VM $vm | Get-Member on your build before scheduling anything. Nothing here is official guidance from any vendor.

Leave a Reply