0

I'm trying to enter in every computer in a list I have and remove a software from it.

When I try the code (not using foreach), the code works fine. But when I try to loop it, it doesnt work at all.

Where there is "do something", it doesn't do anything. For instance, I tried to do:

$product = Get-WmiObject -Class Win32_Product | Where-Object {$_.name -like "7-zip*"} 

and in the next line, print on screen the $product variable. But it's always empty.

When I manually enter a pssession and run this command, it returns me something.

What I'm doing wrong here? I already wasted hours trying to figure this out, but no luck :(

foreach ($computer in $computers){

    if(Test-Connection "$computer" -Count 1 -ErrorAction SilentlyContinue){

        Enter-PSSession -ComputerName $computer

        "do something"

        Exit-PSSession

    }else{

        Write-Warning "computer is offline."

    }
}
Itchydon
  • 2,572
  • 6
  • 19
  • 33
mergulhao21
  • 33
  • 1
  • 7
  • 2
    https://stackoverflow.com/questions/3705321/enter-pssession-is-not-working-in-my-powershell-script - `Enter-PSSession` is not meant to be used in scripts. It's for interactive use only. – Thomas Glaser Aug 25 '17 at 13:01

1 Answers1

1

Use invoke-command Example:

$ReturnValue = Invoke-Command -ComputerName $ComputerName -ScriptBlock{
    #DoSomethingHere
}
Write-host $Returnvalue #Will print the output of the scriptblock
guiwhatsthat
  • 2,349
  • 1
  • 12
  • 24