functions/other/Out-PSUVariable.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
function Out-PSUVariable
{
<#
    .SYNOPSIS
        Writes the input to a variable.
     
    .DESCRIPTION
        Writes the input to a variable.
        This allows doing variable assignments at the end of a pipeline, rather than just at the beginning.
     
        Previous contents will be overwritten.
     
    .PARAMETER Name
        The name of the variable to write to.
     
    .PARAMETER InputObject
        The objects to write.
     
    .EXAMPLE
        PS C:\> Get-ChildItem | Out-PSUVariable -Name 'files'
     
        Writes the files & folders in the current path into the variable $files
     
    .EXAMPLE
        PS C:\> dir | ov files
     
        Does the same thing as the first example, only this time in a convenient interactive commandline usage
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, Position = 0)]
        [string]
        $Name,
        
        [Parameter(ValueFromPipeline = $true)]
        $InputObject
    )
    
    begin
    {
        $list = New-Object System.Collections.Generic.List[Object]
    }
    process
    {
        foreach ($object in $InputObject)
        {
            $list.Add($object)
        }
    }
    end
    {
        # Write to caller scope
        $PSCmdlet.SessionState.PSVariable.Set($Name, ($list | Write-Output))
    }
}
Import-PSUAlias -Name ov -Command Out-PSUVariable