Public/Get-VarStash.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<#
.SYNOPSIS
   Gets one or more variable stashes.
.DESCRIPTION
   Gets one or more variable stashes. Returns the name and the created date for each stash.
.EXAMPLE
   Get-VarStash
 
   Gets all available variable stashes.
.EXAMPLE
   Get-VarStash -Name MyStash
 
   Gets the variable stash called MyStash.
 
.EXAMPLE
   Get-VarStash -Name My*
 
   Gets variable stashes with names starting with 'My'.
 
.EXAMPLE
    Get-VarStash -Index 2
 
    Gets the variable stash on index position 2 in the stash. Index starts with 0.
#>

function Get-VarStash {
    [CmdletBinding(DefaultParameterSetName = '__AllParameterSets')]
    param(
        [parameter(ParameterSetName = 'Name',
                   ValueFromPipeline = $true,
                   ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$Name,

        [parameter(ParameterSetName = 'Index',
                   ValueFromPipeline = $true,
                   ValueFromPipelineByPropertyName = $true)]
        [ValidateRange(0, [int]::MaxValue)]
        [int]$Index
    )
    
    Process {

        switch ($PSCmdlet.ParameterSetName) {
            'Name' { 
                $stashes = @(Get-ChildItem -Path "$env:APPDATA\VariableStash\VariableStash_$Name.xml" | Sort-Object -Property lastwritetime -Descending)
                if ($stashes.count -eq 0) {
                    Write-Error -Category ObjectNotFound -Message "Cannot find stash with name $Name."
                }
            }
            'Index' { 
                $stashes = @(Get-ChildItem -Path "$env:APPDATA\VariableStash\VariableStash_*.xml" | Sort-Object -Property lastwritetime -Descending | Select-Object -First 1 -Skip $Index)  
                if ($stashes.count -eq 0) {
                    Write-Error -Category ObjectNotFound -Message "Cannot find stash with index $Index."
                }
            }
            Default {
                $stashes = @(Get-ChildItem -Path "$env:APPDATA\VariableStash\VariableStash_*.xml" | Sort-Object -Property lastwritetime -Descending)
                if ($stashes.count -eq 0) {
                    Write-Error -Category ObjectNotFound -Message 'No stash found. Use Push-VarStash to create a stash.'
                }
            }
        }

        foreach ($stash in $stashes) {
            $props = @{
                Name = $stash.Name.Replace('VariableStash_','').Replace('.xml','')
                Date = $stash.LastWriteTime
            }
            New-Object -TypeName psobject -Property $props
        }

    }
}