Private/Invoke-ISNuGetCommand.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
74
75
76
77
78
79
80
81
82
83
<#
.SYNOPSIS
    Invokes a NuGet command
.DESCRIPTION
    The Invoke-ISNuGetCommand cmdlet is a wrapper around NuGet.exe. Running the cmdlet will allow you to run various forms of NuGet commands.
    The output from the cmdlet will be the exact same as a running a regular instance of NuGet.exe with the same parameters.
    If an argument does not require a parameter, pass $null as the parameter.
.EXAMPLE
        $NuGetArguments = @{
            "SomePackageName" = $null
            '-NonInteractive' = $null
            -OutputDirectory' = C:\Temp\
        }
        Invoke-ISNuGetCommand -Action "install" -Arguments $NugetCommand
.INPUTS
    String, Hashtable
.OUTPUTS
    String
#>

function Invoke-ISNuGetCommand
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [ValidateSet('list', 'install', 'setApiKey', 'sources', 'config', 'locals', 'update')]
        [string]$Action,

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [hashtable]$Arguments
    )

    try
    {
        $argArr = @()
        $argArr += $Arguments.GetEnumerator() | Sort-Object Value | ForEach-Object {
            if (-not $_.Value)
            {
                '"{0}"' -f $_.Key
            }
            else
            {
                '-{0} "{1}"' -f $_.Key, $_.Value
            }
        }
        $argString = $argArr -join ' '

        $stdOutTempFile = [System.IO.Path]::GetTempFileName()
        $stdErrTempFile = [System.IO.Path]::GetTempFileName()

        $startProcessParams = @{
            FilePath               = $NUGET_EXE
            ArgumentList           = "$Action $argString"
            RedirectStandardError  = $stdErrTempFile
            RedirectStandardOutput = $stdOutTempFile
            Wait                   = $true
            PassThru               = $true
            NoNewWindow            = $true
        }

        Write-Verbose -Message ("Running command: {0} {1}" -f $startProcessParams.FilePath, $startProcessParams.ArgumentList)

        $cmd = Start-Process @startProcessParams
        if ($cmd.ExitCode -ne 0)
        {
            throw (Get-Content -Path $stdErrTempFile -Raw)
        } 
        else 
        {
            Get-Content -Path $stdOutTempFile -Raw
        }
    } 
    catch
    {
        $PSCmdlet.ThrowTerminatingError($_)
    } 
    finally
    {
        Remove-Item -Path $stdOutTempFile, $stdErrTempFile -Force
    }
}