ForEach inside a PSSession

akosijesyang 101 Reputation points

Hi -

I'm currently writing a simple script. The script will run locally on my machine but it will initiate Resolve-DnsName on a remote computer - also the target machines (the machines that will be resolved). I know I need to pass the value of my test file inside a New-PSSession, though I can't get it working.


$target_computer = Get-Content -Path "C:\Scripts\targets.txt" #hosted in my local machine
Invoke-Command -Session $psremote -ScriptBlock {foreach ($target in $target_computer) {Resolve-DnsName -Name $args[0] -ErrorAction Ignore }} -ArgumentList $target

Please help?

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,430 questions
0 comments No comments
{count} votes

Accepted answer
  1. Andreas Baumgarten 99,466 Reputation points MVP

    Hi @akosijesyang ,

    to pass the $target_computer in the Invoke-Command you can try this (not tested):

    $target_computer = Get-Content -Path "C:\Scripts\targets.txt" #hosted in my local machine  
    Invoke-Command -Session $psremote -ScriptBlock {  
       foreach ($target in $using:target_computer) { Resolve-DnsName -Name $target -ErrorAction Ignore } }  


    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Andreas Baumgarten

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful