PowerShell 语法 $using

Pur*_*lot 2 powershell

我发现了一个类似的函数:

function New-ActiveDirectoryForest {
    param(
        [Parameter(Mandatory)]
        [string]$Name,

        [Parameter(Mandatory)]
        [pscredential]$Credential,

        [Parameter(Mandatory)]
        [string]$SafeModePassword,

        [Parameter(Mandatory)]
        [string]$ComputerName
    )

    Invoke-Command -ComputerName $ComputerName -Credential $Credential -ScriptBlock {
        Install-windowsfeature -Name AD-Domain-Services     
        $forestParams = @{
            DomainName                    = $using:Name
            InstallDns                    = $true
            Confirm                       = $false
            SafeModeAdministratorPassword = (ConvertTo-SecureString -AsPlainText -String $using:SafeModePassword -Force)
            WarningAction                 = 'Ignore'
        }
        $null = Install-ADDSForest @forestParams
    }
}
Run Code Online (Sandbox Code Playgroud)

$using:Name$using:SafeModePassword代表什么?

感谢您的帮助。

小智 7

正如评论之一中提到的,您可以在 about_scopes Microsoft Docs 站点上查看 $using 的用法。

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scopes?view=powershell-7#scope-modifiers

我认为这是文档中最相关的解释。

对于在会话外执行的任何脚本或命令,您需要使用作用域修饰符来嵌入调用会话作用域中的变量值,以便会话外代码可以访问它们。在以下上下文中支持使用范围修饰符:

远程执行的命令,使用 ComputerName、HostName、SSHConnection 或会话参数(远程会话)通过 Invoke-Command 启动 后台作业,通过 Start-Job(进程外会话)启动 线程作业,通过 Start-ThreadJob 或 ForEach- 启动对象-并行(单独的线程会话)

因此,对于您包含的脚本,它会在调用时从参数中收集 SafeModePassword 变量。它使用 $Using 范围定义它,以便该变量正确传递到远程 Invoke-Command。