Kralizek
Kralizek

Reputation: 2063

How to merge different Powershell macros into one?

Since .NET Core is out I've been using more and more the command line as way of working and in general I'm using a lot PowerShell.

Whilst Visual Studio Code is very command line friendly, it can't be said the same for its big brother.

To improve the situation I have added the following to my $PROFILE file.

function Execute-VisualStudioAsAdmin
{
    if ($args.Count -gt 0)
    {
        Start-Process "${env:ProgramFiles(x86)}\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\devenv.exe" $args -Verb RunAs
    }
    else
    {
        Start-Process "${env:ProgramFiles(x86)}\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\devenv.exe" -Verb RunAs
    }
}

Set-Alias vsa Execute-VisualStudioAsAdmin -Option ReadOnly

Set-Alias vs "${env:ProgramFiles(x86)}\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\devenv.exe" -Option ReadOnly

Now I can do

PS> vs

PS> vsa

PS> vs .\Solution.sln

PS> vsa .\Solution.sln

Everything works as expected but it's not as good as I would like. Maybe I'm overthinking it, but I wonder if there is a way to create a better function and have both aliases using it by passing different parameters.

Thanks in advance!

Upvotes: 3

Views: 55

Answers (1)

marsze
marsze

Reputation: 17035

What you want is this:

function Start-VisualStudio {
    [CmdletBinding()]
    [Alias("vs")]
    param(
        [Parameter()]
        [switch]$AsAdmin,
        [Parameter(
            Mandatory = $false,
            ValueFromRemainingArguments = $true
        )]
        [string[]]$ArgumentList
    )
    process {
        $parameters = @{
            FilePath = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\devenv.exe"
        } 
        if ($AsAdmin.ToBool()) {
            $parameters["Verb"] = "RunAs"
        }
        # Allow no null or empty arrays or values
        $ArgumentList  = @($ArgumentList | where {"$_" -ne ""})
        if ($ArgumentList.Count -gt 0) {
            $parameters["ArgumentList"] = $ArgumentList 
        }
        Start-Process @parameters
    }
}

Examples:

vs
vs .\Solution.sln
vs .\Solution.sln -AsAdmin

Explanations:

[CmdletBinding()] makes a function work like a compiled cmdlet. => MS Docs

[Alias()] allows you to define the alias inside the function. => MS Docs

ValueFromRemainingArguments makes an array from all arguments that are not -AsAdmin. => MS Docs

@parameters is called "splatting". => MS Docs

Upvotes: 5

Related Questions