-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMicrosoft.PowerShell_profile.ps1
648 lines (586 loc) · 19.5 KB
/
Microsoft.PowerShell_profile.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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
using namespace System.Management.Automation
Add-Type -AssemblyName System.Windows.Forms
#Set-PSReadlineOption -AddToHistoryHandler
# $x | where { $y=cat $_ | ss -Pattern "\bcall" | ss "\bput" ; $y.Length -ge 1 }
. $PSScriptRoot\secret.ps1
#Write-Host "started"
New-Alias ss Select-String
New-Alias grep Select-String
New-Alias z Get-Help -ErrorAction SilentlyContinue
New-Alias m Get-Member
# Remove the default cd alias
Remove-Alias cd
# Create a new cd function
#
#
function Checkout-FileWithDifferentName {
param (
[string]$FilePath,
[string]$NewFileName,
[string]$Branch = "main"
)
# Check if the file exists in the current directory
if (-Not (Test-Path $FilePath)) {
Write-Error "File '$FilePath' does not exist in the current directory."
return
}
# Get the directory and file name from the file path
$directory = Split-Path $FilePath
$fileName = Split-Path $FilePath -Leaf
# Change to the directory containing the file
Push-Location $directory
try {
# Stash any local changes to the file
git stash push $fileName
# Checkout the file from the specified branch
git checkout $Branch -- $fileName
# Rename the checked-out file
Rename-Item -Path $fileName -NewName $NewFileName
# Restore the stashed changes
git stash pop
}
catch {
Write-Error "An error occurred: $_"
}
finally {
# Return to the original directory
Pop-Location
}
}
function ConvertPSObjectToHashtable
{
param (
[Parameter(ValueFromPipeline)]
$InputObject
)
process
{
if ($null -eq $InputObject)
{ return $null
}
if ($InputObject -is [System.Collections.IEnumerable] -and $InputObject -isnot [string])
{
$collection = @(
foreach ($object in $InputObject)
{ ConvertPSObjectToHashtable $object
}
)
Write-Output -NoEnumerate $collection
} elseif ($InputObject -is [psobject])
{
$hash = @{}
foreach ($property in $InputObject.PSObject.Properties)
{
$hash[$property.Name] = (ConvertPSObjectToHashtable $property.Value).PSObject.BaseObject
}
$hash
} else
{
$InputObject
}
}
}
$global:jsonFile = Join-Path -Path $env:USERPROFILE -ChildPath ('cmdLines.json' )
$ExecutionContext.InvokeCommand.PostCommandLookupAction = {
$cmdLine = $MyInvocation.Line
if ($args[1].CommandOrigin -ne 'Runspace' -or $cmdLine -match 'PostCommandLookupAction|^prompt$')
{ return
}
$currentDir = (Get-Location).Path
if (!(Test-Path -Path $global:jsonFile))
{
@{ $currentDir = @($cmdLine) } | ConvertTo-Json | Set-Content -Path $global:jsonFile
} else
{
$existingCmdLines = Get-Content -Path $global:jsonFile | ConvertFrom-Json
$existingCmdLines = ConvertPSObjectToHashtable $existingCmdLines
if (!$existingCmdLines.ContainsKey($currentDir))
{
$existingCmdLines.Add($currentDir, @($cmdLine))
} else
{
if (!$existingCmdLines[$currentDir].Contains($cmdLine))
{
$existingCmdLines[$currentDir] += $cmdLine
}
}
$existingCmdLines | ConvertTo-Json | Set-Content -Path $global:jsonFile
}
}
$parameters = @{
Key = 'Alt+q'
BriefDescription = 'Go to last dir'
LongDescription = 'Go to last dir'
ScriptBlock = {
param($key, $arg) # The arguments are ignored in this example
CdLast
}
}
Set-PSReadLineKeyHandler @parameters
$parameters = @{
Key = 'Alt+e'
BriefDescription = 'Execute from last same direrctory'
LongDescription = 'Execute from last commands typed in same direrctory'
ScriptBlock = {
param($key, $arg) # The arguments are ignored in this example
[Microsoft.PowerShell.PSConsoleReadLine]::RevertLine()
[Microsoft.PowerShell.PSConsoleReadLine]::Insert( $(GrepOnCurDir) )
[Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine()
}
}
Set-PSReadLineKeyHandler @parameters
$parameters = @{
Key = 'Alt+l'
BriefDescription = 'Grep from last same direrctory'
LongDescription = 'Grep from last commands typed in same direrctory'
ScriptBlock = {
param($key, $arg) # The arguments are ignored in this example
[Microsoft.PowerShell.PSConsoleReadLine]::RevertLine()
[Microsoft.PowerShell.PSConsoleReadLine]::Insert( $(GrepOnCurDir) )
}
}
Set-PSReadLineKeyHandler @parameters
function GrepOnCurDir()
{
$currentDir = (Get-Location).Path
$existingCmdLines = Get-Content -Path $global:jsonFile | ConvertFrom-Json
$existingCmdLines = ConvertPSObjectToHashtable $existingCmdLines
$existingCmdLines[$currentDir] | fzf
}
function MyCD
{
Set-Location @args
#$curtime =$(Get-Date -Format "yyyy-MM-dd HH:mm:ss")
#$dict = @{
#Id = "30"
#CommandLine = "cd $(Get-Location)"
#ExecutionStatus = "Completed"
#StartExecutionTime = $curtime
#EndExecutionTime = $curtime
#Duration = "00:00:00.0389011"
#}
#$historyObject = New-Object -TypeName PSObject -Property $dict
#Add-History -InputObject $historyObject
$historyLocation = $(Get-PSReadLineOption).HistorySavePath
Add-Content -Path $historyLocation -Value "cd $(Get-Location)"
}
# Set cd to use the new function
Set-Alias cd MyCD
function SimpHistEx
{
$va=$(SimpHist)
[Microsoft.PowerShell.PSConsoleReadLine]::RevertLine()
[Microsoft.PowerShell.PSConsoleReadLine]::Insert( $va )
[Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine()
#[System.Windows.Forms.SendKeys]::SendWait($va)
}
function SimpHist
{
$historyLocation = $(Get-PSReadLineOption).HistorySavePath
$all = Get-Content $historyLocation
return $($all | Sort-Object -Unique | FZF)
}
# Function to get history of saved locations
function StupidHist
{
$historyLocation = $(Get-PSReadLineOption).HistorySavePath
$all = Get-Content $historyLocation | select-string -Pattern "^cd .:" | %{ echo ($_ -replace "^cd (.*)","`$1") } | Sort-Object -Unique
return $all | Where-Object { Test-Path $($_) }
}
# Function to change to the last visited location
function CdLast
{
$location = StupidHist | FZF
if ($location)
{
Set-Location $location
}
}
# Create an alias for CdLast
Set-Alias q CdLast
function ConVM
{
$Username = "User"
$Password = ConvertTo-SecureString "Password1" -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential($Username, $Password)
$Session = New-PSSession -VMName win10 -Credential $Credential
return $Session
}
function ClearShada
{
rm C:\Users\ekarni\AppData\Local\nvim-data\shada\*
ResetNeo
}
function Which($arg)
{
python -c "import shutil; print(shutil.which('$arg'))"
}
function AddWrapper([parameter(mandatory=$true, position=0)][string]$For,[parameter(mandatory=$true, position=1)][string]$To)
{
$paramDictionary = [RuntimeDefinedParameterDictionary]::new()
$paramset= $(Get-Command $For).Parameters.Values | %{[System.Management.Automation.RuntimeDefinedParameter]::new($_.Name,$_.ParameterType,$_.Attributes)}
$paramsetlet= $(Get-Command empt).Parameters.Keys
$paramsetlet+= $(Get-Command $To).ScriptBlock.Ast.Body.ParamBlock.Parameters.Name | %{ $_.VariablePath.UserPath }
$paramset | %{ if ( -not ($paramsetlet -contains $_.Name) )
{$paramDictionary.Add($_.Name,$_)
}}
return $paramDictionary
}
function GetRestOfParams()
{
#if dontincludecommon provide source function else dst function
Param([parameter(mandatory=$true, position=1)][hashtable]$params,
[parameter(mandatory=$true, position=0)][string]$dstsource,
[parameter(mandatory=$false, position=2)][switch][bool]$dontincludecommon=$true)
$dstorgparams=$(Get-Command $dstsource).Parameters.Keys
$z= $params
if ( -not $dontincludecommon)
{
$z.Keys | %{ if ( -not ($dstorgparams -contains $_) )
{$z.Remove($_)
} } | Out-Null
} else
{
$dyn= $(Get-Command $dstsource).Parameters.Values | Where-Object -Property IsDynamic -Eq $false
$dyn | %{ $z.Remove($_.Name) } | Out-Null
}
return $z
}
function Empt
{
[CmdletBinding()]
Param([parameter(mandatory=$true, position=0)][string]$aaaa)
1
}
function Let
{
[CmdletBinding()]
Param([parameter(mandatory=$true, position=0)][string]$Option,[parameter(mandatory=$false, position=0)][string]$OptionB)
DynamicParam
{
AddWrapper -For Get -To $MyInvocation.MyCommand.Name
}
Begin
{
$params = GetRestOfParams Let $PSBoundParameters -dontincludecommon
}
Process
{
Get @params -OptionB ( $OptionB + "1"
)
}
}
function Get
{
[CmdLetBinding()]
Param([parameter(mandatory=$false, position=0)][string]$OptionA,
[parameter(mandatory=$false, position=1)][string]$OptionB)
Write-Host "opta",$OptionA
Write-Host "optb",$OptionB
}
Function Term($Proc,$cmd="*")
{
(Get-Process) | Where { $_.name -like $Proc} | Where-Object CommandLine -like $cmd | ForEach-Object{Get-CimInstance Win32_Process -Filter ("ProcessId = {0}" -f ($_.Id)) } | %{ Invoke-CimMethod -InputObject $_ -MethodName Terminate }
}
Function KillAllPyCharm()
{
Term python *pydevd*
Term python *ibsrv*
Term cmd *ibsrv*
}
Function EditInNeo($ar)
{
Write-Host nvr --remote $ar --servername $(Get-Content C:\temp\listen.txt)
nvr --remote $ar --servername $(Get-Content C:\temp\listen.txt)
if ($LASTEXITCODE -eq 1)
{&"C:\Users\ekarni\Neovim\bin\nvim-qt.exe" $ar
}
Show-Window nvim-qt
}
Function ResetNeo($a)
{
DelProcess nvim-qt
if ($a)
{
Start-Process "C:\Users\ekarni\Neovim\bin\nvim-qt.exe" -ArgumentList ($a)
} else
{ Start-Process "C:\Users\ekarni\Neovim\bin\nvim-qt.exe"
}
#ps | Where-Object -Property ProcessName -Like "*goneovim*"| %{Write-Host $_.Id ,$_.ProcessName ;$_.Kill()}
#C:\Users\ekarni\Downloads\Goneovim-v0.4.12-win64\goneovim.exe
}
Function DelProcess($name)
{
ps | Where-Object -Property ProcessName -Like "*$name*"| %{Write-Host $_.Id ,$_.ProcessName ;$_.Kill()}
}
function TranslatePath($fil)
{
wsl bash -c "wslpath -w '$fil'"
}
function RunBash($fil)
{
wsl bash -c "source /home/ekarni/.bash_profile; $fil"
}
function OtherPython($a)
{
Invoke-expression "C:\users\ekarni\AppData\Local\Programs\Python\Python39\python.exe $a"
}
function Show-Window
{
param(
[Parameter(Mandatory)]
[string] $ProcessName
)
# As a courtesy, strip '.exe' from the name, if present.
$ProcessName = $ProcessName -replace '\.exe$'
# Get the PID of the first instance of a process with the given name
# that has a non-empty window title.
# NOTE: If multiple instances have visible windows, it is undefined
# which one is returned.
$hWnd = (Get-Process -ErrorAction Ignore $ProcessName).Where({ $_.MainWindowTitle }, 'First').MainWindowHandle
if (-not $hWnd)
{ Throw "No $ProcessName process with a non-empty window title found."
}
$type = Add-Type -PassThru -NameSpace Util -Name SetFgWin -MemberDefinition @'
[DllImport("user32.dll", SetLastError=true)]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll", SetLastError=true)]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll", SetLastError=true)]
public static extern bool IsIconic(IntPtr hWnd); // Is the window minimized?
'@
# Note:
# * This can still fail, because the window could have bee closed since
# the title was obtained.
# * If the target window is currently minimized, it gets the *focus*, but its
# *not restored*.
$null = $type::SetForegroundWindow($hWnd)
# If the window is minimized, restore it.
# Note: We don't call ShowWindow() *unconditionally*, because doing so would
# restore a currently *maximized* window instead of activating it in its current state.
if ($type::IsIconic($hwnd))
{
$type::ShowWindow($hwnd, 9) # SW_RESTORE
}
}
Function Get-LockingProcess
{
[cmdletbinding()]
Param(
[Parameter(Position=0, Mandatory=$True,
HelpMessage="What is the path or filename? You can enter a partial name without wildcards")]
[Alias("name")]
[ValidateNotNullorEmpty()]
[string]$Path
)
# Define the path to Handle.exe
# //$Handle = "G:\Sysinternals\handle.exe"
$Handle = "C:\SysinternalsSuite\handle.exe"
# //[regex]$matchPattern = "(?<Name>\w+\.\w+)\s+pid:\s+(?<PID>\b(\d+)\b)\s+type:\s+(?<Type>\w+)\s+\w+:\s+(?<Path>.*)"
# //[regex]$matchPattern = "(?<Name>\w+\.\w+)\s+pid:\s+(?<PID>\d+)\s+type:\s+(?<Type>\w+)\s+\w+:\s+(?<Path>.*)"
# (?m) for multiline matching.
# It must be . (not \.) for user group.
[regex]$matchPattern = "(?m)^(?<Name>\w+\.\w+)\s+pid:\s+(?<PID>\d+)\s+type:\s+(?<Type>\w+)\s+(?<User>.+)\s+\w+:\s+(?<Path>.*)$"
# skip processing banner
$data = &$handle -u $path -nobanner
# join output for multi-line matching
$data = $data -join "`n"
$MyMatches = $matchPattern.Matches( $data )
# //if ($MyMatches.value) {
if ($MyMatches.count)
{
$MyMatches | foreach {
[pscustomobject]@{
FullName = $_.groups["Name"].value
Name = $_.groups["Name"].value.split(".")[0]
ID = $_.groups["PID"].value
Type = $_.groups["Type"].value
User = $_.groups["User"].value.trim()
Path = $_.groups["Path"].value
toString = "pid: $($_.groups["PID"].value), user: $($_.groups["User"].value), image: $($_.groups["Name"].value)"
} #hashtable
} #foreach
} #if data
else
{
Write-Warning "No matching handles found"
}
} #end function
function copy-foldertovirtualmachine
{
param(
[parameter (mandatory = $true, valuefrompipeline = $true)]
[string]$VMName,
[string]$FromFolder = '.\'
)
foreach ($File in (Get-ChildItem $Folder -recurse | ? Mode -ne 'd-----'))
{
$relativePath = $item.FullName.Substring($Root.Length)
Copy-VMFile -VM (Get-VM $VMName) -SourcePath $file.fullname -DestinationPath $file.fullname -FileSource Host -CreateFullPath -Force
}
}
function NewVMDrive
{
$Username = "user"
$Password = ConvertTo-SecureString "Password1" -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential($Username, $Password)
New-PSDrive -Name "V" -PSProvider "FileSystem" -Root "\\192.168.10.2\c$" -Credential $cred -Persist
}
function GetGitStash
{
git stash list | ss mychanges | %{ $_ -replace ":.*$"} | %{ git diff $_^1 $_}
}
function CheckCommit ($n,$line)
{
$commits= git log --pretty=format:%h -n $n
$commits | %{ git show $_ | select-string $line}
}
function SquashCommits([int]$count)
{
$commitHashes = git log --pretty=format:%h -n $count
$commands= ( 0..$($count-2) ) | %{ "sed -i 's/^pick $($commitHashes[$_])/squash $($commitHashes[$_])/' `$file" }
$st= $commands -join "`n"
$st="func() {
local file=`$1
$st
}; func"
$env:GIT_SEQUENCE_EDITOR=$st
try
{
git rebase -i HEAD~$count
} finally
{
Remove-Item Env:\GIT_SEQUENCE_EDITOR
}
}
function RemoveCommit([string]$commit)
{
$commitid=git log --pretty="%h" --grep=$commit
$st= "sed -i 's/^pick $($commitid)/drop $($commitid)/' `$file"
$st= $commands -join "`n"
$st="func() {
local file=`$1
$st
}; func"
$env:GIT_SEQUENCE_EDITOR=$st
try
{
git rebase -i HEAD~$count
} finally
{
Remove-Item Env:\GIT_SEQUENCE_EDITOR
}
}
function ExtractFromLastStash($file)
{
$x=git diff stash@`{0`}^1 stash@`{0`} -- $file
return $x
}
function Checkout-FileFromStash {
param (
[Parameter(Mandatory = $true)]
[string]$FilePath,
[Parameter(Mandatory = $false)]
[int]$StashIndex
)
# Get the list of stashes
$stashes = git stash list
if ($stashes.Count -eq 0) {
Write-Host "No stashes found."
return
}
# Display the list of stashes
Write-Host "Available stashes:"
$stashes | ForEach-Object { Write-Host $_ }
# If StashIndex is not provided, prompt the user to select a stash
if (-not $PSBoundParameters.ContainsKey('StashIndex')) {
$StashIndex = Read-Host "Enter the index of the stash you want to use (e.g., 0 for stash@{0})"
# Validate the user's input
if (-not $StashIndex -match '^\d+$') {
Write-Error "Invalid input. Please enter a valid stash index."
return
}
}
# Checkout the specified file from the selected stash
try {
git checkout stash@{$StashIndex} -- $FilePath
Write-Host "File '$FilePath' has been checked out from stash@{$StashIndex}."
} catch {
Write-Error "An error occurred while checking out the file: $_"
}
}
function StashAll($name)
{
git stash store $(git stash create) -m $name
}
function GitPullKeepLocal ()
{
param (
[parameter()][switch]$keeplocalinconflict =$null,
[parameter()][switch]$dontkeepstash=$false
)
$commit_hash=$(git rev-parse HEAD)
git stash save | Out-Null
git pull --rebase
$conflicts = $(git diff --name-only --diff-filter=U)
$changes = $(git diff --name-only $commit_hash)
if ($conflicts)
{
Write-Host "There are merge conflicts. Please run git pull. Aborting"
#abort the pull
git rebase --abort
# Exit or throw an error here, if you want to stop the script
} else
{
# Checkout files from the stash
git checkout stash -- . | Out-Null
git reset | Out-Null
$localch= $(git diff --name-only)
$int = $localch | ?{ $changes -contains $_ }
if ($int)
{
echo "Following files are in both: $int "
if ($(-not ($keeplocalinconflict)))
{
$userInput = Read-Host -Prompt "Do you want to keep local changes in case of conflict? (y/n/merge)"
if ($userInput -eq "y") {
$keeplocalinconflict = $true
} else {
echo "reseting to remote"
git checkout -- $int
}
if ($userInput -eq "merge")
{
git stash apply
}
}
}
if ($dontkeepstash)
{
git stash drop
}
# Drop the stash
}
}
function RestartWsl()
{
Get-Service LxssManager | Restart-Service
}
function UpdateVim($typ)
{
cd C:\Users\ekarni
Write-Host "usage: new-version-zip-filename (ie nightly)"
Remove-Item -Path nvim-win64.zip -ErrorAction SilentlyContinue
$webClient = New-Object System.Net.WebClient
$webClient.DownloadFile("https://github.com/neovim/neovim/releases/download/$typ/nvim-win64.zip", "C:\Users\ekarni\nvim-win64.zip")
if (Test-Path -Path nvim-temp)
{
Write-Host "moving temp to last temp"
Remove-Item -Path ./neovim-lasttemp -Recurse -Force -ErrorAction SilentlyContinue
Move-Item -Path nvim-temp -Destination nvim-lasttemp
}
#Move-Item -Path nvim-temp -Destination nvim-lasttemp -ErrorAction SilentlyContinue
Move-Item -Path ./Neovim -Destination nvim-temp
Expand-Archive -Path nvim-win64.zip -DestinationPath ./Neovim -Force
}
New-Alias gitp GitPullKeepLocal