powershellfunctiondynamicnew-item

Dynamically create functions from hashtable with parameters in PowerShell


Question

Hi, I'd like to dynamically create functions from a hashtable in Powershell. But the created functions are supposed to be able to receive parameters.

The Code I have so far:

$functions = @{
    "wu" = "winget upgrade --include-unknown";
    "wui" = "winget upgrade -i -e";
    "wi" = "winget install -i";
    "wii" = "winget install -i -e";
    "ws" = "winget search"
}

foreach($funcName in $functions.PSBase.Keys){
    New-Item function:\ -Name $funcName -Value $([scriptblock]::Create($functions[$funcName])) | Out-Null
}

The problem is, that whatever I type behind the function is not considered a parameter: enter image description here

Can you help me out?

Answer

The finished result thanks to @zett42 & @mklement0

# Functions (separated for autocomplete)
$wg_functions = @{
    wu   = {winget upgrade @args}
    wui  = {winget upgrade -i -e @args}
    wuiu = {winget upgrade --include-unknown @args}
    wi   = {winget install -i @args}
    wii  = {winget install -i -e @args}
    ws   = {winget search @args}
}

$other_functions = @{
    dev = {Set-Location "W:/Projects/Development" @args}
    gtc = {git clone @args}
}

$functions = $wg_functions + $other_functions

foreach($funcKey in $functions.PSBase.Keys) {
    New-Item function:$funcKey -Value $functions.$funcKey | Out-Null
}

Solution

  • Here is a possible solution:

    $functions = @{
        ws = { winget search $args }
        # ... and so on
    }
    
    foreach($funcName in $functions.PSBase.Keys){
        New-Item function:\ -Name $funcName -Value $functions.$funcName | Out-Null
    }