显示默认值的powershell强制参数 [英] powershell mandatory parameter with default value shown

查看:240
本文介绍了显示默认值的powershell强制参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来让PowerShell脚本要求输入一个必需参数,但该参数必须显示为默认值,例如:

I am looking for a way to have an PowerShell script ask for an parameter which needs to be mandatory, but shown with an default value, e.g.:

    .\psscript
    Supply values for the following parameters:
    parameter1[default value]:
    parameter2[1234]:

我想输入信息,但提供一些默认值.

I want to ask for input but provide some default values.

如果我使用强制选项,它将很好地询问值,但不显示默认值或处理给定的值.如果我不强制执行该命令,那么PowerShell根本不会要求该值.

If I use the mandatory option it asks for the values nicely but doesn't show the default value or process the given value. If I don't make it mandatory then PowerShell doesn't ask for the value at all.

这是我尝试过的一些脚本示例:

Here's some script examples I tried:

    [CmdletBinding()]
    Param(
        [parameter(Mandatory=$true)] $SqlServiceAccount = $env:computername + "_sa",
        [parameter(Mandatory=$true)] $SqlServiceAccountPwd
    )

如果我只是按第一个参数的Enter键,此脚本会询问参数,但不会显示或处理默认值.

This script asks for parameters but does not show or process the default value if I just press enter on the first parameter.

    [CmdletBinding()]
    Param(
        [parameter(Mandatory=$false)] $SqlServiceAccount = $env:computername + "_sa",
        [parameter(Mandatory=$true)] $SqlServiceAccountPwd
    )

此脚本不要求输入第一个参数,而是处理默认值.

This script doesn't ask for the first parameter, but processes the default value.

推荐答案

下面是一个可能对您有所帮助的 short 示例:

Here's a short example that might help:

    [CmdletBinding()]
    Param(
        $SqlServiceAccount = (Read-Host -prompt "SqlServiceAccount ($($env:computername + "_sa"))"),
        $SqlServiceAccountPwd = (Read-Host -prompt "SqlServiceAccountPwd")
    )
    if (!$SqlServiceAccount) { $SqlServiceAccount = $env:Computername + "_sa" }
    ...

这篇关于显示默认值的powershell强制参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