Is Remove-CimSession necessary?

This topic contains 4 replies, has 4 voices, and was last updated by  Will Anderson 11 months, 3 weeks ago.

  • Author
  • #75733

    Kevin Greer

    If I create a New-CimSessions with one or more computers, execute my code, should I follow up with Remove-CimSession or is that not necessary? I'm looking for best practice to apply to my functions.

  • #75734

    Frank Tucker

    Generally you would want the function to support a list of computers. Connecting and then disconnecting after getting or setting something from the computer/s. Like a Try, Catch, Finnally statement.... yes I think in general remove the session once task is complete

  • #75763

    Richard Siddaway

    In absolute terms its not necessary to use Remove-CimSession. When you close the PowerShell console, or ISE, your CIM session will be destroyed. In terms of best practice each CIM session consumes resources. Its better to remove them when you've finished with them so that the resources can be put to other uses.

    if I create a CIM session in a script I normally use Remove-CimSession at the end of the script to tidy up the environment. You should also do the same with remoting sessions. Once you're sure you're finished using them – get rid of them

  • #75775

    Kevin Greer

    Thank you for your replies.
    I'll add remove-CimSession to my scripts. Does this also apply to Remove-CimInstance if I run Get-CimInstance? Typically I would always use New-CimSession with a New-CimSessionOption explicitly set to either WSMAN or DCOM (for backwards compatibility). So if I have created a session, then run get-CimInstance -session, should I follow up with Remove-CimInstance then Remove-CimSession?

  • #75791

    Will Anderson

    No. Remove-CimInstance removes the object from CIM. Example:

    PS C:\WINDOWS\system32> (Get-CimInstance -ClassName Win32_Process).where({$PSItem.Name -eq 'notepad.exe'})
    ProcessId Name        HandleCount WorkingSetSize VirtualSize  
    --------- ----        ----------- -------------- -----------  
    15348     notepad.exe 273         16293888       2199167918080
    5904      notepad.exe 606         40423424       2199289872384

    You can see with Get-CimInstance, I've got two notepad sessions open. So if I do this:

    PS C:\WINDOWS\system32> $Process = (Get-CimInstance -ClassName Win32_Process).where({$PSItem.Name -eq 'notepad.exe'})
    PS C:\WINDOWS\system32> $Process | Remove-CimInstance
    PS C:\WINDOWS\system32> (Get-CimInstance -ClassName Win32_Process).where({$PSItem.Name -eq 'notepad.exe'})

    You can see they are no longer there.

You must be logged in to reply to this topic.