Skip to content

Commit 60a5ef1

Browse files
committed
clear-history
1 parent 7e72904 commit 60a5ef1

File tree

6 files changed

+171
-48
lines changed

6 files changed

+171
-48
lines changed

Initialize-Machine.ps1

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -627,6 +627,11 @@ Begin
627627
$0 = 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\TaskbarDeveloperSettings'
628628
if (!(Test-Path $0)) { New-Item -Path $0 | Out-Null }
629629
Set-ItemProperty $0 -Name 'TaskbarEndTask' -Type DWord -Value 1
630+
631+
# show seconds in time
632+
$0 = 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced'
633+
if (!(Test-Path $0)) { New-Item -Path $0 | Out-Null }
634+
Set-ItemProperty $0 -Name 'ShowSecondsInSystemClock' -Type DWord -Value 1
630635

631636
$0 = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\Explorer'
632637
if (!(Test-Path $0)) { New-Item -Path $0 | Out-Null }

Microsoft.PowerShell_profile.ps1

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ function Start-Wilma
6767
}
6868

6969
New-Alias hx Get-HistoryEx
70+
New-Alias Clear-History Clear-HistoryEx
7071

7172
# Docker helpers
7273
New-Alias doc Remove-DockerTrash
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<#
2+
Clears the PowerShell history file, retaining the specified number of most
3+
recent commands.
4+
5+
.PARAMETER Keep
6+
Specifies the number of commands to keep in the history file, where 0 would
7+
clear all history. The default is to keep the 300 most recent commands.
8+
#>
9+
10+
[CmdletBinding(SupportsShouldProcess = $true)]
11+
12+
param(
13+
[int] $Keep = 300
14+
)
15+
16+
Begin
17+
{
18+
}
19+
Process
20+
{
21+
$script:savePath = (Get-PSReadlineOption).HistorySavePath
22+
$cache = Join-Path ([IO.Path]::GetTempPath()) ([IO.Path]::GetRandomFileName())
23+
Get-Content $savePath -Tail $Keep | Out-File $cache
24+
Copy-Item $cache $savePath -Force
25+
Remove-Item $cache -Force
26+
}

Modules/Scripts/Get-HistoryEx.ps1

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,15 @@
1+
<#
2+
.SYNOPSIS
3+
Get and search the full history command line history.
4+
5+
.PARAMETER Arg1
6+
Interchangeable with Arg2, specifies either the number of most recent items to
7+
return or a string used to search the history.
8+
9+
.PARAMETER Arg2
10+
Interchangeable with Arg1, specifies either the number of most recent items to
11+
return or a string used to search the history.
12+
#>
113

214
# CmdletBinding adds -Verbose functionality, SupportsShouldProcess adds -WhatIf
315
[CmdletBinding(SupportsShouldProcess = $true)]

Modules/Scripts/Invoke-NormalUser.ps1

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,5 @@ param (
1212
[string] $Command
1313
)
1414

