1

How to I pass a SwitchParameter to a function?

function schtsk( $triggers ) {
 $trigger = New-ScheduledTaskTrigger $triggers
}
schtsk -AtStartup

EDIT: Simpler question,

$trigger "-AtStartup"
$trigger = New-ScheduledTaskTrigger $trigger

error: Cannot convert value "System.String" to type "System.Management.Automation.SwitchParameter"

FHC
  • 71
  • 7

3 Answers3

2

What you are doing is defining a variable in a non-parameterized function. Defining all the possibilities in a function is in the PowerShell help files.

About Functions

Switch Parameters

A switch is a parameter that does not require a value. Instead, you type the function name followed by the name of the switch parameter.

To define a switch parameter, specify the type [switch] before the parameter name, as shown in the following example:

function Switch-Item {
  param ([switch]$on)
  if ($on) { "Switch on" }
  else { "Switch off" }
}

See also: About Functions Advanced for more function capabilities and About Functions Advanced Parameters.

Update as per your 'confused' comment below

Stuff like this is just an example. No matter what you call your function, you must use the parameter block to use a switch. This function could have just as easily been called ...

function MyNewFangledSwitchTag {
  param ([switch]$on)
  if ($on) { "Switch on" }
  else { "Switch off" }
}

... and it would be the same thing, and used the same way...

MyNewFangledSwitchTag  -on

Yet, never use such stuff. Always use the proper verb-noun naming convention.

Just refactor you function to be the same as the example, the name does not matter, other than using the proper conventions mentioned.

function New-MySchtsk 
{
    Param 
    (
        [switch]$AtStartUp
    )

    if ($AtStartUp) 
    { 
        'AtStartup switch used' 
         # Put the rest of your code actions here
         # $trigger = New-ScheduledTaskTrigger $triggers
    }
    else
    { 
        'AtStartup switch was not used' 
         # Put the rest of your code actions here
    }
}

New-MySchtsk -AtStartUp

A switch parameter is about a state. This is what the documentation tells you. You cannot assign/use anything else on it since that is not its purpose. If the switch is used, run the code block, if it does not, do nothing, or run some other code block.

This is the same thing as using the -WhatIf switch when testing your code or any other switch available with any built-in cmdlet. You can view the Powershell Source Code on Microsoft PowerShell github to see what cmdlets do under the covers and how parameters are implemented, used, etc.

postanote
  • 15,138
  • 2
  • 14
  • 25
  • I already saw that, confusing example. I just want to put some text after New-ScheduledTaskTrigger. -AtStartup isn't boolean, what purpose would the if/else statement serve? Is the function literally supposed to be called Switch-Item or is that just a placeholder for the name? If that is the name, how would you call multiple functions that you want to pass parameters if they are all called Switch-Item? I have one short project in Powershell and I'll probably never use it again, I wish someone could just translate my example above, would probably clear up 90% of my questions. – FHC May 17 '20 at 16:37
  • Confusing? What are you confused about. There is only one way to do a switch and that is as in the docs. You can call a function whatever you want. – postanote May 18 '20 at 00:14
  • Confused? What are you confused about? There is only one way to do a parameter switch and that is as documented. There examples of how to to do such thing in the builtin snippets in the ISE [use crtl+j] to see them on in VSCode use [crtl+alt+j]. Don't confuse the switch statement code with a parameter switch setting. Your confused statement would lead me to believe you did not read the docs I linked to beyond the sample. A switch is either used (on/yes/true) or it is not (off/no/false). – postanote May 18 '20 at 00:23
1

You can use -switch:$bool to achieve this, as suggested here, but besides the static $True and $False, you can also use your own variable. The result is that you only have to define your cmdlets/code once.

I used this with Format-Table to only show table headers first time in a loop that shall show order lines after each order.

$intIndex = 0;
$arrayOrders | ForEach-Object -Process `
{  
    # Only show table headers first time
    If($intIndex++ -eq 0) {
        $boolHideTableHeaders = $False }
    Else {
        $boolHideTableHeaders = $True }

    # Show current order
    $_ | Format-Table -HideTableHeaders:$boolHideTableHeaders `
        @{ Name = "No.";                Expression = {  $_.orderNumber                  } },
        @{ Name = "Date";               Expression = {  $_.date                         } },
        @{ Name = "Net amount";         Expression = {  '{0, 10:N2}' -f $_.netAmount    } }

    # Show order lines after each order
    Write-Line "Order lines..."
}
PatrikN
  • 119
  • 7
-1

Try this

PS> $taskTrigger = Invoke-Expression "New-ScheduledTaskTrigger $ScheduleArgs"
PS> $taskTrigger

Enabled            : True
EndBoundary        :
ExecutionTimeLimit :
Id                 :
Repetition         :
StartBoundary      : 2021-01-07T05:00:00Z
DaysInterval       : 1
RandomDelay        :
PSComputerName     :
Dmitry
  • 1