Powershell: Can't enter PSSession

264 Views Asked by At

I am using a PromptForChoice to enter a PSSession on another server. Then code will execute that shuts down com applications.

#enters interactive remote session
$Prompt = "Click yes to enter interactive session"
$Choices = [System.Management.Automation.Host.ChoiceDescription[]] @("&Yes", "&No", "&Cancel")
$Default = 1


# Prompt for the choice
$Choice = $host.UI.PromptForChoice($Title, $Prompt, $Choices, $Default)

# Action based on the choice
switch($Choice)
{
    0 {Enter-PSSession ServerABC}
    1 { Write-Host "No"}
    2 { Write-Host "Cancel"}
}


#shutsdown COM
$sb = {
    $admin = New-Object -ComObject "COMAdmin.COMAdminCatalog"
    $appCollection = $admin.GetCollection("Applications")
    $appCollection.Populate()
    $appCollection | ForEach-Object {
      Write-Host "shutdown" $_.Name; $admin.ShutdownApplication($_.Name) }

    }

Invoke-Command -ScriptBlock $sb 

The problem I am facing that it won't actually enter the session. When I run the first section by itself, it enters the session. But when I run it as a whole, it will not enter the session, even when I say yes.

How do I correct this issue?

1

There are 1 best solutions below

0
Ralph Sch On

Don’t enter the session. That won’t work- it’s an interactive command, you’re literally leaving the script scope and at best the script will continue after exiting the session.

Create a PsSession with New-PsSession, then pass to invoke-command using -Session parameter.