Summary: I am attempting to structure my script with less redundancy. The issue is that I am having to repeat a function for each switch although the are going to the same destination and accomplishing the same task.
Question: Is it possible to take the switch es age,name and profession and convert it to a single function?
Side Note: I am using a psobject and storing its URI, enumurating that and instantiating the $Search variable as that URI specified to each member in the psobject.
function Search-PersonnelData {
param(
[switch]$Name,
[switch]$Age,
[switch]$Profession,
[switch]$All,
[switch]$Less,
[switch]$Count,
[string]$Search,
[string]$Limit
)
if ($Limit.Length -eq 0 -or ($Limit -match $invalidnumber))
{
$Limit = 15
Write-Warning -Message 'Invalid limit specified, setting to 15 by default'
}
# HERE IS WHERE I AM REPEATING THE SAME FUNCTION OVER
# Name Query
if($Name)
{
$searchTerms = Get-QueryType -userinput Name
$Results = Invoke-RestMethod -Method Get -Uri $apiUrl$searchTerms"?term=$Search&limit=$Limit" -WebSession $currentsession
}
# Age Query
if($Age)
{
$searchTerms = Get-QueryType -userinput Age
$Results = Invoke-RestMethod -Method Get -Uri $apiUrl$searchTerms"?term=$Search&limit=$Limit" -WebSession $currentsession
}
# Profession Query
if($Profession)
{
$searchTerms = Get-QueryType -userinput 'Profession'
$Results = Invoke-RestMethod -Method Get -Uri $apiUrl$searchTerms"?term=$Search&limit=$Limit" -WebSession $currentsession
}
##########################Here is where there repeition ends###############################
if($Results.DataBase.UUID.Count -eq 0)
{
Write-Warning -Message 'No results found'
break
}
if($SignatureCount -eq $true)
{
$Results.DataBase| Group-Object | Select-Object -Property count,name -ExcludeProperty RunspaceId
}
if($Less -eq $true)
{
$Results.DataBase | Select-Object -Property $TableFormat -ExcludeProperty RunspaceId
}
if($All -eq $true)
{
$Results.DataBase | Select-Object -Property $Gridtable -ExcludeProperty RunspaceId
}
if($Count -eq $false -and ($less -eq $false)-and ($all -eq $false))
{
$Results.DataBase| Select-Object -Property $TableFormat | Format-Table -AutoSize
$Results.DataBase | Group-Object | Select-Object -Property count,name -ExcludeProperty RunspaceId | Format-Table -AutoSize
}
}
$EndPoints = New-Object psobject
Add-Member -InputObject $EndPoints -MemberType NoteProperty -Name 'Profession' -Value "by_profession"
Add-Member -InputObject $EndPoints -MemberType NoteProperty -Name 'Age' -Value "by_age"
Add-Member -InputObject $EndPoints -MemberType NoteProperty -Name Name -Value "by_Name"
function Get-QueryType {
param(
$userinput
)
$EndPoints.psobject.Members |
Where-Object {$_.Name -eq $userinput } |
? {$_.Membertype -eq "noteproperty"} |
%{ $_.Value }
}
$resultsif you have multiple switches. So it looks like you would want to use parameter sets and then do aswitchstatement on which set you use.