{"id":4835,"date":"2019-07-21T23:03:16","date_gmt":"2019-07-22T06:03:16","guid":{"rendered":"https:\/\/www.cloudnotes.io\/?p=4835"},"modified":"2019-07-21T23:03:16","modified_gmt":"2019-07-22T06:03:16","slug":"get-all-switch-parameters-for-a-powershell-function-or-script","status":"publish","type":"post","link":"https:\/\/www.cloudnotes.io\/get-all-switch-parameters-for-a-powershell-function-or-script\/","title":{"rendered":"Get all Switch Parameters for a Powershell function or script"},"content":{"rendered":"\n<p>The other day I was working on a Powershell function to return a list and filter it through a number of <code>switch<\/code> parameters; anyway if no <code>switch<\/code> is used I want to return a default, raw result without manipulation, in other words I want the result to look like this:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">PS C:\\> .\\ListSwitchParameters.ps1 -SubscriptionOne -SubscriptionFour \n\nName                           Value\n----                           -----\nSubscriptionOne                45615ed1-0de1-4ec9-b018-71c0b37eadfd\nSubscriptionFour               5b9cc023-9250-4421-8bfc-2c98465d97f3\n\n\nPS C:\\> .\\ListSwitchParameters.ps1\n\nName                           Value\n----                           -----\nSubscriptionOne                45615ed1-0de1-4ec9-b018-71c0b37eadfd\nSubscriptionTwo                220b4052-c956-4d42-9f74-3d4c111c1c72\nSubscriptionThree              c70bab09-b330-4557-b856-328bc7ffe1a3\nSubscriptionFour               5b9cc023-9250-4421-8bfc-2c98465d97f3\nSubscriptionFive               0e9b837d-6b63-41b1-88c1-f42e8325211d<\/pre>\n\n\n\n<p>One possible approach to obtain it is code similar to this:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"shell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">param (\n    [switch]$SubscriptionOne,\n    [switch]$SubscriptionTwo,\n    [switch]$SubscriptionThree,\n    [switch]$SubscriptionFour,\n    [switch]$SubscriptionFive\n)\n\n$list = @(\n    @{'SubscriptionOne' = '45615ed1-0de1-4ec9-b018-71c0b37eadfd' },\n    @{'SubscriptionTwo' = '220b4052-c956-4d42-9f74-3d4c111c1c72' },\n    @{'SubscriptionThree' = 'c70bab09-b330-4557-b856-328bc7ffe1a3' },\n    @{'SubscriptionFour' = '5b9cc023-9250-4421-8bfc-2c98465d97f3' },\n    @{'SubscriptionFive' = '0e9b837d-6b63-41b1-88c1-f42e8325211d' }\n)\n\nif ($SubscriptionOne) { $list | where Keys -eq 'SubscriptionOne' }\nif ($SubscriptionTwo) { $list | where Keys -eq 'SubscriptionTwo' }\nif ($SubscriptionThree) { $list | where Keys -eq 'SubscriptionThree' }\nif ($SubscriptionFour) { $list | where Keys -eq 'SubscriptionFour' }\nif ($SubscriptionFive) { $list | where Keys -eq 'SubscriptionFive' }\n\nif ((-not $SubscriptionOne) -and (-not $SubscriptionTwo) -and (-not $SubscriptionThree) -and (-not $SubscriptionFour) -and (-not $SubscriptionFive)) {\n    $list\n}<\/pre>\n\n\n\n<p>It works, but it&#8217;s not very elegant or efficient&#8230; for example, what if I need to add more <code>switch<\/code> options? I would have to add additional <code>if<\/code> statements but also update the last <code>if<\/code> to make sure no switch has been used. The example above can be refactored like this:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"shell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"17,19\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">param (\n    [switch]$SubscriptionOne,\n    [switch]$SubscriptionTwo,\n    [switch]$SubscriptionThree,\n    [switch]$SubscriptionFour,\n    [switch]$SubscriptionFive\n)\n\n$list = @(\n    @{'SubscriptionOne' = '45615ed1-0de1-4ec9-b018-71c0b37eadfd' },\n    @{'SubscriptionTwo' = '220b4052-c956-4d42-9f74-3d4c111c1c72' },\n    @{'SubscriptionThree' = 'c70bab09-b330-4557-b856-328bc7ffe1a3' },\n    @{'SubscriptionFour' = '5b9cc023-9250-4421-8bfc-2c98465d97f3' },\n    @{'SubscriptionFive' = '0e9b837d-6b63-41b1-88c1-f42e8325211d' }\n)\n\n$switchParameters = (Get-Command .\\ListSwitchParameters.ps1).Parameters.Values | Where-Object SwitchParameter | foreach { Get-Variable $_.Name -ErrorAction 'SilentlyContinue' }\n$switchParameters | where Name -in ($switchParameters | where Value).Name\nif ($switchParameters.Count -eq ($switchParameters | where -not Value).Count) {\n    $list\n}<\/pre>\n\n\n\n<p>The magic happens an line <code>17<\/code>, here I have it on a one line but let me break it down: first, we can use <code>Get-Command<\/code> to retrieve the list of parameters for any script or function (here I have even getting the parameter list for the script <code>ListSwitchParameters.ps1<\/code> from within the script itself)<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"shell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">PS C:\\> (Get-Command .\\ListSwitchParameters.ps1).Parameters\n\nKey               Value\n---               -----\nSubscriptionOne   System.Management.Automation.ParameterMetadata\nSubscriptionTwo   System.Management.Automation.ParameterMetadata\nSubscriptionThree System.Management.Automation.ParameterMetadata\nSubscriptionFour  System.Management.Automation.ParameterMetadata\nSubscriptionFive  System.Management.Automation.ParameterMetadata\n\n\nPS C:\\> (Get-Command .\\ListSwitchParameters.ps1).Parameters.Values | ft\n\nName              ParameterType                                ParameterSets                                                             IsDynamic Aliases Attributes                                                      SwitchParameter\n----              -------------                                -------------                                                             --------- ------- ----------                                                      ---------------\nSubscriptionOne   System.Management.Automation.SwitchParameter {[__AllParameterSets, System.Management.Automation.ParameterSetMetadata]}     False {}      {, System.Management.Automation.ArgumentTypeConverterAttribute}            True\nSubscriptionTwo   System.Management.Automation.SwitchParameter {[__AllParameterSets, System.Management.Automation.ParameterSetMetadata]}     False {}      {, System.Management.Automation.ArgumentTypeConverterAttribute}            True\nSubscriptionThree System.Management.Automation.SwitchParameter {[__AllParameterSets, System.Management.Automation.ParameterSetMetadata]}     False {}      {, System.Management.Automation.ArgumentTypeConverterAttribute}            True\nSubscriptionFour  System.Management.Automation.SwitchParameter {[__AllParameterSets, System.Management.Automation.ParameterSetMetadata]}     False {}      {, System.Management.Automation.ArgumentTypeConverterAttribute}            True\nSubscriptionFive  System.Management.Automation.SwitchParameter {[__AllParameterSets, System.Management.Automation.ParameterSetMetadata]}     False {}      {, System.Management.Automation.ArgumentTypeConverterAttribute}            True<\/pre>\n\n\n\n<p>The <code>Values<\/code> property contains the list of ParameterNames, their type and a boolean indicating if the parameter is a <code>SwitchParameter<\/code>; since it&#8217;s switch parameters we&#8217;re looking for, it is easy to filter this list. Last, we can use <code>Get-Variable<\/code> to retrieve the actual value for each Switch Parameter. Now, I admit my example is not very realistic since I am assuming the Switch Parameter has the same name as the property I want to return from the list but you can still see how with this technique there is no need to explicitly check if each switch parameter has been used or not. This is even clearer in the last <code>if<\/code> statement, where I am just counting the number of switch parameters whose value is <code>$false<\/code> and check that number is equal to the total number of switch parameters in the script: if the two values match it means no switch parameter has been used, therefore I can return the raw, unfiltered list<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"shell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">if ($switchParameters.Count -eq ($switchParameters | where -not Value).Count) {\n    $list\n}<\/pre>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<p> I can calculate the motion of heavenly bodies, but not the madness of people &#8211;  <a href=\"http:\/\/quotes4all.net\/isaac-newton-quotes\" target=\"_blank\" rel=\"noreferrer noopener\" aria-label=\" (opens in a new tab)\">Isaac Newton<\/a>\u00a0 <\/p>\n","protected":false},"excerpt":{"rendered":"<p>The other day I was working on a Powershell function to return a list and filter it through a number of switch parameters; anyway if no switch is used I want to return a default, raw result without manipulation, in other words I want the result to look like this: One possible approach to obtain it is code similar to this: It works, but it&#8217;s not very elegant or efficient&#8230; for example, what if I need to add more switch options? I would have to add additional if statements but also update the last if to make sure no switch has been used. The example above can be refactored like this: The magic happens an line 17, here I have it on a one line but let me break it down: first, we can use Get-Command to retrieve the list of parameters for any script or function (here I have even getting the parameter list for the script ListSwitchParameters.ps1 from within the script itself) The Values property contains the list of ParameterNames, their type and a boolean indicating if the parameter is a SwitchParameter; since it&#8217;s switch parameters we&#8217;re looking for, it is easy to filter this list. Last, we can use Get-Variable to retrieve the actual value for each Switch Parameter. Now, I admit my example is not very realistic since I am assuming the Switch Parameter has the same name as the property I want to return from the list but you can still see how with this technique there is no need to explicitly check if each switch parameter has been used or not. This is even clearer in the last if statement, where I am just counting the number of switch parameters whose value is $false and check that number is equal to the total number of switch parameters in the script: if the two values match it means no switch parameter has been used, therefore I can return the raw, unfiltered list I can calculate the motion of heavenly bodies, but not the madness of people &#8211; Isaac Newton\u00a0<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_uag_custom_page_level_css":"","advgb_blocks_editor_width":"","advgb_blocks_columns_visual_guide":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[35],"tags":[40],"class_list":["post-4835","post","type-post","status-publish","format-standard","hentry","category-powershell","tag-powershell"],"author_meta":{"display_name":"carloc","author_link":"https:\/\/www.cloudnotes.io\/author\/admin\/"},"featured_img":null,"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false,"savona-slider-full-thumbnail":false,"savona-slider-grid-thumbnail":false,"savona-full-thumbnail":false,"savona-grid-thumbnail":false,"savona-single-navigation":false},"uagb_author_info":{"display_name":"carloc","author_link":"https:\/\/www.cloudnotes.io\/author\/admin\/"},"uagb_comment_info":0,"uagb_excerpt":"The other day I was working on a Powershell function to return a list and filter it through a number of switch parameters; anyway if no switch is used I want to return a default, raw result without manipulation, in other words I want the result to look like this: One possible approach to obtain&hellip;","coauthors":[],"tax_additional":{"categories":{"linked":["<a href=\"https:\/\/www.cloudnotes.io\/category\/powershell\/\" class=\"advgb-post-tax-term\">Powershell<\/a>"],"unlinked":["<span class=\"advgb-post-tax-term\">Powershell<\/span>"]},"tags":{"linked":["<a href=\"https:\/\/www.cloudnotes.io\/category\/powershell\/\" class=\"advgb-post-tax-term\">Powershell<\/a>"],"unlinked":["<span class=\"advgb-post-tax-term\">Powershell<\/span>"]}},"comment_count":"0","relative_dates":{"created":"Posted 7 years ago","modified":"Updated 7 years ago"},"absolute_dates":{"created":"Posted on July 21, 2019","modified":"Updated on July 21, 2019"},"absolute_dates_time":{"created":"Posted on July 21, 2019 11:03 pm","modified":"Updated on July 21, 2019 11:03 pm"},"featured_img_caption":"","series_order":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/paQTEh-1fZ","jetpack_likes_enabled":true,"jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/www.cloudnotes.io\/wp-json\/wp\/v2\/posts\/4835","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.cloudnotes.io\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.cloudnotes.io\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.cloudnotes.io\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.cloudnotes.io\/wp-json\/wp\/v2\/comments?post=4835"}],"version-history":[{"count":1,"href":"https:\/\/www.cloudnotes.io\/wp-json\/wp\/v2\/posts\/4835\/revisions"}],"predecessor-version":[{"id":4836,"href":"https:\/\/www.cloudnotes.io\/wp-json\/wp\/v2\/posts\/4835\/revisions\/4836"}],"wp:attachment":[{"href":"https:\/\/www.cloudnotes.io\/wp-json\/wp\/v2\/media?parent=4835"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.cloudnotes.io\/wp-json\/wp\/v2\/categories?post=4835"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.cloudnotes.io\/wp-json\/wp\/v2\/tags?post=4835"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}