Purclot
Purclot

Reputation: 559

PowerShell Syntax $using

I found a Function like:

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
    }
}

What does $using:Name or $using:SafeModePassword stand for?

Thanks for your help.

Upvotes: 5

Views: 9137

Answers (1)

zackchadwick
zackchadwick

Reputation: 111

As mentioned in one of the comments, you can see the use of $using at the about_scopes Microsoft Docs site.

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

I think this is the most pertinent explanation from the documentation.

For any script or command that executes out of session, you need the Using scope modifier to embed variable values from the calling session scope, so that out of session code can access them. The Using scope modifier is supported in the following contexts:

Remotely executed commands, started with Invoke-Command using the ComputerName, HostName, SSHConnection or Session parameters (remote session) Background jobs, started with Start-Job (out-of-process session) Thread jobs, started via Start-ThreadJob or ForEach-Object -Parallel (separate thread session)

So in the case of the script that you included, it gathers the SafeModePassword variable from the parameters when it is called. It defines it with the $Using scope so that the variable is properly passed to the remote Invoke-Command.

Upvotes: 9

Related Questions