15-
if ($env:ConEmuPID)
16-
{
17-
# trying to run this in a new tab but it opens a new PowerShell console! :-(
18-
runas /trustlist:0x20000 $Command
19-
}
20-
else
21-
{
22-
runas /trustlist:0x20000 $Command
23-
}
15+
#https://superuser.com/questions/1749696/parameter-is-incorrect-when-using-runas-with-trustlevel-after-windows-11-22h2
16+
runas /machine:x86 /trustlevel:0x20000 "C:\Windows\sysWOW64\cmd.exe /c `"$Command`""

Modules/Scripts/Restart-App.ps1

Lines changed: 125 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,14 @@
11
<#
2+
3+
4+
I tried! I really tried. Sigh...
5+
6+
This mostly works but if your current user is a member of a group with elevated privileges
7+
then the Command always starts elevated. Appears it's not possible to start a non-elevated
8+
process from a privileged account on Windows!
9+
10+
11+
212
.SYNOPSIS
313
Restart the named process. This can be used to restart applications such as Outlook on a nightly
414
basis. Apps such as this tend to have memory leaks or become unstable over time when dealing with
@@ -51,10 +61,10 @@ To run the task as a specific user: important when restarting Outlook as it mus
5161
the current user, otherwise it will run as admin and you can't click toast notification
5262
5363
> $password = ConvertTo-SecureString -AsPlainText <plainTextPassword>
54-
> Restart-App -Name outlook -Register `
55-
-command 'C:\Program Files\Microsoft Office\root\Office16\OUTLOOK.EXE' `
56-
-StartTime '2am' -Delay '02:00:00' `
57-
-User '<username>' -Password $password
64+
> Restart-App -Name outlook -Register -command 'C:\Program Files\Microsoft Office\root\Office16\OUTLOOK.EXE' `
65+
-User $env:username -Password $password -StartTime '2am' -Delay '02:00:00'
66+
67+
For quick testing, use: -Delay '00:00:05' -StartTime (get-date).addseconds(5)
5868
#>
5969

6070
# CmdletBinding adds -Verbose functionality, SupportsShouldProcess adds -WhatIf
@@ -69,6 +79,7 @@ param (
6979
[string] $User,
7080
[System.Security.SecureString] $Password,
7181
[switch] $Register,
82+
[switch] $Unregister,
7283
[switch] $GetCommand
7384
)
7485

@@ -96,77 +107,146 @@ Begin
96107
$process = (Get-Process $Name -ErrorAction:SilentlyContinue)
97108
if ($process -ne $null)
98109
{
99-
# get the commandline from the process, strip off quotes
100-
$script:cmd = (Get-CimInstance win32_process -filter ("ProcessID={0}" -f $process.id)).CommandLine.Replace('"', '')
101-
Write-Host "... found process $Name running $cmd"
110+
try
111+
{
112+
# get the commandline from the process, strip off quotes
113+
$script:cmdline = (Get-CimInstance win32_process `
114+
-filter ("ProcessID={0}" -f $process.id)).CommandLine.Replace('"', '')
102115

103-
# terminating instead of graceful shutdown because can't connect using this:
104-
# something funny about 32/64 or elevated process or just whatever
105-
#$outlook = [Runtime.Interopservices.Marshal]::GetActiveObject('Outlook.Application')
116+
Log "... terminating process $Name running $cmdline"
106117

107-
Write-Host "... terminating process $Name"
108-
$process.Kill()
109-
$process = $null
110-
Start-Sleep -s $delay
111-
}
118+
# terminating instead of graceful shutdown because can't connect using this:
119+
# GetActiveObject undefined in pwsh Core. Any other way to connect?
120+
#$outlook = [Runtime.Interopservices.Marshal]::GetActiveObject('Outlook.Application')
121+
#$outlook.Quit()
122+
123+
$process.Kill()
124+
$process = $null
125+
126+
Log "sleeping $($delay.ToString())"
127+
Start-Sleep -Duration $delay
128+
}
129+
catch
130+
{
131+
Log "*** error stopping $Name"
132+
Log "*** $($_)"
133+
}
134+
}
112135
else
113136
{
114-
Write-Host "... $Name process not found"
137+
Log "... $Name process not found"
115138
}
116139
}
117140

118141

119142
function Startup
120143
{
121-
if (!$cmd) { $cmd = $Command }
122-
if (!$cmd)
144+
Log "... starting $Name"
145+
146+
$credfile = "C:\Users\$User\$Name`.xml"
147+
if (Test-Path $credfile)
123148
{
124-
Write-Host "*** No command specified to start $Name" -ForegroundColor Yellow
125-
return
149+
try
150+
{
151+
$credential = Import-Clixml $credfile
152+
153+
# TODO: Remove this line:
154+
#Remove-Item -Path $credfile -Force
155+
156+
Log "... running as $($credential.Username) with provided credentials"
157+
158+
if ($Arguments)
159+
{
160+
Log "... starting -Command `"$Command`" -Arguments `"$Arguments`""
161+
Invoke-Command -Credential $credential -ComputerName $env:ComputerName `
162+
-ScriptBlock { & $Command $Arguments }
163+
}
164+
else
165+
{
166+
Log "... starting -Command `"$Command`""
167+
168+
#runas /machine:x86 /trustlevel:0x20000 "C:\Windows\sysWOW64\cmd.exe /c `"$Command`""
169+
170+
# Invoke-Command -Credential $credential -ComputerName $env:ComputerName `
171+
# -ScriptBlock { & $Command }
172+
173+
Log '... started? elevated?'
174+
}
175+
}
176+
catch
177+
{
178+
Log "*** error starting $Name"
179+
Log "*** $($_)"
180+
}
181+
}
182+
else
183+
{
184+
Log "... could not file $credfile, aborting"
126185
}
127-
128-
Write-Host "... starting $Name"
129-
Write-Host "... $cmd $Arguments"
130-
131-
Invoke-Command -ScriptBlock { & $cmd $Arguments }
132186
}
133187

