Why does this work?

Welcome Forums General PowerShell Q&A Why does this work?

This topic contains 4 replies, has 4 voices, and was last updated by

js
 
Participant
2 months ago.

  • Author
    Posts
  • #111766

    Participant
    Points: 1
    Rank: Member

    Why does ($a = "this") return "this"? Also, what is that return/output called?

    Is there an implicit return there? I know ("this") returns "this", but I don't understand why ($a = "this") returns "this".

  • #111778

    Participant
    Points: 59
    Rank: Member
    
    "this"
    
    

    returns

    
    this
    
    

    because it invokes the default cmdlet

    
    write-output
    
    

    in other words,

    
    "this"
    
    

    is the same as

    
    write-output "this"
    
    

    Now,

    
    $a = "this"
    
    

    is a simple variable assignment that outputs nothing. Nevermind that PowerShell also "determines" the data type of the variable $a on the fly

    However, when you enclose an expression in brackets like:

    
    ($a = "this")
    
    

    Here's what happens:

    – PowerShell evaluates the expression "this", next

    – PowerShell "picks" a suitable data type for variable $a, next

    – PowerShell assigns the $a variable the value from the expression "this", next

    – PowerShell also puts the value from the expression "this" in the stio pipeline (outputs it to console)

    This is useful in if statements or while loops where you want to evaluate an expression/condition as well as save it to a variable for further processing in the script block of the  if statement or while loop for example.

  • #111781

    Participant
    Points: 0
    Rank: Member

    Hi,

    With PowerShell, toi do not have to type thé variable, like you Say it's implicite.

     

    If i do

    $x ="test"

    Write-host " Valeur de X : $x"

    It will equal to Valeur de X : test.

    And the variable is a string.

     

  • #111784

    Participant
    Points: 0
    Rank: Member

    Sorry, i haven't saw your replay Boutros.

  • #111788
    js

    Participant
    Points: 202
    Helping Hand
    Rank: Participant

    That's a nice way to do an assignment with a "passthru", thanks. I've seen people do something like this, but it fails:

    $a = 'hi' | measure

You must be logged in to reply to this topic.