Как определить необязательный параметр в powershell, который не имеет значения?(например, get-object -verbose) - PullRequest
0 голосов
/ 29 ноября 2018

Мне нужно предоставить отладочные или подробные данные в скрипте powershell.Как определить функцию, которая позволяет пользователю запускать с get-object или get-object -verbose?

Ответы [ 3 ]

0 голосов
/ 29 ноября 2018

Примените атрибут CmdletBinding к вашей функции:

function Get-Object
{
    [CmdletBinding()]
    PARAM()

    Write-Verbose "You'll only see this with -Verbose"
}
0 голосов
/ 29 ноября 2018

К НЕ используйте -verbose, но переключатель:

function get-object{
   param (
     [switch]$gassy
   )
   "switch gassy is {0}" -f $gassy
}

> get-object
switch gassy is False
> get-object -gassy
switch gassy is True

См. Get-Help about_commonparameters

-Verbose [: {$ true |$ false}] Псевдоним: vb

   Displays detailed information about the operation performed by the
   command. This information resembles the information in a trace or in
   a transaction log. This parameter works only when the command generates
   a verbose message. For example, this parameter works when a command
   contains the Write-Verbose cmdlet.

   The Verbose parameter overrides the value of the $VerbosePreference
   variable for the current command. Because the default value of the
   $VerbosePreference variable is SilentlyContinue, verbose messages
   are not displayed by default.

   Valid values:

       $true (-Verbose:$true) has the same effect as -Verbose.

       $false (-Verbose:$false) suppresses the display of verbose
       messages. Use this parameter when the value of $VerbosePreference
       is not SilentlyContinue (the default).
0 голосов
/ 29 ноября 2018

Вы можете вызвать функцию param.В этом случае я определил переменную с именем $obj, которая является строкой и связана с параметром командной строки с именем «Get-Object».

param (
    [string]$obj = Get-Object 
)

If($obj)
{
    "Do Something"
}
else
{
    "Do Something Else"
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...