简体   繁体   中英

PowerShell function as parameter in function

All,

I am working on a function, and in the function I would like to use another function which I have created as a parameter. For below, I would like to bring up a calendar selector that I have created (Select-Date) as a prompt after you've run the Add-TempLocalAdmin function. Is there a better way to do this? Should I just take the date selection out of the parameters and call it below in the Begin block (not shown)? If this is the right way, how to I make the Select-Date parameter available?

function Add-TempLocalAdmin {
[CmdletBinding()]
param(
    [Parameter(Position=0, ValueFromPipeline=$true, Mandatory=$true)]
    [string[]]$ComputerName,
    [Parameter(Position=1, Mandatory=$true)]
    [string]$Trustee,
    [Parameter(Mandatory=$true)]
    [string]$Requester,
    [Parameter(Mandatory=$true)]
    [string]$ServiceNowCR,
    [Parameter(Mandatory=$true)]
    [datetime]$StartDate = Select-Date,
    [Parameter(Mandatory=$true)]
    [datetime]$EndDate = Select-Date,
    [Parameter(Mandatory=$true)]
    [string]$Grantor = $env:USERNAME
    )
Write-Host $ComputerName $Trustee $Requester $ServiceNowCR $StartDate $EndDate $grantor
}

If you say the parameter is mandatory, then PowerShell will prompt the user for the parameter's value if the user omits it.

You can call a function as the default value for a parameter. If the user omits a value for the parameter, you can run the function. You can do that like this:

[DateTime] $MyDate=$(Select-Date)

(What value gets returned if the user cancels the selection? You will have to deal with that contingency in your code.) Don't declare it as mandatory in this case.

Do you really need a Select-Date function? If you require a date for a parameter, then declare as a mandatory [DateTime] - the user will need to provide a date for the parameter, or the function won't run.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM