ForEach inside a PSSession

Jonathan Yang 101 Reputation points
2021-05-09T09:15:25.01+00:00

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.

Here

$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,463 questions
0 comments No comments
{count} votes

Accepted answer
  1. Andreas Baumgarten 104K Reputation points MVP
    2021-05-09T14:00:35.747+00:00

    Hi @Jonathan Yang ,

    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)

    Regards
    Andreas Baumgarten

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful