ForEach inside a PSSession

asked 2021-05-09T09:15:25.01+00:00
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.

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.
4,618 questions
No comments
{count} votes

Accepted answer
  1. answered 2021-05-09T14:00:35.747+00:00
    Andreas Baumgarten 66,011 Reputation points Microsoft 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)

    Regards
    Andreas Baumgarten


0 additional answers

Sort by: Most helpful