gpt4 book ai didi

PowerShell 函数

转载 作者:行者123 更新时间:2023-12-03 00:47:41 27 4
gpt4 key购买 nike

PowerShell 脚本中的函数被命名为代码块,它可以轻松地组织脚本命令。

定义使用:

Function [Scope Type:]<Function name>

例子:
Function Test
{
Write-Host "Test method"
}
Test

带参数的函数

例子:
Function Test( $msg)
{
Param ([string] $msg)
Write-Host "$msg"
}
Test "Test method"

输出:
Test method

参数类型:
  • 命名参数:Param ([int] $first,[int] $second)
  • 位置参数:$args[0], $args[1]
  • 切换参数:Param([Switch] $one,[Switch] $two)
  • 动态参数:Set-Item -path alias:OpenNotepad -value c:\windows\notepad.exe

  • 这些“开关参数”如何在 PowerShell 脚本中工作?

    最佳答案

    它就像一个 bool 值,但您不必(但可以)通过 $true$false给它。例子:

    function Test-SwitchParam
    {
    Param(
    [Switch] $one,
    [Switch] $two
    )

    if ($one)
    {
    Write-Host "Switch one is set"
    }

    if ($two)
    {
    Write-Host "Switch two is set"
    }
    }

    现在你可以像这样调用函数:
    Test-SwitchParam -one

    开关 $one将是 $true ,因为它是设置的,并且 $two将是错误的。

    关于PowerShell 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39608708/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com