File size: 8,206 Bytes
8c763fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Remoting;

using System.Management.Automation.Runspaces;
using System.Diagnostics.CodeAnalysis;

using Dbg = System.Management.Automation.Diagnostics;

namespace Microsoft.PowerShell.Commands
{
    /// <summary>
    /// This cmdlet stops the runspace and frees the resources associated with
    /// that runspace. If any execution is in process in that runspace, it is
    /// stopped. Also, the runspace is removed from the global cache.
    ///
    /// This cmdlet can be used in the following ways:
    ///
    /// Remove the runspace specified
    ///     $runspace = New-PSSession
    ///     Remove-PSSession -remoterunspaceinfo $runspace
    ///
    /// Remove the runspace specified (no need for a parameter name)
    ///     $runspace = New-PSSession
    ///     Remove-PSSession $runspace.
    /// </summary>
    [Cmdlet(VerbsCommon.Remove, "PSSession", SupportsShouldProcess = true,
            DefaultParameterSetName = RemovePSSessionCommand.IdParameterSet,
            HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096963", RemotingCapability = RemotingCapability.OwnedByCommand)]
    public class RemovePSSessionCommand : PSRunspaceCmdlet
    {
        #region Parameters

        /// <summary>
        /// Specifies the PSSession objects which need to be
        /// removed.
        /// </summary>
        [Parameter(Mandatory = true,
                   Position = 0,
                   ValueFromPipeline = true,
                   ValueFromPipelineByPropertyName = true,
                   ParameterSetName = RemovePSSessionCommand.SessionParameterSet)]
        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
        public PSSession[] Session { get; set; }

        /// <summary>
        /// ID of target container.
        /// </summary>
        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
            Justification = "This is by spec.")]
        [Parameter(Mandatory = true,
                   ValueFromPipelineByPropertyName = true,
                   ParameterSetName = PSRunspaceCmdlet.ContainerIdParameterSet)]
        [ValidateNotNullOrEmpty]
        public override string[] ContainerId { get; set; }

        /// <summary>
        /// Guid of target virtual machine.
        /// </summary>
        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
            Justification = "This is by spec.")]
        [Parameter(Mandatory = true,
                   ValueFromPipelineByPropertyName = true,
                   ParameterSetName = PSRunspaceCmdlet.VMIdParameterSet)]
        [ValidateNotNullOrEmpty]
        [Alias("VMGuid")]
        public override Guid[] VMId { get; set; }

        /// <summary>
        /// Name of target virtual machine.
        /// </summary>
        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
            Justification = "This is by spec.")]
        [Parameter(Mandatory = true,
                   ValueFromPipelineByPropertyName = true,
                   ParameterSetName = PSRunspaceCmdlet.VMNameParameterSet)]
        [ValidateNotNullOrEmpty]
        public override string[] VMName { get; set; }

        #endregion Parameters

        #region Overrides

        /// <summary>
        /// Do the following actions:
        ///     1. If runspace is in opened state,
        ///             a. stop any execution in process in the runspace
        ///             b. close the runspace
        ///     2. Remove the runspace from the global cache.
        /// </summary>
        protected override void ProcessRecord()
        {
            ICollection<PSSession> toRemove = null;

            switch (ParameterSetName)
            {
                case RemovePSSessionCommand.ComputerNameParameterSet:
                case RemovePSSessionCommand.NameParameterSet:
                case RemovePSSessionCommand.InstanceIdParameterSet:
                case RemovePSSessionCommand.IdParameterSet:
                case RemovePSSessionCommand.ContainerIdParameterSet:
                case RemovePSSessionCommand.VMIdParameterSet:
                case RemovePSSessionCommand.VMNameParameterSet:
                    {
                        Dictionary<Guid, PSSession> matches = GetMatchingRunspaces(false, true);

                        toRemove = matches.Values;
                    }

                    break;
                case RemovePSSessionCommand.SessionParameterSet:
                    {
                        toRemove = Session;
                    }

                    break;
                default:
                    Diagnostics.Assert(false, "Invalid Parameter Set");
                    toRemove = new Collection<PSSession>(); // initialize toRemove to turn off PREfast warning about it being null
                    break;
            }

            foreach (PSSession remoteRunspaceInfo in toRemove)
            {
                RemoteRunspace remoteRunspace = (RemoteRunspace)remoteRunspaceInfo.Runspace;

                if (ShouldProcess(remoteRunspace.ConnectionInfo.ComputerName, "Remove"))
                {
                    // If the remote runspace is in a disconnected state, first try to connect it so that
                    // it can be removed from both the client and server.
                    if (remoteRunspaceInfo.Runspace.RunspaceStateInfo.State == RunspaceState.Disconnected)
                    {
                        bool ConnectSucceeded;

                        try
                        {
                            remoteRunspaceInfo.Runspace.Connect();
                            ConnectSucceeded = true;
                        }
                        catch (InvalidRunspaceStateException)
                        {
                            ConnectSucceeded = false;
                        }
                        catch (PSRemotingTransportException)
                        {
                            ConnectSucceeded = false;
                        }

                        if (!ConnectSucceeded)
                        {
                            // Write error notification letting user know that session cannot be removed
                            // from server due to lack of connection.
                            string msg = System.Management.Automation.Internal.StringUtil.Format(
                                RemotingErrorIdStrings.RemoveRunspaceNotConnected, remoteRunspace.PSSessionName);
                            Exception reason = new RuntimeException(msg);
                            ErrorRecord errorRecord = new ErrorRecord(reason, "RemoveSessionCannotConnectToServer",
                                ErrorCategory.InvalidOperation, remoteRunspace);
                            WriteError(errorRecord);

                            // Continue removing the runspace from the client.
                        }
                    }

                    try
                    {
                        // Dispose internally calls Close() and Close()
                        // is a no-op if the state is not Opened, so just
                        // dispose the runspace
                        remoteRunspace.Dispose();
                    }
                    catch (PSRemotingTransportException)
                    {
                        // just ignore, there is some transport error
                        // on Close()
                    }

                    try
                    {
                        // Remove the runspace from the repository
                        this.RunspaceRepository.Remove(remoteRunspaceInfo);
                    }
                    catch (ArgumentException)
                    {
                        // just ignore, the runspace may already have
                        // been removed
                    }
                }
            }
        }

        #endregion Overrides
    }
}