question

akosijesyang avatar image
0 Votes"
akosijesyang asked AndreasBaumgarten commented

ForEach inside a PSSession

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
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

AndreasBaumgarten avatar image
1 Vote"
AndreasBaumgarten answered AndreasBaumgarten commented

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




· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi @AndreasBaumgarten

It worked! Thank you so much.

Btw, what $using: does?

Jes

0 Votes 0 ·

Hi @akosijesyang ,

maybe this helps:
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_remote_variables?view=powershell-7.1#using-local-variables


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

Regards
Andreas Baumgarten

0 Votes 0 ·