Sunday, May 19, 2024
HomePowershellPowerShell is enjoyable :)Utilizing $utilizing in PowerShell for native variables in distant...

PowerShell is enjoyable :)Utilizing $utilizing in PowerShell for native variables in distant periods


When working scripts that connect with distant methods utilizing Invoke-Command, you need to use your native variables within the distant session which makes issues loads simpler. On this weblog put up, I’ll present you ways 🙂

What are distant variables?

“You should use variables in instructions that you simply run on distant computer systems. Assign a price to the variable after which use the variable instead of the worth.

By default, the variables in distant instructions are assumed to be outlined within the session that runs the command. Variables which can be outlined in an area session, should be recognized as native variables within the command.”

Supply: https://be taught.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_remote_variables?view=powershell-7.4#long-description

How does this work?

If in case you have a script or operate that has parameters, for instance, and also you wish to use these in a distant system utilizing Invoke-Command, then you need to use the $utilizing:variable to move these throughout execution.

Within the instance under, I take advantage of a easy operate to connect with a system to start out a Home windows Service and set the Startup Kind to Automated. (And sure, you are able to do this utilizing Get-Service and Set-Service with the -ComputerName parameter… However that is simply an instance 🙂 )

param (
    [Parameter(Mandatory = $true)][String[]]$ComputerName = $env:COMPUTERNAME,
    [parameter(Mandatory = $true)][ValidateSet("Automatic", "Boot", "Disabled", "Manual", "System")][string]$StartupType,
    [Parameter(Mandatory = $true)][String]$ServiceName

)

#Hook up with distant system, begin the service and configure the service(s) Startup Kind
Invoke-Command -ComputerName $ComputerName -ScriptBlock {
    Begin-Service -Title $utilizing:ServiceName
    Set-Service -Title $utilizing:ServiceName -StartupType $utilizing:StartupType
    Get-Service -Title $utilizing:ServiceName
}

Working this above towards two machines (One Home windows 11 consumer and one Home windows Server 2022 in my lab on this case) will use the $ServiceName and $StartupType variables you specify as parameters for the script within the ScriptBlock. (This makes working scripts extra versatile than utilizing variables within the script itself.)

Wrapping up

By utilizing the $utilizing distant variable, you possibly can take any native variable right into a distant session. You possibly can learn extra about utilizing it in several situations right here.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments