-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWarmUp.ps1
321 lines (298 loc) · 15.1 KB
/
WarmUp.ps1
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
param(
[string] $Mode
)
Add-Type -Language CSharp -TypeDefinition @'
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Collections.Generic;
namespace Rds {
public static class Sessions {
[DllImport("wtsapi32.dll")]
static extern IntPtr WTSOpenServer([MarshalAs(UnmanagedType.LPStr)] String pServerName);
[DllImport("wtsapi32.dll")]
static extern void WTSCloseServer(IntPtr hServer);
[DllImport("wtsapi32.dll")]
static extern Int32 WTSEnumerateSessions(IntPtr hServer,
[MarshalAs(UnmanagedType.U4)] Int32 Reserved,
[MarshalAs(UnmanagedType.U4)] Int32 Version, ref IntPtr ppSessionInfo,
[MarshalAs(UnmanagedType.U4)] ref Int32 pCount);
[DllImport("wtsapi32.dll")]
static extern void WTSFreeMemory(IntPtr pMemory);
[DllImport("Wtsapi32.dll")]
static extern bool WTSQuerySessionInformation(System.IntPtr hServer, int sessionId, WTS_INFO_CLASS wtsInfoClass, out System.IntPtr ppBuffer, out uint pBytesReturned);
[DllImport("Wtsapi32.dll")]
static extern bool WTSLogoffSession(System.IntPtr hServer, int sessionId, bool wait);
[StructLayout(LayoutKind.Sequential)]
private struct WTS_SESSION_INFO {
public Int32 SessionID;
[MarshalAs(UnmanagedType.LPStr)]
public String pWinStationName;
public WtsConnect State;
}
public enum WTS_INFO_CLASS {
WTSInitialProgram,
WTSApplicationName,
WTSWorkingDirectory,
WTSOEMId,
WTSSessionId,
WTSUserName,
WTSWinStationName,
WTSDomainName,
WTSConnectState,
WTSClientBuildNumber,
WTSClientName,
WTSClientDirectory,
WTSClientProductId,
WTSClientHardwareId,
WTSClientAddress,
WTSClientDisplay,
WTSClientProtocolType,
WTSIdleTime,
WTSLogonTime,
WTSIncomingBytes,
WTSOutgoingBytes,
WTSIncomingFrames,
WTSOutgoingFrames,
WTSClientInfo,
WTSSessionInfo,
WTSSessionInfoEx,
WTSConfigInfo,
WTSValidationInfo,
WTSSessionAddressV4,
WTSIsRemoteSession
}
public enum WtsConnect {
Active,
Connected,
ConnectQuery,
Shadow,
Disconnected,
Idle,
Listen,
Reset,
Down,
Init
}
public class WtsSessionInformation {
public string InitialProgram;
public string ApplicationName;
public string WorkingDirectory;
public string OEMId;
public int SessionId;
public string UserName;
public string WinStationName;
public string DomainName;
public WtsConnect ConnectState;
public string ConnectStateString;
public int ClientBuildNumber;
public string ClientName;
public string ClientDirectory;
}
public static IntPtr OpenServer(String name) {
IntPtr server = WTSOpenServer(name);
return server;
}
public static void CloseServer(IntPtr serverHandle) {
WTSCloseServer(serverHandle);
}
public static bool LogoffSession(int id, bool waitForLogoff) {
IntPtr serverHandle = IntPtr.Zero;
serverHandle = OpenServer(Environment.MachineName);
IntPtr sessionInfoPtr = IntPtr.Zero;
try {
return WTSLogoffSession(serverHandle, id, waitForLogoff);
} catch (Exception e) {
Console.WriteLine("Exception querying session information: " + e.ToString());
} finally {
WTSFreeMemory(sessionInfoPtr);
CloseServer(serverHandle);
}
return false;
}
public static WtsSessionInformation GetSession(string userName) {
var sessions=GetSessions();
return sessions.FirstOrDefault(n=>string.Equals(n.UserName, userName, StringComparison.InvariantCultureIgnoreCase));
}
public static List < WtsSessionInformation > GetSessions() {
var wtsList = new List < WtsSessionInformation > ();
IntPtr serverHandle = IntPtr.Zero;
serverHandle = OpenServer(Environment.MachineName);
IntPtr sessionInfoPtr = IntPtr.Zero;
try {
IntPtr sPtr = IntPtr.Zero;
Int32 sessionCount = 0;
Int32 retVal = WTSEnumerateSessions(serverHandle, 0, 1, ref sessionInfoPtr, ref sessionCount);
Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO));
Int64 currentSession = (long) sessionInfoPtr;
uint bytes = 0;
if (retVal != 0) {
for (int i = 0; i < sessionCount; i++) {
WTS_SESSION_INFO si = (WTS_SESSION_INFO) Marshal.PtrToStructure((System.IntPtr) currentSession, typeof(WTS_SESSION_INFO));
currentSession += dataSize;
var wts = new WtsSessionInformation();
if (WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSUserName, out sPtr, out bytes)) {
wts.UserName = Marshal.PtrToStringAnsi(sPtr);
WTSFreeMemory(sPtr);
}
if (WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSDomainName, out sPtr, out bytes)) {
wts.DomainName = Marshal.PtrToStringAnsi(sPtr);
WTSFreeMemory(sPtr);
}
if (WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSWinStationName, out sPtr, out bytes)) {
wts.WinStationName = Marshal.PtrToStringAnsi(sPtr);
WTSFreeMemory(sPtr);
}
if (WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSSessionId, out sPtr, out bytes)) {
wts.SessionId = Marshal.ReadInt32(sPtr);
WTSFreeMemory(sPtr);
}
if (WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSInitialProgram, out sPtr, out bytes)) {
wts.InitialProgram = Marshal.PtrToStringAnsi(sPtr);
WTSFreeMemory(sPtr);
}
if (WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSApplicationName, out sPtr, out bytes)) {
wts.ApplicationName = Marshal.PtrToStringAnsi(sPtr);
WTSFreeMemory(sPtr);
}
if (WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSWorkingDirectory, out sPtr, out bytes)) {
wts.WorkingDirectory = Marshal.PtrToStringAnsi(sPtr);
WTSFreeMemory(sPtr);
}
if (WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSConnectState, out sPtr, out bytes)) {
wts.ConnectState = (WtsConnect) Marshal.ReadInt32(sPtr);
wts.ConnectStateString = wts.ConnectState.ToString();
WTSFreeMemory(sPtr);
}
if (WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSClientBuildNumber, out sPtr, out bytes)) {
wts.ClientBuildNumber = Marshal.ReadInt32(sPtr);
WTSFreeMemory(sPtr);
}
if (WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSClientName, out sPtr, out bytes)) {
wts.ClientName = Marshal.PtrToStringAnsi(sPtr);
WTSFreeMemory(sPtr);
}
if (WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSClientDirectory, out sPtr, out bytes)) {
wts.ClientDirectory = Marshal.PtrToStringAnsi(sPtr);
WTSFreeMemory(sPtr);
}
if (!string.IsNullOrEmpty(wts.UserName)) wtsList.Add(wts);
}
}
return wtsList;
} catch (Exception e) {
Console.WriteLine("Exception querying session information: " + e.ToString());
} finally {
WTSFreeMemory(sessionInfoPtr);
CloseServer(serverHandle);
}
return null;
}
}
}
'@
$LogDir="$($env:windir)\system32\LogFiles"
$LogFile="$($LogDir)\AVD.WarmUp.log"
function LogWriter($message) {
$message = "$(Get-Date ([datetime]::UtcNow) -Format "o") $message"
write-host($message)
if ([System.IO.Directory]::Exists($LogDir)) { try { write-output($message) | Out-File $LogFile -Append } catch {} }
}
if ($mode -like "install") {
LogWriter("Copy script to windir")
Copy-Item "$($MyInvocation.InvocationName)" -Destination ($env:windir + "\WarmUp.ps1")
LogWriter("Creating schedule task to run the script at startup")
$action = New-ScheduledTaskAction -Execute "$env:windir\System32\WindowsPowerShell\v1.0\Powershell.exe" -Argument "-executionPolicy Unrestricted -File `"$($env:windir)\WarmUp.ps1`""
$trigger = New-ScheduledTaskTrigger -AtStartup
$principal = New-ScheduledTaskPrincipal 'NT Authority\SYSTEM' -RunLevel Highest
$settingsSet = New-ScheduledTaskSettingsSet
$task = New-ScheduledTask -Action $action -Principal $principal -Trigger $trigger -Settings $settingsSet
Register-ScheduledTask -TaskName 'ITPC-AVD-WarmUpUser' -InputObject $task -ErrorAction Ignore
Enable-ScheduledTask -TaskName 'ITPC-AVD-WarmUpUser'
} else {
$localUserName = "warmup-user"
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#' #$%^&*()-_=+[]{}|;:,.<>?'
$localUserPWPlain = -join (1..32 | ForEach-Object { Get-Random -InputObject $characters.ToCharArray() }) +"!@1aA"
$localUserPW = ConvertTo-SecureString -String $localUserPWPlain -AsPlainText -Force # https://www.sharepointdiary.com/2020/04/powershell-generate-random-password.html
# Store default configuration
LogWriter("Getting local configuration to use saved credentials for the warmup user")
$oldAuthenticationLevelOverride=$null
if (Test-Path "HKCU:\Software\Microsoft\Terminal Server Client") {
$oldAuthenticationLevelOverride = Get-ItemProperty -Path "HKCU:\Software\Microsoft\Terminal Server Client" -Name "AuthenticationLevelOverride" -ErrorAction SilentlyContinue
} else {
New-Item -Path "HKCU:\Software\Microsoft\Terminal Server Client" -Force -ErrorAction SilentlyContinue
}
if ($oldAuthenticationLevelOverride -eq $null) {$oldAuthenticationLevelOverride = 99} else {$oldAuthenticationLevelOverride = $oldAuthenticationLevelOverride.AuthenticationLevelOverride}
try {
LogWriter("Modifying configuration to login warmup user with stored credentials")
# Set temporary configuration to allow user logins
New-ItemProperty -Path "HKCU:\Software\Microsoft\Terminal Server Client" -Name "AuthenticationLevelOverride" -Value 0 -Force
New-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows NT\Terminal Services" -Name "DisablePasswordSaving" -Value 1 -Force
# Prepare temporary local user
if ((Get-LocalUser -Name $localUserName -ErrorAction SilentlyContinue) -ne $null) {
LogWriter("Removing existing local warmup user")
Remove-LocalUser -Name $localUserName
}
LogWriter("Adding local user")
$localUser = New-LocalUser -Name $localUserName -Password $localUserPW -AccountExpires (Get-Date).AddMinutes(10) -PasswordNeverExpires -UserMayNotChangePassword
# Add user to remote desktop group
LogWriter("Adding user to the remote desktop group")
Add-LocalGroupMember -SID "S-1-5-32-555" -Member $localUserName -ErrorAction SilentlyContinue
# Login user
LogWriter("Adding credentials of the warmup user to the key store")
cmdkey /generic:TERMSRV/localhost /user:"$($env:Computername)\$($localUserName)" /pass:$localUserPWPlain
$startTime=Get-Date
$i=0
do {
LogWriter("Login in user warmup user")
if ($mstsc) {
$mstsc.Kill()
Start-Sleep -Seconds 6
}
$mstsc = Start-Process -PassThru -FilePath "mstsc.exe" -ArgumentList "/v:localhost"
# Wait for the user to login
LogWriter("Waiting a few seconds")
Start-Sleep -Seconds 20
$i++
} while ([Rds.Sessions]::GetSession($localUserName) -eq $null -and $i -le 10)
# Remove credentials
LogWriter("Removing credentials from the key store")
cmdkey /delete:TERMSRV/localhost
# Check, if user is connected
$session=[Rds.Sessions]::GetSession($localUserName)
if ($session -eq $null) {
LogWriter("Warning: Warm-up user is not connected. So, the workaround is not working for some reasons")
} else {
# Let the user for a while in the session and then logoff
LogWriter("Let the user logged in for a while")
Start-Sleep -Seconds 300
LogWriter("Logoff user")
[Rds.Sessions]::LogoffSession($session.SessionId, $true)
# Remove profile of the user
try {
LogWriter("Delete profile of the warm-up user")
@(Get-CimInstance -Class Win32_UserProfile | Where-Object { $_.Loaded -eq $false -and ($_.LocalPath.split('\')[-1] -like $localUserName -or $_.LocalPath.split('\')[-1] -like "$($localUserName).*")}) | Remove-CimInstance
} catch {
LogWriter("Error: Cannot delete the profile of the warmup user: $_")
}
}
LogWriter("Terminate mstsc.exe, if running")
$mstsc.Kill()
} catch {
LogWriter("Error: $_")
} finally {
# Remove user
LogWriter("Disable and remove user")
Remove-LocalGroupMember -SID "S-1-5-32-555" -Member $localUserName
Disable-LocalUser -Name $localUserName -ErrorAction SilentlyContinue
Remove-LocalUser -Name $localUserName -ErrorAction SilentlyContinue
# Restore default configuration
LogWriter("Restoring local configuration")
if ($oldAuthenticationLevelOverride -eq 99) {
Remove-ItemProperty "HKCU:\Software\Microsoft\Terminal Server Client" -Name "AuthenticationLevelOverride" -Force
} else {
New-ItemProperty -Path "HKCU:\Software\Microsoft\Terminal Server Client" -Name "AuthenticationLevelOverride" -Value $oldAuthenticationLevelOverride -Force
}
}
LogWriter("Done")
}