[PS] Using & to run a command with an argument in a foreach loop

Discussion in 'Scripting' started by Matt, May 16, 2006.

  1. Matt

    Matt Guest

    I'm trying to run a command passing an argument which is contained in a
    'nslookup server1' is not recognized as a cmdlet, function, operable
    program, or script file.
    At line:1 char:2
    + &$ <<<< ("nslookup server1")

    But I can run this at the command line:
    PS P:\> nslookup server1
    Server: dnsserver
    Address: #######

    Name: server1
    Address: #######

    same (correct) result with
    This just leaves me at the nslookup prompt:
    PS P:\> $computers | foreach { &$("nslookup") $_.tostring() }
    Default Server: dnsserver
    Address: #########

    What am I doing wrong here?
    Matt, May 16, 2006
    1. Advertisements

  2. Matt,

    Try $computers | foreach { $("nslookup $_" )}

    Andrew Watt MVP
    Andrew Watt [MVP], May 16, 2006
    1. Advertisements

  3. $Computers | foreach $_ {nslookup $_}

    or, more simply,

    $Computers | foreach {nslookup $_}

    works for me.

    Andrew Watt MVP
    Andrew Watt [MVP], May 16, 2006
  4. Matt

    Matt Guest

    I see what happened, I was getting the list from a text file and when i
    sorted the items the first few lines turned up blank. when i strip those out
    it works.

    but thanks for the help, i kinda feel stupid for wrestling with this all
    morning =)
    Matt, May 16, 2006
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.