PowerShell – By Reference

Background

It is always so easy to talk about things we know so little of.

Code

Outline

  1. Calling Routine
    • Each variable to pass by ref
      • Syntax
        • argument-in-called function ([ref] $local-variable)
      • Sample
        • strNew ([ref] $newCompanyName)
  2. Called Routine
    • Add Param Clause
      • Syntax
        • [ref] $variable-name
      • Example
        • [ref] $companyName
    • Explicitly state that value is being changed
      • Syntax
        • $variable.Value=[new-value]
      •  Example
        •   $strNew.Value=”Inprise Corp”

PowerShell


Set-StrictMode -Version Latest

function passByRef
{

    Param($str, [ref] $strNew, [ref] $loadDuration, [ref] $ratio)
    $str="Inprise Corp"
    $strNew.Value="Inprise Corp"
    $loadDuration.Value=100
    $ratio.Value=10

    $result = $loadDuration.Value / $ratio.Value
}

$company = "Borland"
$companyNameChange = ""
$loadDuration=0
$ratioLocal=-1

passByRef $company -strNew ([ref]$companyNameChange) -loadDuration ([ref]$loadDuration) -ratio ([ref]$ratioLocal)

"Company is $company"
"Company Name Change is $companyNameChange"
"loadDuration is $loadDuration"
"ratioLocal is $ratioLocal"

"Press Enter to complete"

#Wait
$HOST.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") | OUT-NULL;
$HOST.UI.RawUI.Flushinputbuffer();

Output

passByRef_20181015_0721PM

Listening

Listening to Paul Simon..

Something so right
Link

Lyrics

When the fever runs high
You’ve got the look of love light
In your eyes
And I was in crazy motion
‘Til you calmed me down
It took a little time
But you calmed me down
When something goes wrong
I’m the first to admit it
I’m the first to admit it
But the last one to know
When something goes right
Well it’s likely to lose me
It’s apt to confuse me
It’s such an unusual sight
I can’t get used to something so right
Something so right

 

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s