private/Invoke-UnraidStateChange.ps1
|
function Invoke-UnraidStateChange { [CmdletBinding(SupportsShouldProcess)] param( [Parameter(Mandatory)] [string]$Id, [Parameter()] [string]$Name, [Parameter(Mandatory)] [ValidateSet('start', 'stop', 'restart', 'forceStop', 'reboot', 'reset', 'pause', 'resume')] [string]$Action, [Parameter(Mandatory)] [ValidateSet('docker', 'vm')] [string]$Type, [Parameter()] [string]$ShouldProcessTarget, [Parameter()] [string]$ShouldProcessAction, [Parameter()] [UnraidSession]$Session = $script:DefaultUnraidSession, [Parameter(Mandatory)] [System.Management.Automation.PSCmdlet]$Cmdlet ) process { # Use Name or the Id for display $target = if ($ShouldProcessTarget) { $ShouldProcessTarget } elseif ($Name) { $Name } else { $Id } # Build action description if not provided if (!$ShouldProcessAction) { $actionMap = @{ 'start' = 'Start' 'stop' = 'Stop' 'restart' = 'Restart' 'forceStop' = 'Force Stop' 'reboot' = 'Reboot' 'reset' = 'Hard Reset' 'pause' = 'Suspend' 'resume' = 'Resume' } $resourceType = if ($Type -eq 'docker') { 'Container' } else { 'Virtual Machine' } $ShouldProcessAction = "$($actionMap[$Action]) $resourceType" } if ($Cmdlet.ShouldProcess($target, $ShouldProcessAction)) { # Build api mutation based on type and action $mutation = switch ($Type) { 'docker' { $mutationName = "$($Action.Substring(0,1).ToUpper())$($Action.Substring(1))Container" @" mutation $mutationName { docker { $Action(id: "$Id") { id state } } } "@ } 'vm' { $mutationName = "$($Action.Substring(0,1).ToUpper())$($Action.Substring(1))Vm" @" mutation $mutationName { vm { $Action(id: "$Id") } } "@ } } try { $result = Invoke-UnraidQuery -Query $mutation -Session $Session if ($result) { $displayName = if ($Name) { $Name } else { $Id } $resourceType = if ($Type -eq 'docker') { 'Container' } else { 'Virtual machine' } # Map actions to past-tense display messages $actionMessage = switch ($Action) { 'start' { 'started' } 'stop' { 'stopped' } 'restart' { 'restarted' } 'forceStop' { 'powered off' } 'reboot' { 'restarted' } 'reset' { 'reset' } 'pause' { 'suspended' } 'resume' { 'resumed' } default { $Action } } Write-Information "$resourceType $actionMessage`: $displayName" -InformationAction Continue } } catch { $displayName = if ($Name) { $Name } else { $Id } Write-Error "Failed to $Action $Type '$displayName': $_" } } } } |