I created this function but I don't know how to make it work. here is the code:
function ProgramRegistry {
param (
[Parameter(Mandatory=$false)][HashTable]$HashTable,
[Parameter(Mandatory=$false)][String]$AlertPath,
[Parameter(Mandatory=$false)][String]$AlertName,
[Parameter(Mandatory=$false)][String]$AlertValue
)
foreach ($AlertPath in $HashTable.Values){
foreach($AlertName in $HashTable.Values){
foreach($AlertValue in $HashTable.Values){
New-Item -Path $AlertPath -Force | Out-Null
New-ItemProperty -Path $AlertPath -Name $AlertName -Value $AlertValue -PropertyType DWORD -Force
}
}
}
}
$keys = [ordered]@{
key1 = @{
AlertPath = 'Path'
AlertName = 'Name'
AlertValue = 'Value'
}
key2 = @{
AlertPath = 'Path'
AlertName = 'Name'
AlertValue = 'Value'
}
# and so on...
}
ModifyRegistry @keys
ModifyRegistry -AlertPath "path" -AlertName "name" -AlertValue "value"
I want to be able to call the function in 2 different ways (as shown in the script)
- either by defining its 3 parameters explicitly in one line.
- or by passing a nested hash table consisting of multiple objects each having the function's 3 parameters.
how can I achieve that?
I want to only modify the function and not the way I call it. I need to call it a bunch of times and want to keep the code for doing it as minimal as possible, like this ModifyRegistry @keys
. it's okay if the function itself is complicated and long but I want calls to function to take very little code like that. instead of nested hash table, I could just call the function repeatedly but it'd be too much repeated code and that's what I want to avoid.
You may modify your function to accept a hashtable of hashtables. You just need to provide some logic to check if the hashtable received is a hashtable containing other hashtables that have the values you need or if it is instead a single hashtable containing the values you need. Also needed is to handle the other parameters still when not providing a hashtable. The example below shows how I would do this in an advanced function utilizing a begin, process, and end block. In the begin block we only need to create the collection object that we will use to sift out the inputs. The process block is repeated for each input object received when using the pipeline. If supplying the arguments to the function directly this process block will only run once. We will use this process block to determine and add our input objects to the $inputs arraylist we created. In the end block we will perform the actual processing on each of the objects that we've collected.
If pipeline and advanced function is not wanted you can still do something similar without begin, process, and end blocks. I use nested function 'processit' so that I don't have to repeat the processing logic multiple times
Update in response to your question regarding using the key name as AlertName
Calling the function
Output