Invoke-Expression Store Output to Variable


  • I'm trying to create a script that utilizes a program called TCPDump.  First the script calls TCPDump and loads a list of NICs into a variable called varNicList

    I then loop through that list and filter out NICs that I do not want to query.  For the NICs that I do want to query, I load a variable with the command I want to run, which captures some packets for the NIC.  With the script as is, I can see the packet info displayed in the console screen when I run the powershell script.

    However, I want to be able to load the Output from my command into another variable for manipulation, similar to what I'm doing for varNicList.  The problem is, when I create a variable and set it equal to my Invoke-Expression, I end up with nothing when the script completes. 
    I.E. = $myVar = Invoke-expression $varCommand

    How can I get this to work?  The end result I am looking to get at is to take the output from capturing the packets and filter out specifc data from each line that is returned.  I want to load the results from tcpdump into an array because it will be easier to find the values I'm looking for and use substring to grab what I need.


    My Script:


    = ./tcpdump -D

    ForEach ($varNic in $varNicList) {
    If ($varNic -match "Loopback") { Write-Host "Skipping: " $varNic}
    ElseIf ($varNic -match "Miniport") { Write-Host "Skipping: " $varNic}
    ElseIf ($varNic -match "Team") { Write-Host "Skipping: " $varNic }
    Else {
    $varCommand = "./tcpdump -nn -v -s 1500 -i " + $varNic.Substring(0,1) + " -c 1 ether[20:2]==0x2000"
    Invoke-expression $varCommand


    Tuesday, April 12, 2011 8:40 PM


All replies

  • Hi,

    Have you tried

    $myVar = & ./tcpdump ...

    instead of invoke-expression ?


    Tuesday, April 12, 2011 8:58 PM
  • I agree with AbqBill, there should be no need to use invoke-expression.  Just try

    $result = ./tcpdump -nn -v -s 1500 -i $varNic.Substring(0,1) -c 1 ether[20:2]==0x2000   # might need the last param in quotes

    That being said, it should work the way you are doing it.

    PS C:\> $test = invoke-expression "1..3"

    PS C:\> $test




    Are you sure the util is writing to stdout?  It might be going to stderr, which case try adding 2>&1 at the end, like below, to force stderr output to go through stdout:

    $result = ./tcpdump -nn -v -s 1500 -i $varNic.Substring(0,1) -c 1 ether[20:2]==0x2000 2>&1


    Tuesday, April 12, 2011 9:53 PM
  • That worked to add the &.  Thanks!

    I've got one more question.  Is there a way to set a timer when I run the command?  Sometimes the TCPDump program hangs if the NIC it is querying isn't active.  I'd like to run the command and then move on if it does not complete within 30 seconds.

    Wednesday, April 13, 2011 3:15 PM