-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathps-profile.ps1
881 lines (809 loc) · 30.8 KB
/
ps-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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
using namespace System.Management.Automation
using namespace System.Management.Automation.Language
using namespace System.Collections.Generic
using namespace Microsoft.Azure.Commands.ContainerRegistry.Models
try {
Import-Module TerminalBlocks -ErrorAction Stop
Import-Module posh-git -ErrorAction Stop
$global:GitPromptSettings = New-GitPromptSettings
$global:GitPromptSettings.BeforeStatus = ''
$global:GitPromptSettings.AfterStatus = ''
$global:GitPromptSettings.PathStatusSeparator = ''
$global:GitPromptSettings.BeforeStash.Text = "$(Text '&ReverseSeparator;')"
$global:GitPromptSettings.AfterStash.Text = "$(Text '&Separator;')"
$global:Prompt = @(
# Initialize-Prompt
[PoshCode.TerminalBlock]::LastSuccess = $global:?
[PoshCode.TerminalBlock]::LastExitCode = $global:LASTEXITCODE
Show-LastExitCode -ForegroundColor 'VioletRed1' -Caps '',"`n"
Show-HistoryId -Prefix '#' -DefaultForegroundColor Gold -DefaultBackgroundColor MediumSlateBlue
Show-Path -DriveName -ForegroundColor Black -DefaultBackgroundColor SeaGreen1
Show-ElapsedTime -Prefix '' -ForegroundColor SeaGreen1 -BackgroundColor Black
Show-KubeContext -Prefix "😇"
Show-AzureContext -Prefix "🦾"
if (Get-Module posh-git) {
Show-PoshGitStatus -AfterStatus ' ' -PathStatusSeparator '' -Caps ''
}
Show-Date -Format 'hh:mm:sss yyyy-MM-dd' -ForegroundColor Orchid1 -BackgroundColor Black -Alignment Right
New-TerminalBlock '>' -ForegroundColor 'Gray80' -Caps '',' '
Set-PSReadLineOption -PromptText (New-Text '>> ' -Foreground AntiqueWhite4), (New-Text '> ' -Foreground 'VioletRed1')
# Exit-Prompt
$global:LASTEXITCODE = [PoshCode.TerminalBlock]::LastExitCode
)
function global:Prompt { -join $Prompt }
} catch {
Write-Warning "Issue importing and configuring TerminalBlocks: $($_)"
}
# improve speed of downloads by turning off progress bar
$ProgressPreference = 'SilentlyContinue'
$PSDefaultParameterValues = @{
'Invoke-Command:HideComputerName' = $true
}
if (Get-Module ImportExcel -List) {
$PSDefaultParameterValues.Add('Export-Excel:FreezeTopRow',$true)
$PSDefaultParameterValues.Add('Export-Excel:BoldTopRow',$true)
$PSDefaultParameterValues.Add('Export-Excel:TableStyle','Light14')
}
if (Get-Module Terminal-Icons -ListAvailable) {
Import-Module Terminal-Icons
}
if ((Get-Module AzureAD -ListAvailable) -and ($psedition -eq 'Core' -and -not $IsMacOS)) {
Import-Module AzureAD -UseWindowsPowerShell -WarningAction SilentlyContinue
}
#region PSReadLine
Set-PSReadLineOption -PredictionSource History -PredictionViewStyle ListView
#endregion PSReadLine
if ($psedition -ne 'Core' -and -not $IsMacOS) {
[System.Net.ServicePointManager]::SecurityProtocol = @('Tls12', 'Tls11', 'Tls', 'Ssl3')
}
if (Test-Path "$env:USERPROFILE\azure-context.json") {
$azContextImport = "$env:USERPROFILE\azure-context.json"
}
#region shortcuts
Set-Alias -Name gsc -Value 'Get-Secret'
Set-Alias -Name g -Value git
Set-Alias -Name k -Value kubectl
Set-Alias -Name kx -Value kubectx
Set-Alias -Name kns -Value kubens
Set-Alias -Name ci -Value 'code-insiders'
#endregion shortcuts
#region functions
function GitLog {
[Alias('glc')]
[CmdletBinding()]
param(
[Parameter(Position = 0)]
[int]$LineCount = 5,
[Parameter(Position = 1)]
[string]$FilePath
)
if ($FilePath) {
git log --pretty=oneline --all --full-history -- $FilePath
} else {
git log --pretty=oneline -$LineCount
}
}
if (-not $IsMacOS) {
function myRdp {
[cmdletbinding()]
param (
$server,
[switch]$fullScreen
)
if ($fullScreen) {
mstsc.exe -v $server -f
} else {
mstsc.exe -v $server /w 2150 /h 1250
}
}
function findAd {
[cmdletbinding()]
param(
[Parameter(Position = 0,Mandatory)]
[string]
$str,
[Parameter(Position = 1)]
[string[]]
$Props,
[Parameter(Position = 2)]
[Alias('emo')]
[switch]
$ExpandMemberOf
)
begin {
$hasSpace = $false
}
process {
if ($IsCoreCLR -and -not (Get-Module ActiveDirectory)) {
Import-Module ActiveDirectory -UseWindowsPowerShell -ErrorAction Stop
} elseif (-not (Get-Module ActiveDirectory)) {
Import-Module ActiveDirectory -ErrorAction Stop
}
$hasSpace = $str.Split(' ').Count -gt 1
$adObject = Get-ADObject -Filter "Name -eq '$str'"
if ($adObject) {
switch ($adObject.ObjectClass) {
'user' {
$defaultProps = 'Description', 'MemberOf', 'whenCreated', 'whenChanged', 'LastLogonDate', 'PasswordLastSet', 'UserPrincipalName', 'CannotChangePassword', 'PasswordNeverExpires'
if ($PSBoundParameters.ContainsKey('Props')) {
$defaultProps = $defaultProps, $Props
}
Write-Verbose "Properties: $($defaultProps -join ',')"
$finalAdObject = Get-ADUser -Filter "Name -eq '$str'" -Properties $defaultProps
}
default {
$defaultProps = 'Description', 'MemberOf', 'whenCreated', 'whenChanged', 'UserPrincipalName'
if ($PSBoundParameters.ContainsKey('Props')) {
$defaultProps = $defaultProps, $Props
}
Write-Verbose "Properties: $($defaultProps -join ',')"
$finalAdObject = Get-ADObject -Filter "Name -eq '$str'" -Properties $defaultProps
}
}
if ($finalAdObject) {
if ($PSBoundParameters.ContainsKey('ExpandMemberOf')) {
$finalAdObject.MemberOf | Sort-Object
} else {
$finalAdObject
}
}
}
}
}
function findAdSrv {
[cmdletbinding()]
param(
[Parameter(Position = 0,Mandatory)]
[string]
$str,
[Parameter(Position = 1)]
[string[]]
$Props,
[Parameter(Position = 2)]
[Alias('emo')]
[switch]
$ExpandMemberOf
)
process {
if ($IsCoreCLR -and -not (Get-Module ActiveDirectory)) {
Import-Module ActiveDirectory -UseWindowsPowerShell -ErrorAction Stop
} elseif (-not (Get-Module ActiveDirectory)) {
Import-Module ActiveDirectory -ErrorAction Stop
}
$defaultProps = 'Description', 'MemberOf', 'whenCreated', 'LastLogonDate'
if ($PSBoundParameters.ContainsKey('Props')) {
$srvResult = Get-ADComputer -Identity $str -Properties $defaultProps,$Props
} else {
$srvResult = Get-ADComputer -Identity $str -Properties $defaultProps
}
if ($srvResult) {
if ($PSBoundParameters.ContainsKey('ExpandMemberOf')) {
$srvResult.MemberOf | Sort-Object
} else {
$srvResult
}
}
}
}
function Get-ClusterFailoverEvent {
param([string]$Server)
Get-WinEvent -ComputerName $Server -FilterHashtable @{LogName = 'Microsoft-Windows-FailoverClustering/Operational'; Id = 1641 }
}
function Find-MissingCommands {
<#
.SYNOPSIS
Find missing commands between the dbatools.io/commands and dbatools Module public functions
.PARAMETER ModulePath
Path to dbatools local repository
.PARAMETER CommandPagePath
Full path to the index.html commands page (e.g. c:\git\web\commands\index.html)
.PARAMETER Reverse
Compare commands found in the CommandPagePath to those in the module
.EXAMPLE
Find-MissingCommands
Returns string list of the commands not found in the Commands page.
#>
[cmdletbinding()]
param(
[string]
$ModulePath = 'C:\git\dbatools',
[string]
$CommandPagePath = 'C:\git\web\commands\index.html',
[switch]
$Reverse
)
$commandPage = Get-Content $CommandPagePath
if (-not (Get-Module dbatools)) {
Import-Module $ModulePath
}
$commands = Get-Command -Module dbatools -CommandType Cmdlet, Function | Where-Object Name -NotIn 'Where-DbaObject','New-DbaTeppCompletionResult' | Select-Object -Expand Name
if ($Reverse) {
$commandRefs = $commandPage | Select-String '<a href="http://docs.dbatools.io/' | ForEach-Object { $_.ToString().Trim() }
$commandRefList = foreach ($ref in $commandRefs) {
$ref.ToString().SubString(0,$ref.ToString().IndexOf('">')).TrimStart('<a href="http://docs.dbatools.io/')
}
$commandRefList | Where-Object { $_ -notin $commands }
} else {
#find missing
$notFound = $commands | ForEach-Object -ThrottleLimit 10 -Parallel { $foundIt = $using:commandPage | Select-String -Pattern $_; if (-not $foundIt) { $_ } }
# found
$found = $commands | ForEach-Object -ThrottleLimit 10 -Parallel { $foundIt = $using:commandPage | Select-String -Pattern $_; if ($foundIt) { $_ } }
Write-Host "Tally: Total Commands ($($commands.Count)) | Found ($($found.Count)) | Missing ($($notFound.Count))"
$notFound
}
}
function Revoke-DomainToken {
<#
.SYNOPSIS
Revoking user access in Active Directory and Azure AD Tenant
Ref: https://docs.microsoft.com/en-us/azure/active-directory/enterprise-users/users-revoke-access
#>
[cmdletbinding(SupportsShouldProcess)]
param(
# Provide user identity ([email protected])
[string]
$Identity,
# Credential to login to Active Directory
[PSCredential]
$ADCredential
)
begin {
$justUsername = $Identity.Split('@')[0]
}
process {
try {
if ($psedition -eq 'Core') {
Import-Module ActiveDirectory -UseWindowsPowerShell -ErrorAction Stop
} else {
Import-Module ActiveDirectory -ErrorAction Stop
}
} catch {
throw "Issue loading ActiveDirectory Module: $($_)"
}
try {
if ($psedition -eq 'Core') {
Import-Module AzureAD -UseWindowsPowerShell -ErrorAction Stop
} else {
Import-Module AzureAD -ErrorAction Stop
}
} catch {
throw "Issue loading AzureAD Module: $($_)"
}
if ($PSCmdlet.ShouldProcess($justUsername,'Disabling Active Directory Identity')) {
try {
if (Get-ADUser -Identity $justUsername -Credential $ADCredential -ErrorAction SilentlyContinue) {
Disable-ADAccount -Identity $justUsername -Credential $ADCredential -ErrorAction Stop
} else {
Write-Warning "No user found matching $justUsername"
return
}
} catch {
throw "Issue disabling User [$justUsername]: $($_)"
}
}
if ($PSCmdlet.ShouldProcess($justUsername,'Reseting password to random value x2')) {
try {
1..2 | ForEach-Object {
Set-ADAccountPassword -Identity $justUsername -Credential $ADCredential -Reset -NewPassword (ConvertTo-SecureString -String (New-RandomPassword) -AsPlainText -Force) -ErrorAction Stop
}
} catch {
throw "Issue reseting password for User [$justUsername]: $($_)"
}
}
try {
Get-AzureADTenantDetail -ErrorAction Stop >$null
Write-Host 'Connected to Azure AD'
} catch {
Write-Warning 'No active connection found to Azure AD'
Connect-AzureAD >$null
}
if ($PSCmdlet.ShouldProcess($Identity,'Disabling Azure AD Identity')) {
try {
Set-AzureADUser -ObjectId $Identity -AccountEnabled $false -ErrorAction Stop
} catch {
throw "Issue disabling Azure AD Account [$Identity]: $($_)"
}
}
if ($PSCmdlet.ShouldProcess($Identity,'Revoking Azure AD Token')) {
try {
Revoke-AzureADUserAllRefreshToken -ObjectId $Identity -ErrorAction Stop
} catch {
throw "Issue revoking Azure AD Account [$Identity]: $($_)"
}
}
}
}
function testAdMembership {
param(
[Parameter(Position = 0)]
[string]$User,
[Parameter(Position = 1)]
[string]$Group)
trap { return 'error' }
$adUserParams = @{
Filter = "memberOf -RecursiveMatch '$((Get-ADGroup $Group).DistinguishedName)'"
SearchBase = $((Get-ADUser $User).DistinguishedName)
}
if (Get-ADUser @adUserParams) { $true } else { $false }
}
}
function findshit ($str,$path) {
$str = [regex]::escape($str)
Select-String -Pattern $str -Path (Get-ChildItem $path -Recurse -Exclude 'allcommands.ps1', '*.dll', '*psproj')
}
function Reset-Az {
param(
[string]
$TenantId,
[switch]
$DeviceAuth
)
Clear-AzContext -Force
Connect-AzAccount -UseDeviceAuthentication:$DeviceAuth -Tenant $TenantId -WarningAction SilentlyContinue >$null
Get-AzContext -ListAvailable | ForEach-Object { $n = $_.Name; Rename-AzContext -SourceName $n -TargetName $n.Split(' ')[0] }
Save-AzContext -Path $azContextImport -Force
Import-AzContext -Path $azContextImport >$null
}
function New-RandomPassword {
[cmdletbinding()]
param(
[Parameter(Position = 0)]
[int]$CharLength = 15
)
$charlist = [char]94..[char]126 + [char]65..[char]90 + [char]47..[char]57
$pwLength = (1..10 | Get-Random) + 80
$pwdList = @()
for ($i = 0; $i -lt $pwLength; $i++) {
$pwdList += $charList | Get-Random
}
($pwdList -join '').Substring(0,$CharLength)
}
filter Get-AcrTag {
<#
.SYNOPSIS
Search ACR for repositories and get latest tags
.LINK
https://gist.github.com/Jaykul/88900be0cf36ab6d340d65a4ffd056b3
.EXAMPLE
Test-MyTestFunction -Verbose
Explanation of the function or its result. You can include multiple examples with additional .EXAMPLE lines
#>
[Alias('Get-BicepTag','gat','gbt')]
[CmdletBinding()]
param(
# The (partial) name of the repository.
[Parameter(Mandatory, ValueFromRemainingArguments, Position = 0)]
[Alias('RepositoryName')]
[string[]]$Name,
# The name of the registry to search.
# Recommend you set this in your $PSDefaultParameters
[Parameter(Mandatory)]
[string]$RegistryName,
# Force fetching the list of repositories from the registry
[switch]$Force
)
$global:AzContainerRegistryRepositoryCache += @{}
if (!$Force -and $AzContainerRegistryRepositoryCache.ContainsKey($RegistryName)) {
Write-Verbose 'Using cached repository list (specify -Force to re-fetch)'
} else {
Write-Verbose 'Looking for new repositories'
$global:AzContainerRegistryRepositoryCache[$RegistryName] = Get-AzContainerRegistryRepository -RegistryName $RegistryName
}
$Repositories = $global:AzContainerRegistryRepositoryCache[$RegistryName] -match "($($name -join '|'))$"
foreach ($repo in $Repositories) {
Write-Verbose "Fetching version tags for $repo"
foreach ($registry in Get-AzContainerRegistryTag -RegistryName $azContainerRegistry -RepositoryName $repo -ea 0) {
# Sort the tags the opposite direction
$registry.Tags.Sort( { -1 * $args[0].LastUpdateTime.CompareTo($args[1].LastUpdateTime) } )
$registry
}
}
}
function Set-Subscription {
[Alias('ss')]
[CmdletBinding()]
param (
[Parameter(Mandatory, ValueFromRemainingArguments, Position = 0)]
[string]
$SubName,
[string]
$TenantId = $tenantIdProd
)
process {
$cContext = Get-AzContext
if ($cContext.Name -ne $SubName) {
$result = Select-AzSubscription $SubName -Tenant $TenantId
}
if ($result.Name -eq $SubName) {
Write-Host "Context switched to subscription: [$SubName]" -ForegroundColor DarkCyan
}
}
}
function Get-AzureAddressSpace {
[CmdletBinding()]
param()
process {
try {
$subscriptions = Get-AzSubscription -TenantId $tenantIdProd -ErrorAction Stop
} catch {
throw "Issue getting list of Subscriptions: $($_)"
}
if ($subscriptions) {
$subscriptions | ForEach-Object -ThrottleLimit 10 -Parallel {
$subName = $_.Name
$azContext = Get-AzContext -WarningAction SilentlyContinue
if ($azContext -and $azContext.SubscriptionName -ne $subName) {
Set-AzContext -Subscription $subName -WarningAction SilentlyContinue >$null
}
$virtualNetworks = Get-AzVirtualNetwork
foreach ($vnet in $virtualNetworks) {
$resourceGroup = $vnet.ResourceGroupName.ToLower()
$vnetName = $vnet.Name.ToLower()
$vnetLocation = $vnet.Location
$addressSpaces = $vnet.AddressSpace.AddressPrefixes
if ($addressSpaces.Count -gt 1) {
foreach ($space in $addressSpaces) {
[pscustomobject]@{
Subscription = $subName
ResourceGroupName = $resourceGroup
VnetName = $vnetName
Location = $vnetLocation
AddressSpace = $space
}
}
} else {
[pscustomobject]@{
Subscription = $subName
ResourceGroupName = $resourceGroup
VnetName = $vnetName
Location = $vnetLocation
AddressSpace = $addressSpaces
}
}
}
}
}
}
}
function Get-PopeyeReport {
if (Get-Command popeye -ErrorAction SilentlyContinue) {
try {
$env:POPEYE_REPORT_DIR = $env:temp
popeye -A -c -o 'html'
} catch {
throw "Issue running popeye: $($_)"
}
}
}
function Test-ADUserPassword {
[cmdletbinding()]
param(
[Parameter(Mandatory)]
[pscredential]
$Credential,
[ValidateSet('ApplicationDirectory','Domain','Machine')]
[string]
$ContextType = 'Domain',
[string]
$Server
)
try {
Add-Type -AssemblyName System.DirectoryServices.AccountManagement -ErrorAction Stop
try {
if ($PSBoundParameters.ContainsKey('Server')) {
$pContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext($ContextType,$Server)
} else {
$pContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext($ContextType)
}
} catch {
Write-Error -Message "Issue connecting $ContextType -- $($_)"
}
try {
$pContext.ValidateCredentials($Credential.UserName, $Credential.GetNetworkCredential().Password,'Negotiate')
} catch [UnauthorizedAccessException] {
Write-Warning -Message 'Access denied when connecting to server.'
return $false
} catch {
Write-Error -Exception $_.Exception -Message "Unhandled error occurred: $($_)"
}
} catch {
throw
}
}
function findLocalAdmins {
[cmdletbinding()]
param(
[Parameter(Mandatory)]
[string[]]
$Server,
[pscredential]
$Credential
)
$Server | ForEach-Object -ThrottleLimit 15 -Parallel {
$s = $_
$psSessionParams = @{
ComputerName = $s
}
if ($using:Credential) {
$psSessionParams.Add('Credential',$using:Credential)
}
try {
$psSession = New-PSSession @psSessionParams -ErrorAction Stop
} catch {
Write-Warning "Unable to connect to server: $($s) | $($_)"
}
if ($psSession) {
try {
$resultData = Invoke-Command -Session $psSession -ScriptBlock { Get-LocalGroupMember -Group Administrators } -ErrorAction Stop
if ($resultData) {
foreach ($r in $resultData) {
[pscustomobject]@{
Server = $s
Name = $r.Name
Type = $r.ObjectClass
IsLocal = if ($r.PrincipalSource -eq 'Local') { $true } else { $false }
}
}
}
} catch {
$resultOld = Invoke-Command -Session $psSession -ScriptBlock { net localgroup Administrators }
foreach ($r in ($resultOld | Select-Object -Skip 6)) {
if ($r -notmatch 'The command completed successfully' -and -not [string]::IsNullOrEmpty($r)) {
[pscustomObject]@{
Server = $s
Name = $r
Type = $null
IsLocal = $null
}
}
}
}
Remove-PSSession -Session $psSession
}
}
}
# Kubernetes
function Deploy-PSContainer {
[Alias('krps')]
[CmdletBinding()]
param()
k run -it --rm aks-pwsh --image=mcr.microsoft.com/powershell:latest -n default
}
function Get-PodLog {
<#
.SYNOPSIS
Watch the logs for a given Namespace and particular pod (by index number of the "kubectl get pod" output
#>
[Alias('kpl')]
[CmdletBinding()]
param(
[Parameter(Position = 0)]
[string]$Namespace,
[Parameter(Position = 1)]
[string]$Index = 1
)
k logs -f (kubectl get pod -n $Namespace -o name | Select-Object -Index $Index) -n $Namespace
}
function Get-PodLogStern {
<#
.SYNOPSIS
Get logs of all pods in a namespace using stern utility. https://github.com/stern/stern
.EXAMPLE
kstern mynamespace -Since 10m -State 'running,waiting'
Return logs for namespace "mynamespace", last 10 minutes, containers in state of running or waiting
#>
[Alias('kstern')]
[CmdletBinding()]
param(
[Parameter(Position = 0)]
[string]$Namespace,
# Pull logs since (use 2h, 5m, etc.). Default: 2h (2 hours)
[Parameter(Position = 1)]
[string]$Since = '30m',
# Include only lines container provided regular expression (e.g., "The file uploaded*")
[Parameter(Position = 2)]
[string]$Include,
# Container state to return (running, waiting, terminated, or all)
# Pass in multiple vai single-stringed, comma-separated (e.g. 'running, waiting')
# Pass in 'all' to get everything
[Parameter(Position = 3)]
[string]$State = 'running',
# Output log data to JSON format
[switch]$Output,
# Follow the logs for the namespace
[boolean]$EnableFollow
)
if (kubectl krew info stern) {
if ($Output) {
if ($Include) {
kubectl stern ".*" --namespace $Namespace --since $Since --include $Include --no-follow=true --container-state $State --color=always --timestamps=short --output=json
} else {
k stern ".*" --namespace $Namespace --since $Since --no-follow=true --container-state $State --color=always --timestamps=short --output=json
}
} else {
if ($Include) {
kubectl stern ".*" --namespace $Namespace --since $Since --include $Include --no-follow=true --container-state $State --color=always --timestamps=short
} else {
k stern ".*" --namespace $Namespace --since $Since --no-follow=true --container-state $State --color=always --timestamps=short
}
}
} else {
Write-Warning "Stern utility was not found installed via krew"
}
}
function Get-PodTopMetric {
<#
.SYNOPSIS
Return TOP metrics for a pod in a given namespace
#>
[Alias('kpt')]
[CmdletBinding()]
param(
# Namespace to pull
[Parameter(Position = 0)]
[string]$Namespace,
# Output details on all containers in the pod
[switch]$Containers
)
if ($Containers) {
k top pod -n $Namespace --containers
} else {
k top pod -n $Namespace
}
}
function Get-NodeTopMetric {
<#
.SYNOPSIS
Return TOP metrics for a pod in a given namespace
#>
[Alias('knt')]
[CmdletBinding()]
param()
k top node --show-capacity
}
function Get-PodImage {
<#
.SYNOPSIS
Pulls the image value from each pod in a namespace
.EXAMPLE
Get-PodImage namespace
#>
[Alias('kpi')]
[CmdletBinding()]
param(
[Parameter(Position = 0)]
[string]$Namespace
)
if (Get-Command kubectl -ErrorAction SilentlyContinue) {
k get pods -n $Namespace -o jsonpath='{range .items[*]}{@.metadata.name}{" "}{@.spec.containers[*].image}{"\n"}{end}'
} else {
Write-Warning "kubectl not found"
}
}
function Get-PodResource {
<#
.SYNOPSIS
Pulls the resources attribute of all pods in a namespace
.EXAMPLE
Get-PodImage namespace
podname1 {"limits":{"cpu":"250m","memory":"768M"},"requests":{"cpu":"20m","memory":"350M"}}
podname2 {"limits":{"cpu":"250m","memory":"768M"},"requests":{"cpu":"30m","memory":"400M"}}
#>
[Alias('kpr')]
[CmdletBinding()]
param(
[Parameter(Position = 0)]
[string]$Namespace
)
if (Get-Command kubectl -ErrorAction SilentlyContinue) {
# kubectl get pods <pod name> -n jointventure -o jsonpath='{range .spec.containers[*]}{"Container Name: "}{.name}{"\n"}{"Requests:"}{.resources.requests}{"\n"}{"Limits:"}{.resources.limits}{"\n"}{end}'
k get pods -n $Namespace -o jsonpath='{range .spec.containers[*]}{"Container: "}{.name}{@.metadata.namespace}{"/"}{@.metadata.name}{" "}{@.spec.containers[*].resources}{"\n"}{end}'
} else {
Write-Warning "kubectl not found"
}
}
function New-PodTrace {
<#
.SYNOPSIS
Runs tcpdump on remote pod and writes the output to a local file.
Open in Wireshark after the pod is killed or you kill the sniff execution
#>
[Alias('ksniff')]
[CmdletBinding()]
param(
# Pod name to sniff
[Parameter(Position = 0)]
[string]$PodName,
# Namespace of pod
[Parameter(Position = 1)]
[string]$Namespace
)
k sniff $PodName -n $Namespace -o "c:\tmp\$($PodName).tcpdump"
}
function Get-AzureKeyVaultSecret {
<#
.SYNOPSIS
Retrieve a Secret's value from an Azure Key Vault
.EXAMPLE
Get-AzureKeyVaultSecret kvwhatever mysecert, mysecret2
Grant Key Vault Secrets User to the key vault and retrieves each secret name
#>
[Alias('akvs')]
[CmdletBinding()]
param(
# Key Vault name holding the secret
[Parameter(Position = 0)]
[string]$KeyVaultName,
# Secret name(s) to retrieve plain text values
[Parameter(Position = 1)]
[string[]]$SecretName,
# Just list the secrets
[Parameter(Position = 2)]
[switch]$ListOnly
)
try {
$keyVault = Get-AzKeyVault -VaultName $KeyVaultName -ErrorAction Stop
Write-Verbose ($kv | Out-String)
} catch {
throw "Unable to pull the Key Vault $($_)"
}
<# Grant Key Vault Secrets User #>
# $roleParams = @{
# SignInName = $Username
# RoleDefinitionName = 'Key Vault Secrets User'
# Scope = $keyVault.ResourceId
# ErrorAction = 'Stop'
# }
# try {
# $azRoleAssigned = New-AzRoleAssignment @roleParams
# Write-Verbose ($azRoleAssigned | Out-String)
# Start-Sleep -Seconds 4
# } catch {
# throw "Unable to create role assignment: $($_)"
# }
try {
$kvSecrets = Get-AzKeyVaultSecret -VaultName $keyVault.VaultName -ErrorAction Stop
if ($kvSecrets) {
if ($ListOnly) {
$kvSecrets
} else {
$secrets = $kvSecrets.Where({ $_.Name -in $SecretName })
foreach ($secret in $secrets) {
$plainTextValue = Get-AzKeyVaultSecret -VaultName $keyVault.VaultName -Name $secret.Name -AsPlainText -ErrorAction Stop
if ([string]::IsNullOrEmpty($plainTextValue)) {
Write-Warning "No value found in the secret [$($secret.Name)]"
} else {
[pscustomobject]@{
KeyVaultName = $keyVault.VaultName
SecretName = $secret.Name
Value = $plainTextValue
}
}
}
}
} else {
Write-Warning "No secrets found in vault $($keyVault.VaultName)"
}
} catch {
throw "Issue retrieving secret: $($_)"
} finally {
Remove-AzRoleAssignment @roleParams >$null
}
}
#endregion functions
#Import-Module Az.Tools.Predictor
if ($PSEdition -eq 'Core') {
Set-PSReadLineOption -PredictionSource HistoryAndPlugin
}
# if ((Test-Path $azContextImport) -and (Get-Module Az.Accounts -ListAvailable)) {
# $data = Get-Content $azContextImport | ConvertFrom-Json
# if ($data.Contexts.Count -gt 1) {
# Import-AzContext -Path $azContextImport
# }
# }
<# VS Code Environment #>
# if ($host.Name -eq 'Visual Studio Code Host') {
# if (Import-Module EditorServicesCommandSuite) {
# Import-EditorCommand -Module EditorServicesCommandSuite
# }
# }