Save the Connect-VIServer session between scripts?

In order to make the GUI for people who are not used to the command line, we want to look at aid where VBScript code call scripts powershell to work behind the scenes of the HTA.  The only problem is the delay of connecting to VIServer for what the user does.  Say they click on a button for a list of the virtual machine, it could trigger a ps script which collects and posts this info using the Clipboard.  After that, however, that the script is closed and therefore the session.  The button depending on whether they click should also have a sign at the beginning of the script, accompanied by another 10 seconds to wait on the connection.  Is there a way to store/save the session so that we can connect onload of the code of the road and all the following scripts could continue with this session?

Thank you

Josh

Keep the open sessions is not a good idea imho, and the maximum number of sessions is limited.

Have you tried all the known solutions to accelerate the PowerCLI process?

Another possible way is to use a central script that runs continuously in the background and you submit orders from your application to this central script through a sort of semaphores (this could be simple files in a specific folder for example).

Update: there used to Save Session and Load-Session cmdlets in previous versions of PowerCLI, but these were dropped.

Tags: VMware

Similar Questions

  • How to make the Connect-VIServer cmdlet to always ask for username password

    Hi all

    I use the connect-viserver cmdlet to connect between host windows to my vcenter server.

    using

    The host - Powershell - 2.0, Windows XP, Powercli installed machine.

    Target machine - Vcenter server 4.1.0 on windows 2008 server, in the other subnet

    I want to have a provision that it must always ask for user name and password to connect.

    I took a look at

    http://pubs.VMware.com/vSphere-50/index.jsp?topic=/com.VMware.wssdk.apiref.doc_50/Vim.virtualmachine.html

    resultof = % 22connect - viserver % 22 & http://pubs.VMware.com/vSphere-50/index.jsp?topic=/com.VMware.PowerCLI.cmdletref.doc_50/connect-VIServer.html

    But failed to get the relevant information.

    Any ideas?

    Thank you

    Madalena

    Bangalore-India

    My mistake, Connect-ViServer does not accept a SecureString. You first need to convert it

    Try it like this

    $userName = "username"
    $passwd = Read-Host ("Password for " + $userName) -AsSecureString:$true
    $cred = New-Object System.Management.Automation.PSCredential -ArgumentList $userName,$passwd
    Connect-VIServer -Server MyServer -Credential $cred
    
  • Unable to save the connection Wireless to a flash drive

    I'm saving my connections without wire of a machine so that I can import them on another. I use the wizrad to Windows 7 and I'm to the point where I hit next to export or copy the settings on an external drive. Once I have click on next to start the copy I get an error that says:

    Impossible to copy the settings to the USB flash Drive

    Windows cannot save your network settings on the flash drive.

    The flash drive is visible in Windows Explorer and I can copy files it it.

    -Russ

    Hi Russ,

    Thanks for posting your question in the community of Microsoft Windows.

    From the description of the problem, it seems that you can not save the settings of the wireless connection to a flash drive.

    I imagine the inconvenience that you are experiencing. I'll help you fix the problem.

    I suggest save wireless settings using Netsh commands to export a profile wireless existing to a XML file, then import the wireless profile settings stored in the XML file on another computer.

    Follow the steps in the link below to import and export wireless profiles.

    Import and export wireless profiles:

    http://TechNet.Microsoft.com/en-us/library/dd283011 (v = ws.10) .aspx

    Note: This also applies to the Windows 7 operating system.

    If the problem persists, I suggest you to ask your question in the Technet forums to get help from the link below.

    Windows 7 networking:

    http://social.technet.Microsoft.com/forums/en-us/w7itpronetworking/threads

    I hope that the information above helps you.

    In the future if you fall on any question relating to Windows, please do not hesitate to post your request here on Microsoft Community, we will be more than happy to help you.

  • Firefox does not save the connection ID

    I would like to register my code for the sites that require a login. I never save the password, just the code.
    Don't know what combination of setting lets do this
    The parameters I tried:
    Don't forget history of navigation > 0
    And parameters customized to clear:
    Clear passwords
    Clear shape data
    It seems that when I put "remember...". "0 days then my ID disappears the next day. I do check not control it clear of passwords and Date of precise form on the assumption that these two ratingses, but that makes no difference.

    In Firefox 3.5 and later "form and search history" entries expire just like the "regular" browser history

    The pref browser.history_expire_days determines the expiration of items of history and also data form and the research of the effects.

    See http://kb.mozillazine.org/browser.history_expire_days (180) (also affects saved form data)

    Make sure that you do not remove the navigation, search and download history on Firefox to clear "form & search history".

  • Share the attribute Scope Session between Bean and Servlet

    Hello

    I use jdeveloper 11.1.1.3.0

    Before I created a post on java.util.Map page jspx parameter sent to a servlet. pass to the parameter java.util.Map to Servlet

    The proposed solution was the setting of the card to the session scope attribute and use this parameter in the servlet.

    I created a bean with a session scope and defined an attribute (MapParam) in this bean and set the value to him.

    But when I want to get the value of this attribute (MapParam) in a servlet doGet method via the below code, it returns null

    public void doGet(HttpServletRequest request,  HttpServletResponse response) throws ServletException,
                                                               IOException {
    
                     HashMap param = (HashMap)request.getSession().getAttribute("MapParam"); // returns null
    
    }
    

    I want to know how to fix this?

    Habib

    Habib,

    The SessionScope and an extended session bean are two different things. SessionScope is a map interface to the set of objects that are directly related to the HttpSession (via the HttpSession.setAttribute () method. A scope of session bean is one of those objects that are related to the HttpSession. Setting a property of a range session bean does not mean that you add this property directly to the SessionScope, so you cannot directly search the SessionScope for this property. You can search however for the purpose of bean in the SessionScope and then take the value of the property of the bean object.

    Assuming that your level of the session bean is mapped under the name of "uiStateBean" and its class is screen. UiState, you can get the MapParam in the servlet in the following way:

    public void doGet(HttpServletRequest request,  HttpServletResponse response) throws ServletException,  IOException {
      UiState bean = (UiState)request.getSession().getAttribute("uiStateBean"); // Get the uiStateBean instance from the HttpSession
      HashMap param = (bean==null) ? null : bean.getMapParam(); // Get the MapParam value from the bean instance
      ...
    

    Dimitar

    P.S. The naming convention you use is misleading and it is causing a lot of vagueness. You use the name of "_sessionScope" for a range of session bean, which is not the same thing as SessionScope himself. You also use the name of "MapParam" for a member variable, which is inconsistent with the conventions of Java where the Member variables names must not start with a capital letter. Class and interface names must start with an uppercase letter instead.

  • Connect-VIServer throws the invalid URI error in the Studio of Powershell, but is very well outdoors

    I don't know if it's a problem of Powershell Studio 2014 or PowerCLI, but other people have reported the "invalid URI: the hostname could not be parsed" error, so I'll start here.

    I have a PowerCLI 5.0.1 on Windows 7, Powershell v2.0 and Powershell Studio 2014.

    In my script, when I run the Connect-VIServer-Server $server command, the command fails and generates the invalid URI error.  However, when I run my script in the command window PowerCLI, the script works fine.

    I guess I have a problem of environment in the Studio of Powershell, but wonder what circumstances causes PowerCLI to raise this error.

    So far, I have not had much luck with Studio 2014 Powershell and PowerCLI, don't know if it's powershell v2.0 or something else.

    It looks like a Studio of Powershell environment problem.

    I have many ps1 files and use the point of supply to load the files ps1 in support which includes the call to connect-VIServer.  When I put the connect-VIServer in the file main ps1 I can connect to my vCenter, but when I put in the origin file, I cannot connect, nor can fact the fitting of test-work order.

    Thanks for the help.

  • start-work using connect-viserver hangs in powercli 6

    Hello

    Previously, I used powercli jobs to execute commands to invoke vmscript quite successfully in our workplaces 5.1 and 5.1.

    I'm testing these scripts in vSphere 6 with pwoercli 6 and am having some problems with the script.

    An example of the previous scripts that worked is as follows:

    -----------------------------------

    Start-job-name $vm - RunAs32 - PSVersion 2.0 - scriptblock {}

    Param ($vm, $vcentre, $GuestCred, $session)

    {if(!$Global:DefaultVIServer)})

    If (!) () Get-pssnapin. where {$_.name - eq "vmware.vimautomation.core"})) {}

    try {}

    Add-pssnapin VMware.VimAutomation.Core - ea 0. out-null

    } catch {}

    throw "could not load the PowerCLI snap."

    }

    }

    try {}

    to connect-viserver $vcentre - $session wa - 0 session | out-null

    } catch {}

    throw "Failed to connect to server VI".

    }

    }

    $TestGuestCredentials = "dir C:\. »

    Invoke-VMScript - VM $vm GuestCredential - $GuestCred - $TestGuestCredentials ScriptText

    } - ArgumentList, $vm, $GuestCred, $session, $vcentre | FT

    -----------------------------------

    Now, in powercli 6 using modules that I tried to edit the script as well as the previous option using addsnapin is no longer works:

    -----------------------------------

    Start-job-name $vm - RunAs32 - PSVersion 4.0 - scriptblock {}

    Param ($vm, $vcentre, $GuestCred, $session)

    If (!) () Get-Module-name VMware.VimAutomation.Core - ErrorAction SilentlyContinue)) {}

    . "C:\Program Files (x 86) \VMware\Infrastructure\vSphere.

    }

    try {}

    to connect-viserver $vcentre - $session wa - 0 session | out-null

    } catch {}

    throw "Failed to connect to server VI".

    }

    $TestGuestCredentials = "dir C:\. »


    Invoke-VMScript - VM $vm GuestCredential - $GuestCred - $TestGuestCredentials ScriptText

    } - ArgumentList, $vm, $GuestCred, $session, $vcentre | FT

    -----------------------------------

    Using the foregoing in powercli 6 that the work never ends.  It's as if the connect-viserver command causes a response that requires intervention and locks work.


    If I remove the connect-viserver in the work section - it full well.

    Any ideas would be very appreciated!

    See you soon

    Have you tried switching of warning messages via the cmdlet Set-PowerCLIConfiguration , the DisplayDeprecationWarnings parameter?

  • connection of several VC with connect-viserver

    Based on another post, I tried to connect to multiple environments within a script.   My intention was to use

    $vclist = 'server1', 'Server2', 'server' 3

    {foreach ($vc to $vclist)

    to connect-viserver $vc

    }

    So to do the job

    {foreach ($connection in $defaultVIServers)

    to connect-viserver-session $connection. SessionId

    {do work}

    }

    It did not work. A command such as get - vm were withdrawing from all 3 of VC.   Should I rewrite with a connect then disconnect?

    How to work with different connections is implemented a little differently.

    First of all, make sure that you configure PowerCLI to work in multi mode.

    $config = Get-PowerCLIConfiguration if($config.DefaultVIServerMode -eq "Single"){
        Set-PowerCLIConfiguration -DefaultVIServerMode Multiple}
    

    Open your vCenter or ESX (i) connections

    $vclist = "server1","server2","server3" foreach ($vc in $vclist){
         connect-viserver $vc}
    

    When you run a cmdlet against a use specific vCenter the -Server setting

    Get-VM -Server $defaultVIServers[0]
    

    If you omit the - server parameter and you run in multi mode, the cmdlet will run against all connections.

    The $defaultVIServers variable contains all the connections.

  • How to operate with several connections open for VCs (Connect-VIServer).

    Hello:

    I know that I can open multiple connections to VCs (Connect-VIServer), but do not really understand how to run with them...

    How can I speak in VC1 for a single operation and after that VC2 to another without closing the connection in VC1?  I might need to do this several times in my script...

    Any help and simple example will be really appreciated.

    Thank you

    qwert

    The cmdlet Connect-VIServer of PowerCLU 4u1 leave takes supported several open sessions.

    The sessions are stored in a table called $defaultVIServers.

    If you need restore an open session, you can use the entry for this server in the array and then use the SessionId property to make this session open session / by default (which is stored in the variable $defaultVIServer).

    Something like that

    Connect-VIServer -Server VC1
    Connect-VIServer -Server VC2
    # Show the sessions and their properties
    $defaultVIServers | Select *
    
    # Open the session to VC1
    Connect-VIServer -Session $defaultVIServers[0].SessionId
    
    # Open the session to VC2
    Connect-VIServer -Session $defaultVIServers[1].SessionId
    
    # The open session
    $defaultVIServer
    
  • Need to export Connect-VIServer drive and import it for later use

    Hello

    I'm trying to export Connect-VIServer on disk:

    $vcenterconnection = Connect-VIServer-Server vcenterserver

    $vcenterconnection | Export-Clixml-path C:\TEMP\session.xml

    I want to import the session exported to a new process of powershell that it connects faster to vcentern later:

    $ImportedSession = import-Clixml-path C:\TEMP\session.xml

    I can access all the properties of the imported object that before exporting it.

    $NewConnection = Connect-VIServer-Session $ImportedSession - Server vcenterserver

    It does not work:

    SE connect-VIServer: 23.11.2015 14:11:17SE connect-VIServerUnable to connect to the VI server: https://vcenterserver/SDK using session Id: "vcenterserver"On line: 1 char: 22

    Is there a way to export a vCenter session on the disc to reuse it in a new process of powershell?

    Thank you

    For the parameter of the cmdlet Connect-ViServer Session you must pass a Guid.

    Your current logon, you can retrieve this Guid

    Global $: DefaultVIServer | Select - ExpandProperty SessionId

    Note that when you want to reconnect, that these sessions have a time-out value.

    They don't stay open forever (normally).

  • to connect-viserver to several viservers @ simultaneously fails

    Hello

    because they are forced to leave related modes, we cannot use the connect-viserver - alllinked more...

    If google told me to use connect-viserver vc1, vc2

    You can check this, if you check the $global value: DefaulViServers

    In my case, there is only the vc2 listed, even if the connection to the two vcenters works very well...

    Version is 5.1 Release 1 PowerCLI

    Why?

    THX in advance

    Chakoe

    Add the parameter Scope

    Game-PowerCLIConfiguration - multiple DefaultVIServerMode - Scope Session

  • SE connect-viserver to remain persistent through different functions.

    For some reason, I can't get my Virtual Center connection to remain persistent so I can use in a different function when the connection is in service.  If I perform other tasks in the same function as the "Connect-VIServer" then they work without any problem.  I know I must be missing something.  Two examples of code base of what I'm trying to do.

    Code

    function connectVC

    {

    SE connect-VIServer $vcserver

    }

    function showdatacenters

    {

    Get-data center

    }

    Add-PSsnapin VMware.VimAutomation.Core

    Initialize - VIToolkitEnvironment.ps1

    $vcserver = read-host 'Target VirtualCenter Server'

    connectVC

    showdatacenters

    Error

    2009-05-07 15:51:22 Get-data center you are not currently connected to all servers. Sign in first using Connect-VIServer or one of his pseudonyms.

    To: tank line: 7:15

    + Get-Data Center & lt; & lt; & lt; & lt;

    Code

    function connectVC

    {

    $objVC = to connect-VIServer $vcserver

    }

    function showdatacenters

    {

    $objVC.------

    Get-data center

    }

    Add-PSsnapin VMware.VimAutomation.Core

    Initialize - VIToolkitEnvironment.ps1

    $vcserver = read-host 'Target VirtualCenter Server'

    connectVC

    showdatacenters

    Error

    The argument cannot be null or empty.

    To: tank line: 7:24

    + $objVC.

    Get-data center & lt; & lt; & lt; & lt;

    Is the reason that you see, it is because of the "scope" in which you connect to the VC server.

    While in a function (connectVC in your first example), local variables you create are lost when you leave the service.

    There are 2 solutions

    1) connect to the VC server outside of a function, the scope of the script called

    
    function showdatacenters
    {
    Get-Datacenter
    }
    
    Add-PSsnapin VMware.VimAutomation.Core
    Initialize-VIToolkitEnvironment.ps1
    
    $vcserver = read-host "Target VirtualCenter Server"
    Connect-VIServer $vcserver
    showdatacenters
    

    (2) store the ViServerImpl object (which is returned by the cmdlet Connect-VIServer) outside the function and pass on all other VITK cmdlets.

    
    function connectVC
    {
    $global:vc = Connect-VIServer $vcserver
    }
    function showdatacenters
    {
    Get-Datacenter -Server $global:vc
    }
    
    Add-PSsnapin VMware.VimAutomation.Core
    Initialize-VIToolkitEnvironment.ps1
    
    $vcserver = read-host "Target VirtualCenter Server"
    connectVC
    showdatacenters
    

    If you want to learn more about scope modifiers (like the World Cup, I used 2)), take a look at this.

  • Save the password on the Client VPN with PIX

    I'm running a PIX 515 6.1 (2) configured for a small number of VPN clients. I want VPN clients to automatically remember the password of login for users do not have to enter it each time (we have an application which periodically autoconnexions).

    While it is a configurable option with concentrators 3000 series, it seems not be configurable with the PIX.

    The only work around, I can find is to make the connection file (.pcf) read-only and set SaveUserPassword = 1. The problem

    which is the password, and then must be stored in clear text in the file and it becomes inconvenient for the user to change their password.

    Does anyone know if the command exists on the PIX from the VPN client to save the connection password?

    Thank you

    Misha

    The command to do this is not currently available on the PIX. He has just been included in the IOS EZVPN server functionality, but have not heard of anything anyone yet as to if it will be included in the PIX.

    If you want this feature, do not hesitate to contact your account manager and have them grow for him, the more customers requesting a new feature faster he gets.

  • Extraction of SSL with initial Connect-VIServer

    Sorry if this has already been asked before, but I was not able to find it by searching online or in the forums.

    When you start a connection to another host of VC/ESXi, there is some information about x 509 certificate as shown below.

    * The X 509 chain could not be achieved with the root certificate.

    Certificate: [subject]

    C = US, CN = vcenter60 - 4.primp - industries.com

    [Issuer]

    O = vcenter60 - 4.primp - industries.com, C = US, DC = local, DC = vghetto, CN = CA

    [Number]

    00D9B9AE28CFD6CF4D

    [Not before]

    02/08/2015-09:19:14

    [Not After]

    02/02/2025 09:19:13

    [Imprint]

    B846B9F36C1D978CEDA0199294E61B4515656396

    I would like to enter the thumbprint SSL "B846B9F36C1D978CEDA0199294E61B4515656396"? I looked online and even asked some people but never able to retrieve this property by using PowerShell/PowerCLI. I can do it easily on one other system Windows with openssl (http://www.virtuallyghetto.com/2012/04/extracting-ssl-thumbprint-from-esxi.html), but wanted to see if there is a way without going through relays on the external packaging and since it is available as part of the connect-VIServer, I thought it must be possible but my PowerCLI-Fu isn't quite at the height as the others , figure so I ask. If it is indeed removable, which I guess it is then a bonus would be to format and so I have a variable that looks like: B8:46:B9:F3:6 C: 1 d: 97:8 C: ED: A0:19:92:94:E6:1 B: 45:15:65:63:96


    Luc Merci in advance

    Function Test-WebServerSSL {
    # Function original location: http://en-us.sysadmins.lv/Lists/Posts/Post.aspx?List=332991f0-bfed-4143-9eea-f521167d287c&ID=60
    [CmdletBinding()]
        param(
            [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
            [string]$URL,
            [Parameter(Position = 1)]
            [ValidateRange(1,65535)]
            [int]$Port = 443,
            [Parameter(Position = 2)]
            [Net.WebProxy]$Proxy,
            [Parameter(Position = 3)]
            [int]$Timeout = 15000,
            [switch]$UseUserContext
        )
    Add-Type @"
    using System;
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    namespace PKI {
        namespace Web {
            public class WebSSL {
                public Uri OriginalURi;
                public Uri ReturnedURi;
                public X509Certificate2 Certificate;
                //public X500DistinguishedName Issuer;
                //public X500DistinguishedName Subject;
                public string Issuer;
                public string Subject;
                public string[] SubjectAlternativeNames;
                public bool CertificateIsValid;
                //public X509ChainStatus[] ErrorInformation;
                public string[] ErrorInformation;
                public HttpWebResponse Response;
            }
        }
    }
    "@
        $ConnectString = "https://$url`:$port"
        $WebRequest = [Net.WebRequest]::Create($ConnectString)
        $WebRequest.Proxy = $Proxy
        $WebRequest.Credentials = $null
        $WebRequest.Timeout = $Timeout
        $WebRequest.AllowAutoRedirect = $true
        [Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
        try {$Response = $WebRequest.GetResponse()}
        catch {}
        if ($WebRequest.ServicePoint.Certificate -ne $null) {
            $Cert = [Security.Cryptography.X509Certificates.X509Certificate2]$WebRequest.ServicePoint.Certificate.Handle
            try {$SAN = ($Cert.Extensions | Where-Object {$_.Oid.Value -eq "2.5.29.17"}).Format(0) -split ", "}
            catch {$SAN = $null}
            $chain = New-Object Security.Cryptography.X509Certificates.X509Chain -ArgumentList (!$UseUserContext)
            [void]$chain.ChainPolicy.ApplicationPolicy.Add("1.3.6.1.5.5.7.3.1")
            $Status = $chain.Build($Cert)
            New-Object PKI.Web.WebSSL -Property @{
                OriginalUri = $ConnectString;
                ReturnedUri = $Response.ResponseUri;
                Certificate = $WebRequest.ServicePoint.Certificate;
                Issuer = $WebRequest.ServicePoint.Certificate.Issuer;
                Subject = $WebRequest.ServicePoint.Certificate.Subject;
                SubjectAlternativeNames = $SAN;
                CertificateIsValid = $Status;
                Response = $Response;
                ErrorInformation = $chain.ChainStatus | ForEach-Object {$_.Status}
            }
            $chain.Reset()
            [Net.ServicePointManager]::ServerCertificateValidationCallback = $null
        } else {
            Write-Error $Error[0]
        }
    }
    
    $cert = Test-WebServerSSL MYVC
    $cert.Certificate.Thumbprint
    
  • Complete the VI Client with PowerCLI Script idle Sessions

    Hello gurus PowerCLI

    I searched the net for a script PowerCLI that would end all the VI client sessions that have been inactive for x period of time.  I found a post on the forums of VMware (http://communities.vmware.com/message/914858?z=zI0r8n) but had no luck with it.  I also found a script created by A.Mikkelsen, to http://www.amikkelsen.com/?p=384 , but that one does not work either.

    Here's the actual script by A.Mikkelsen that is based on code by LucD in the forum mentioned previously.

    BEGINNING

    ##################################################################################
    # The script terminates all sessions if idle idle user for more than xx #.
    #                             #
    # Created by: Anders Mikkelsen, 2010 #.
    ##################################################################################
    Claire
    # Add - PSSnapin VMware.VimAutomation.Core

    # $server = "vcenter server.
    # $user = "vcenter username.
    # $pwd = "password of vcenter.

    # Add 1 extra hour when, due to the difference of timestamp between MSSQL and Windows.
    # slow down time 5 hours = 360
    # 10 hours slowed = 660
    $intOlderThan = 60

    # Connect-VIServer $server - user $user-password $pwd
    # Connect-VIServer $server

    $svcRef = new-object VMware.Vim.ManagedObjectReference
    $svcRef.Type = 'ServiceInstance.
    $svcRef.Value = 'ServiceInstance.
    $serviceInstance = get-views $svcRef

    $sessMgr = get-view $serviceInstance.Content.sessionManager
    $oldSessions = @)
    {foreach ($sess in $sessMgr.SessionList)}
    If (($sess.)) (LastActiveTime) .addminutes ($intOlderThan) - lt (Get-Date)) {}
    $oldSessions += $sess. Key
    #write "$($sess.)". User name)'
    }
    }

    # Session terminal that are inactive for more than approved ($intOlderThan)
    $sessMgr.TerminateSession ($oldSessions)

    Disconnect-VIServer *-confirm: $false

    END

    The error message I get is:

    BEGINNING

    Exception calling 'TerminateSession' with '1' or the arguments: "it was not correct to specified parameters.

    "

    D:\Scripts\vc_terminate_idle_sessions.ps1:36 char: 26

    + $sessMgr.TerminateSession < < < < ($oldSessions)

    + CategoryInfo: NotSpecified: (:)) [], MethodInvocationException)

    + FullyQualifiedErrorId: DotNetMethodException

    END

    I should mention that my knowledge of PowerCLI is almost nothing, so any help in tweaking this script to make it work with PowerCLI 5.1 Release 2 and VC 5 U2 would be much appreciated.

    The error is caused by the fact that you are trying to kill your own session (if it was started long time ago).

    Apparently in vSphere 5. they included a security mechanism integrated to avoid this.

    You can take this by adding a simple test.

    ## max number of idle minutes for sessions to keep$intOlderThan = 60$serviceInstance = Get-View 'ServiceInstance'## get the session manager object$sessMgr = Get-View $serviceInstance.Content.sessionManager## array to hold info about stale sessions$oldSessions = @()foreach ($sess in $sessMgr.SessionList){    if (($sess.LastActiveTime).addminutes($intOlderThan) -lt (Get-Date) -and          $sess.Key -ne $sessMgr.CurrentSession.Key){        $oldSessions += $sess.Key    } ## end if} ## end foreach
    
    ## if there are any old sessions, terminate them; else, just write message to the Warning streamif (($oldSessions | Measure-Object).Count -gt 0) {    ## Terminate sessions than are idle for longer than approved ($intOlderThan)    $sessMgr.TerminateSession($oldSessions)} ## end ifelse {Write-Warning "No sessions that have been idle for more than '$intOlderThan' minutes; no action taken"}
    

Maybe you are looking for