Remote_NewSession.ps1

function Remote-NewSession {
    $machineName = Read-Host -Prompt "Enter machine name"
    $existingSession = Get-PSSession | Where-Object { $_.ComputerName -eq $machineName }
    
    if (!$existingSession) {
        $newSession = New-PSSession -ComputerName $machineName
        try {
            Connect-PSSession -Session $newSession.Id
            Write-Output "Connected to the new session successfully."
        }
        catch {
            Write-Output "Failed to connect to the new session."
        }
    }
    elseif ($existingSession.State -ne "Opened") {
        try {
            Connect-PSSession -Session $existingSession.Id
            Write-Output "Connected to the existing session successfully."
        }
        catch {
            Write-Output "Failed to connect to the existing session."
        }
    }
    else {
        Write-Output "Session is already opened."
    }
}