- Powershell Core 6.2 Cookbook
- Jan Hendrik Peters
- 210字
- 2021-06-24 15:14:24
How to do it...
Install and start PowerShell Core and execute the following steps:
- Execute the following code block:
$outerScope = 'Variable outside function'
function Foo
{
Write-Host $outerScope
$outerScope = 'Variable inside function'
Write-Host $outerScope
}
Foo
Write-Host $outerScope
You should see the following output:
- Modify the code a little bit to use scope modifiers like private, script, and local and try it again:
<#
By explicitly using scopes, you can alter the state of virtually any variable
The following scopes are available. Inner scopes can access variables from outer scopes
global: The outermost scope, i.e. your current session
script: The scope of a script or module
local: The scope inside a script block
private: In any scope, hidden from child scopes
using: This one is special.
#>
$outerScope = 'Variable outside function'
$private:invisible = 'Not visible in child scopes'
function Foo
{
Write-Host $outerScope
$script:outerScope = 'Variable inside function'
$local:outerScope = 'Both can exist'
Write-Host "Private variable content can't be retrieved: $invisible"
Write-Host $outerScope
}
Foo
Write-Host $outerScope
This time, you'll notice that you can create multiple variables with the same name in different scopes.
- Try the following code next, to see how the using scope works:
$processName = 'pwsh'
$credential = New-Object -TypeName pscredential -ArgumentList 'user',$('password' | ConvertTo-SecureString -AsPlainText -Force)
Start-Job -ScriptBlock { Get-Process -Name $processName} | Wait-Job | Receive-Job # Error
Start-Job -ScriptBlock { Get-Process -Name $using:processName} | Wait-Job | Receive-Job # Works
Start-Job -ScriptBlock { $($using:credential).GetNetworkCredential().Password } | Wait-Job | Receive-Job # Works as well
As you have seen in the output of the previous cmdlet, the using scope allows access to variables from within a script block.