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:
Can you help me out?
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
}
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
}
{…}
directly in the hashtable, so you don't need to convert anything for the New-Item
arguments.$args
to forward arguments of the script block to the command. Note that for native commands, the $args
array is unrolled automatically. For PowerShell commands you'd have to use splatting (@args
).