134188

135189
function RegisterTask
136190
{
137191
$span = $delay.ToString()
138-
$cmd = "Restart-App -Name '$Name' -Command '$Command' -Arguments '$Arguments' -delay '$span')"
192+
$cmd = "Restart-App -Name '$Name' -Command '$Command' -Arguments '$cargs' -User $User -delay '$span'"
139193

140-
$trigger = New-ScheduledTaskTrigger -Daily -At 2am;
194+
$trigger = New-ScheduledTaskTrigger -Daily -At $StartTime
141195
$action = New-ScheduledTaskAction -Execute 'pwsh' -Argument "-Command ""$cmd"""
142196

143197
$task = Get-ScheduledTask -TaskName "Restart $Name" -ErrorAction:SilentlyContinue
144198
if ($task -eq $null)
145199
{
146200
Write-Host "... creating scheduled task 'Restart $Name'"
147201

148-
if ($User -and $Password)
149-
{
150-
$plainPwd = (New-Object System.Management.Automation.PSCredential `
151-
-ArgumentList $User, $Password).GetNetworkCredential().Password
202+
$credential = New-Object PSCredential($User, $Password)
203+
$credential | Export-Clixml -Path "C:\Users\$User\$Name`.xml" -Force
152204

153-
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "Restart $Name" ` `
154-
-User $User -Password $plainPwd ` | Out-Null
155-
}
156-
else
157-
{
158-
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "Restart $Name" `
159-
-RunLevel Highest | Out-Null
160-
}
205+
#$credential = (New-Object System.Management.Automation.PSCredential `
206+
# -ArgumentList $User, $Password).GetNetworkCredential()
207+
208+
$plainPwd = ($credential).GetNetworkCredential().Password
209+
210+
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "Restart $Name" `
211+
-User $User -Password $plainPwd | Out-Null
161212
}
162213
else
163214
{
164215
Write-Host "... scheduled task 'Restart $Name' is already registered"
165216
}
166217
}
218+
219+
220+
function UnregisterTask
221+
{
222+
$taskname = "Restart $Name"
223+
$info = get-scheduledtaskinfo -taskname $taskName -ErrorAction:SilentlyContinue
224+
if ($info)
225+
{
226+
Write-Host "... unregistering scheduled task '$taskName'"
227+
Unregister-ScheduledTask -TaskName $taskName -Confirm:$false
228+
}
229+
else
230+
{
231+
Write-Host "... scheduled task '$taskName' is not found"
232+
}
233+
}
234+
235+
236+
function Log
237+
{
238+
param([string] $text)
239+
$text | Out-File -FilePath $LogFile -Append
240+
}
167241
}
168242
Process
169243
{
244+
if ($Name -and $Unregister)
245+
{
246+
UnregisterTask
247+
return
248+
}
249+
170250
if ($GetCommand)
171251
{
172252
GetCommandLine
@@ -191,6 +271,12 @@ Process
191271
return
192272
}
193273

274+
$script:LogFile = Join-Path $env:TEMP 'restart-app.log'
275+
# reset the log file
276+
"starting at $(Get-Date)" | Out-File -FilePath $LogFile
277+
194278
Shutdown
195279
Startup
280+
281+
Log 'done'
196282
}

0 commit comments

Comments
 (0)