-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMicrosoft.PowerShell_profile.ps1
More file actions
1070 lines (922 loc) · 50.7 KB
/
Copy pathMicrosoft.PowerShell_profile.ps1
File metadata and controls
1070 lines (922 loc) · 50.7 KB
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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#requires -Version 7.0
<#
.SYNOPSIS
UltraShell v3.2.0 - PowerShell Profile on Steroids
.DESCRIPTION
Perfil profesional de PowerShell con 60+ funciones para desarrolladores.
Incluye:
- Gestión automática de entornos virtuales Python
- Configuración de Oh My Posh con temas personalizables
- Gestión inteligente de SSH Agent
- Configuración avanzada de PSReadLine
- Integración con Docker, WSL, Git
- Sistema de snippets y logging
- Monitoreo de sistema
- Generador de proyectos profesionales
- Y mucho más...
.AUTHOR
llopgui - https://github.com/llopgui/UltraShell
.VERSION
3.2.0 - UltraShell - PowerShell Profile on Steroids
.LINK
https://github.com/llopgui/UltraShell
#>
# ================================================================================================
# CONFIGURACIÓN GLOBAL
# ================================================================================================
# Codificación UTF-8 para que la consola muestre correctamente acentos y símbolos (ej. "Versión", Oh My Posh)
$OutputEncoding = [System.Text.UTF8Encoding]::new($false)
if ($Host.UI.RawUI) {
try { [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } catch { }
}
# Directorio base del perfil (rutas relativas a este directorio)
$profileDir = if ($PSScriptRoot) { $PSScriptRoot } else { Split-Path $PROFILE -Parent }
# Cache de comandos para evitar llamadas repetidas a Get-Command
$Script:CommandCache = @{}
# Benchmark de carga: registra tiempos de cada módulo
$Script:LoadTimings = @{}
# Defaults de configuración
$Script:Config = @{
ShowMessagesInIDE = $false
OhMyPoshThemesPath = (Join-Path $profileDir 'oh-my-posh-themes')
OhMyPoshThemes = @('space', 'atomic', 'zash', 'night-owl', 'powerlevel10k_rainbow')
CurrentThemeIndex = 0
VenvPaths = @('.venv', 'venv', '.venv-dev', 'env')
PythonProjectFiles = @('requirements.txt', 'setup.py', 'pyproject.toml', 'Pipfile', 'manage.py', 'poetry.lock')
SSHAutoLoadKeys = $false
SSHKeyPaths = @(
(Join-Path $env:USERPROFILE '.ssh\id_ed25519'),
(Join-Path $env:USERPROFILE '.ssh\id_rsa')
)
EnableLogging = $false
LogPath = (Join-Path $env:USERPROFILE 'Documents\PowerShell\Logs\perfil.log')
SnippetsPath = (Join-Path $env:USERPROFILE 'Documents\PowerShell\Snippets')
ProjectTemplatesPath = (Join-Path $profileDir 'templates')
# PSReadLine: None | History | HistoryAndPlugin (sobrescribible en config.psd1)
PSReadLinePredictionSource = 'HistoryAndPlugin'
BenchmarkThresholdMs = 2000
}
# Mejora 1: Cargar config.psd1 externo y combinar con defaults
$configFile = Join-Path $profileDir 'config.psd1'
if (Test-Path $configFile) {
try {
$userConfig = Import-PowerShellDataFile -Path $configFile
foreach ($key in $userConfig.Keys) {
# Solo combinar claves reconocidas en $Script:Config (evita typos y claves extra inesperadas)
if (-not $Script:Config.ContainsKey($key)) {
Write-Warning "config.psd1: clave desconocida ignorada: $key"
continue
}
$value = $userConfig[$key]
# Expandir {USERPROFILE} y {PROFILEDIR} en strings y arrays de strings
$expand = { param($s)
$s -replace '\{USERPROFILE\}', $env:USERPROFILE -replace '\{PROFILEDIR\}', $profileDir
}
if ($value -is [string]) {
$value = & $expand $value
}
elseif ($value -is [object[]]) {
if ($value.Count -gt 0 -and $value[0] -is [string]) {
$value = $value | ForEach-Object { & $expand $_ }
}
}
$Script:Config[$key] = $value
}
}
catch {
Write-Warning "Error al cargar config.psd1: $($_.Exception.Message)"
}
}
# ================================================================================================
# CARGA DE MÓDULOS (con benchmark)
# ================================================================================================
# Orden de carga: Core primero (logging, mensajes), luego el resto
$moduleLoadOrder = @(
'UltraShell.Core', # Logging, mensajes, cache, utilidades, snippets, monitoreo, red, historial
'UltraShell.PSReadLine', # Configuración de línea de comandos
'UltraShell.Python', # Entornos virtuales y utilidades Python
'UltraShell.Env', # Gestión de archivos .env
'UltraShell.Themes', # Oh My Posh, SSH Agent, temas dinámicos
'UltraShell.Dev', # Docker, WSL, Git, Git Stash, Node.js
'UltraShell.Projects' # Motor de templates, New-Project, New-PythonProject
)
# Mejora 6: Medir tiempo de carga de cada módulo
$profileStartTime = [System.Diagnostics.Stopwatch]::StartNew()
foreach ($moduleName in $moduleLoadOrder) {
$modulePath = Join-Path $profileDir "modules\$moduleName.ps1"
if (Test-Path $modulePath) {
$sw = [System.Diagnostics.Stopwatch]::StartNew()
try {
. $modulePath
}
catch {
Write-Warning "No se pudo cargar ${moduleName}: $($_.Exception.Message)"
}
$sw.Stop()
$Script:LoadTimings[$moduleName] = $sw.ElapsedMilliseconds
}
}
# ================================================================================================
# CONFIGURACIÓN DE ALIASES
# ================================================================================================
<#
.SYNOPSIS
Configura aliases útiles para comandos comunes.
.EXAMPLE
Initialize-Aliases
#>
function Initialize-Aliases {
[CmdletBinding()][OutputType([bool])]
param()
$aliasErrors = [System.Collections.Generic.List[string]]::new()
function Set-UltraShellAlias {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$AliasName,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$TargetCommand,
[switch]$OptionalExternalCommand
)
# Alias opcionales (comandos externos) no deben romper la inicialización global.
if ($OptionalExternalCommand -and -not (Get-CachedCommand $TargetCommand)) {
Write-ProfileLog "Alias opcional '$AliasName' omitido: comando '$TargetCommand' no disponible." -Level "Info"
return
}
try {
Set-Alias -Name $AliasName -Value $TargetCommand -Force -Scope Global -ErrorAction Stop
}
catch {
$message = "No se pudo configurar alias '$AliasName' -> '$TargetCommand': $($_.Exception.Message)"
[void]$aliasErrors.Add($message)
Write-ProfileLog $message -Level "Warning"
}
}
# Aliases básicos de sistema
Set-UltraShellAlias -AliasName 'll' -TargetCommand 'Get-ChildItem'
Set-UltraShellAlias -AliasName 'la' -TargetCommand 'Get-ChildItemAll'
Set-UltraShellAlias -AliasName 'which' -TargetCommand 'Get-CommandLocation'
Set-UltraShellAlias -AliasName 'touch' -TargetCommand 'New-FileWithTimestamp'
Set-UltraShellAlias -AliasName 'grep' -TargetCommand 'Select-String'
Set-UltraShellAlias -AliasName 'open' -TargetCommand 'Open-Explorer'
# Aliases de Git
Set-UltraShellAlias -AliasName 'g' -TargetCommand 'git' -OptionalExternalCommand
Set-UltraShellAlias -AliasName 'gs' -TargetCommand 'Get-GitStatus'
Set-UltraShellAlias -AliasName 'gst' -TargetCommand 'Get-GitStatus'
Set-UltraShellAlias -AliasName 'gitcommit' -TargetCommand 'Invoke-QuickCommit'
Set-UltraShellAlias -AliasName 'gitbr' -TargetCommand 'New-GitBranch'
# Aliases de Python
Set-UltraShellAlias -AliasName 'py' -TargetCommand 'python' -OptionalExternalCommand
Set-UltraShellAlias -AliasName 'pup' -TargetCommand 'Update-PipPackage'
# Aliases de productividad
Set-UltraShellAlias -AliasName 'up' -TargetCommand 'Move-Up'
Set-UltraShellAlias -AliasName 'mkcd' -TargetCommand 'New-DirectoryAndEnter'
Set-UltraShellAlias -AliasName 'fsize' -TargetCommand 'Get-DirectorySize'
Set-UltraShellAlias -AliasName 'ff' -TargetCommand 'Find-FilesByName'
Set-UltraShellAlias -AliasName 'devinfo' -TargetCommand 'Get-DevEnvironmentInfo'
# Aliases de Docker
Set-UltraShellAlias -AliasName 'dps' -TargetCommand 'Get-DockerStatus'
Set-UltraShellAlias -AliasName 'dcu' -TargetCommand 'Start-DockerCompose'
Set-UltraShellAlias -AliasName 'dcd' -TargetCommand 'Stop-DockerCompose'
Set-UltraShellAlias -AliasName 'dockerfile' -TargetCommand 'New-Dockerfile'
# Aliases de WSL
Set-UltraShellAlias -AliasName 'wsl-here' -TargetCommand 'Open-WSL'
Set-UltraShellAlias -AliasName 'wslrun' -TargetCommand 'Invoke-WSLCommand'
# Alias wg: definido en UltraShell.Dev.ps1 al cargar el módulo (si winget existe)
# Aliases de monitoreo
Set-UltraShellAlias -AliasName 'topcpu' -TargetCommand 'Get-TopProcessesByCPU'
Set-UltraShellAlias -AliasName 'topmem' -TargetCommand 'Get-TopProcessesByMemory'
Set-UltraShellAlias -AliasName 'diskinfo' -TargetCommand 'Get-DiskUsage'
Set-UltraShellAlias -AliasName 'sysinfo' -TargetCommand 'Get-SystemInfo'
# Aliases de .env
Set-UltraShellAlias -AliasName 'env-load' -TargetCommand 'Import-EnvFile'
Set-UltraShellAlias -AliasName 'env-show' -TargetCommand 'Show-EnvFile'
Set-UltraShellAlias -AliasName 'env-edit' -TargetCommand 'Edit-EnvFile'
# Aliases de Git Stash
Set-UltraShellAlias -AliasName 'gss' -TargetCommand 'Save-GitStash'
Set-UltraShellAlias -AliasName 'gsp' -TargetCommand 'Restore-GitStash'
Set-UltraShellAlias -AliasName 'gsl' -TargetCommand 'Get-GitStashList'
# Aliases de historial y red
Set-UltraShellAlias -AliasName 'cmdstats' -TargetCommand 'Get-CommandStats'
# Aliases de temas
Set-UltraShellAlias -AliasName 'theme' -TargetCommand 'Switch-OhMyPoshTheme'
Set-UltraShellAlias -AliasName 'next-theme' -TargetCommand 'Invoke-NextOhMyPoshTheme'
# Aliases de snippets
Set-UltraShellAlias -AliasName 'snip-save' -TargetCommand 'Save-Snippet'
Set-UltraShellAlias -AliasName 'snip-get' -TargetCommand 'Get-Snippet'
Set-UltraShellAlias -AliasName 'snip-list' -TargetCommand 'Get-AllSnippets'
if ($aliasErrors.Count -gt 0) {
Write-ProfileMessage "Aliases configurados con advertencias ($($aliasErrors.Count)). Revisa el log para más detalles." -Level "Warning"
return $false
}
Write-ProfileMessage "Aliases configurados" -Level "Success"
return $true
}
# ================================================================================================
# TAB COMPLETION (Mejora 5)
# ================================================================================================
# ArgumentCompleter dinámico para -Template: busca templates JSON disponibles
$templateCompleter = {
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)
$templatesRoot = $Script:Config.ProjectTemplatesPath
if (-not (Test-Path -LiteralPath $templatesRoot)) { return }
try {
# Misma raíz absoluta que FullName de Get-ChildItem; evita Substring incorrecto si la config era relativa.
$resolvedRoot = (Resolve-Path -LiteralPath $templatesRoot -ErrorAction Stop).Path.TrimEnd('\')
}
catch {
return
}
Get-ChildItem -Path $resolvedRoot -Filter '*.json' -Recurse -File -ErrorAction SilentlyContinue |
ForEach-Object {
$name = $_.FullName.Substring($resolvedRoot.Length + 1).TrimStart('\') -replace '\\', '/' -replace '\.json$', ''
$name
} |
Where-Object { $_ -like "$wordToComplete*" } |
ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }
}
Register-ArgumentCompleter -CommandName New-Project, Init-Project -ParameterName Template -ScriptBlock $templateCompleter
Register-ArgumentCompleter -CommandName New-PythonProject -ParameterName Template -ScriptBlock $templateCompleter
Register-ArgumentCompleter -CommandName New-PowerShellProject -ParameterName Template -ScriptBlock $templateCompleter
Register-ArgumentCompleter -CommandName New-NodeProject -ParameterName Template -ScriptBlock $templateCompleter
# ================================================================================================
# AUTO-UPDATE (Mejora 2)
# ================================================================================================
<#
.SYNOPSIS
Copia de forma segura el contenido de un directorio.
.DESCRIPTION
Crea el directorio de destino si no existe y replica todos los elementos del origen.
Se utiliza para preparar promociones y restauraciones con rollback.
.PARAMETER SourceDir
Directorio origen.
.PARAMETER DestinationDir
Directorio destino.
#>
function Copy-UltraShellDirectoryContent {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$SourceDir,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$DestinationDir
)
if (-not (Test-Path -LiteralPath $DestinationDir -PathType Container)) {
New-Item -Path $DestinationDir -ItemType Directory -Force -ErrorAction Stop | Out-Null
}
foreach ($entry in (Get-ChildItem -LiteralPath $SourceDir -Force -ErrorAction Stop)) {
Copy-Item -LiteralPath $entry.FullName -Destination $DestinationDir -Recurse -Force -ErrorAction Stop
}
}
<#
.SYNOPSIS
Verifica si un repositorio local apunta al origen oficial confiable.
.DESCRIPTION
Valida `remote.origin.url` contra el repositorio oficial de UltraShell para evitar
ejecutar instaladores desde un fallback local no confiable.
.PARAMETER RepositoryPath
Ruta del repositorio a validar.
#>
function Test-UltraShellTrustedRepositoryOrigin {
[CmdletBinding()]
[OutputType([bool])]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$RepositoryPath
)
if (-not (Get-CachedCommand 'git')) {
return $false
}
if (-not (Test-Path -LiteralPath (Join-Path $RepositoryPath '.git'))) {
return $false
}
Push-Location $RepositoryPath
try {
$originUrl = git config --get remote.origin.url 2>$null
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($originUrl)) {
return $false
}
$trustedPattern = '(?i)^(https://|ssh://git@|git@)github\.com[:/]llopgui/UltraShell(?:\.git)?/?$'
return ($originUrl.Trim() -match $trustedPattern)
}
finally {
Pop-Location
}
}
<#
.SYNOPSIS
Promociona artefactos de actualización con rollback transaccional.
.DESCRIPTION
Aplica perfil, host config, módulos y templates con seguridad ante fallos:
- Respalda el estado previo
- Prepara artefactos antes de tocar destino
- Si falla cualquier paso, restaura el estado anterior
Además conserva `templates/custom` para no perder templates personalizados.
.PARAMETER SourceProfilePath
Ruta del perfil en staging.
.PARAMETER SourceHostConfigPath
Ruta del powershell.config.json en staging.
.PARAMETER SourceModulesDir
Directorio de módulos en staging.
.PARAMETER SourceTemplatesDir
Directorio de templates en staging.
.PARAMETER DestinationProfilePath
Ruta final del perfil (`$PROFILE`).
.PARAMETER DestinationProfileDir
Directorio base del perfil.
#>
function Invoke-UltraShellUpdatePromotion {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$SourceProfilePath,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$SourceHostConfigPath,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$SourceModulesDir,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$SourceTemplatesDir,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$DestinationProfilePath,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$DestinationProfileDir
)
$modulesDest = Join-Path $DestinationProfileDir 'modules'
$templatesDest = Join-Path $DestinationProfileDir 'templates'
$hostConfigDest = Join-Path $DestinationProfileDir 'powershell.config.json'
$customTemplatesDest = Join-Path $templatesDest 'custom'
$transactionRoot = Join-Path ([System.IO.Path]::GetTempPath()) "ultrashell-update-promotion-$([guid]::NewGuid().ToString('N'))"
$backupRoot = Join-Path $transactionRoot 'backup'
$preparedRoot = Join-Path $transactionRoot 'prepared'
$preparedModules = Join-Path $preparedRoot 'modules'
$preparedTemplates = Join-Path $preparedRoot 'templates'
$managedModuleNames = @()
$state = @{
ProfileExisted = (Test-Path -LiteralPath $DestinationProfilePath -PathType Leaf)
HostConfigExisted = (Test-Path -LiteralPath $hostConfigDest -PathType Leaf)
ModulesExisted = (Test-Path -LiteralPath $modulesDest -PathType Container)
TemplatesExisted = (Test-Path -LiteralPath $templatesDest -PathType Container)
}
try {
New-Item -Path $backupRoot -ItemType Directory -Force -ErrorAction Stop | Out-Null
New-Item -Path $preparedModules -ItemType Directory -Force -ErrorAction Stop | Out-Null
New-Item -Path $preparedTemplates -ItemType Directory -Force -ErrorAction Stop | Out-Null
# Solo gestionamos módulos de UltraShell para no tocar módulos globales del usuario.
$managedModuleNames = Get-ChildItem -LiteralPath $SourceModulesDir -Force -ErrorAction Stop |
Select-Object -ExpandProperty Name
if ($state.ProfileExisted) {
Copy-Item -Path $DestinationProfilePath -Destination (Join-Path $backupRoot 'Microsoft.PowerShell_profile.ps1') -Force -ErrorAction Stop
}
if ($state.HostConfigExisted) {
Copy-Item -Path $hostConfigDest -Destination (Join-Path $backupRoot 'powershell.config.json') -Force -ErrorAction Stop
}
if ($state.ModulesExisted) {
$modulesBackupDir = Join-Path $backupRoot 'modules'
New-Item -Path $modulesBackupDir -ItemType Directory -Force -ErrorAction Stop | Out-Null
foreach ($managedModuleName in $managedModuleNames) {
$existingManagedModulePath = Join-Path $modulesDest $managedModuleName
if (Test-Path -LiteralPath $existingManagedModulePath) {
Copy-Item -LiteralPath $existingManagedModulePath -Destination $modulesBackupDir -Recurse -Force -ErrorAction Stop
}
}
}
if ($state.TemplatesExisted) {
Copy-Item -LiteralPath $templatesDest -Destination $backupRoot -Recurse -Force -ErrorAction Stop
}
Copy-UltraShellDirectoryContent -SourceDir $SourceModulesDir -DestinationDir $preparedModules
Copy-UltraShellDirectoryContent -SourceDir $SourceTemplatesDir -DestinationDir $preparedTemplates
# Preservar los templates del usuario antes del reemplazo del árbol de templates.
if (Test-Path -LiteralPath $customTemplatesDest -PathType Container) {
$preparedCustomDir = Join-Path $preparedTemplates 'custom'
New-Item -Path $preparedCustomDir -ItemType Directory -Force -ErrorAction Stop | Out-Null
Copy-UltraShellDirectoryContent -SourceDir $customTemplatesDest -DestinationDir $preparedCustomDir
}
Copy-Item -Path $SourceProfilePath -Destination $DestinationProfilePath -Force -ErrorAction Stop
Copy-Item -Path $SourceHostConfigPath -Destination $hostConfigDest -Force -ErrorAction Stop
if (-not (Test-Path -LiteralPath $modulesDest -PathType Container)) {
New-Item -Path $modulesDest -ItemType Directory -Force -ErrorAction Stop | Out-Null
}
foreach ($managedModuleName in $managedModuleNames) {
$managedModulePath = Join-Path $modulesDest $managedModuleName
if (Test-Path -LiteralPath $managedModulePath) {
Remove-Item -LiteralPath $managedModulePath -Recurse -Force -ErrorAction Stop
}
}
Copy-UltraShellDirectoryContent -SourceDir $preparedModules -DestinationDir $modulesDest
if (Test-Path -LiteralPath $templatesDest -PathType Container) {
Remove-Item -LiteralPath $templatesDest -Recurse -Force -ErrorAction Stop
}
New-Item -Path $templatesDest -ItemType Directory -Force -ErrorAction Stop | Out-Null
Copy-UltraShellDirectoryContent -SourceDir $preparedTemplates -DestinationDir $templatesDest
}
catch {
Write-Host "Error en la promoción segura de actualización: $($_.Exception.Message)" -ForegroundColor Red
Write-Host "Intentando rollback al estado previo..." -ForegroundColor Yellow
try {
$profileBackupPath = Join-Path $backupRoot 'Microsoft.PowerShell_profile.ps1'
$hostConfigBackupPath = Join-Path $backupRoot 'powershell.config.json'
$modulesBackupPath = Join-Path $backupRoot 'modules'
$templatesBackupPath = Join-Path $backupRoot 'templates'
if ($state.ProfileExisted) {
if (Test-Path -LiteralPath $profileBackupPath -PathType Leaf) {
Copy-Item -Path $profileBackupPath -Destination $DestinationProfilePath -Force -ErrorAction Stop
}
else {
# Protección: no eliminar destino cuando falta el respaldo esperado.
Write-Host "Rollback: se conserva '$DestinationProfilePath' porque no existe backup válido del perfil." -ForegroundColor Yellow
}
}
elseif (Test-Path -LiteralPath $DestinationProfilePath -PathType Leaf) {
Remove-Item -LiteralPath $DestinationProfilePath -Force -ErrorAction Stop
}
if ($state.HostConfigExisted) {
if (Test-Path -LiteralPath $hostConfigBackupPath -PathType Leaf) {
Copy-Item -Path $hostConfigBackupPath -Destination $hostConfigDest -Force -ErrorAction Stop
}
else {
Write-Host "Rollback: se conserva '$hostConfigDest' porque no existe backup válido de powershell.config.json." -ForegroundColor Yellow
}
}
elseif (Test-Path -LiteralPath $hostConfigDest -PathType Leaf) {
Remove-Item -LiteralPath $hostConfigDest -Force -ErrorAction Stop
}
if ($state.ModulesExisted) {
if (Test-Path -LiteralPath $modulesBackupPath -PathType Container) {
if (-not (Test-Path -LiteralPath $modulesDest -PathType Container)) {
New-Item -Path $modulesDest -ItemType Directory -Force -ErrorAction Stop | Out-Null
}
foreach ($managedModuleName in $managedModuleNames) {
$managedModulePath = Join-Path $modulesDest $managedModuleName
if (Test-Path -LiteralPath $managedModulePath) {
Remove-Item -LiteralPath $managedModulePath -Recurse -Force -ErrorAction Stop
}
}
Copy-UltraShellDirectoryContent -SourceDir $modulesBackupPath -DestinationDir $modulesDest
}
else {
Write-Host "Rollback: se conserva '$modulesDest' porque no existe backup válido de modules." -ForegroundColor Yellow
}
}
elseif (Test-Path -LiteralPath $modulesDest -PathType Container) {
foreach ($managedModuleName in $managedModuleNames) {
$managedModulePath = Join-Path $modulesDest $managedModuleName
if (Test-Path -LiteralPath $managedModulePath) {
Remove-Item -LiteralPath $managedModulePath -Recurse -Force -ErrorAction Stop
}
}
}
if ($state.TemplatesExisted) {
if (Test-Path -LiteralPath $templatesBackupPath -PathType Container) {
if (Test-Path -LiteralPath $templatesDest -PathType Container) {
Remove-Item -LiteralPath $templatesDest -Recurse -Force -ErrorAction Stop
}
Copy-Item -LiteralPath $templatesBackupPath -Destination $DestinationProfileDir -Recurse -Force -ErrorAction Stop
}
else {
Write-Host "Rollback: se conserva '$templatesDest' porque no existe backup válido de templates." -ForegroundColor Yellow
}
}
elseif (Test-Path -LiteralPath $templatesDest -PathType Container) {
Remove-Item -LiteralPath $templatesDest -Recurse -Force -ErrorAction Stop
}
}
catch {
Write-Host "Rollback incompleto: $($_.Exception.Message)" -ForegroundColor Red
}
throw
}
finally {
Remove-Item -LiteralPath $transactionRoot -Recurse -Force -ErrorAction SilentlyContinue
}
}
<#
.SYNOPSIS
Actualiza UltraShell a la última versión desde GitHub.
.DESCRIPTION
Si el perfil se instaló desde un repositorio Git, hace git pull y reinstala.
Si se instaló por descarga, descarga la última versión de los archivos.
Para apuntar al clon local sin .git bajo el perfil, define ULTRASHELL_REPO_ROOT (prioritario) o usa el fallback USERPROFILE\Desktop\WORKSPACE\UltraShell.
.PARAMETER Force
No pide confirmación antes de actualizar.
.EXAMPLE
Update-UltraShell
Update-UltraShell -Force
#>
function Update-UltraShell {
[CmdletBinding()]
param([switch]$Force)
$repoDir = $null
$repoSource = $null
# Buscar si el perfil está en un repositorio Git
$possibleRepo = $profileDir
if (Test-Path (Join-Path $possibleRepo '.git')) {
$repoDir = $possibleRepo
$repoSource = 'profile'
}
else {
# Prioridad: ULTRASHELL_REPO_ROOT explícito del usuario.
$candidate = $env:ULTRASHELL_REPO_ROOT
if ($candidate -and (Test-Path (Join-Path $candidate '.git'))) {
$repoDir = $candidate
$repoSource = 'env'
}
elseif ($candidate) {
Write-Host "ULTRASHELL_REPO_ROOT no apunta a un repositorio Git válido; se omitirá." -ForegroundColor Yellow
}
if (-not $repoDir) {
# Fallback documentado: solo confiable si su remote.origin coincide con el repo oficial.
$fallbackCandidate = Join-Path $env:USERPROFILE 'Desktop\WORKSPACE\UltraShell'
if ((Test-Path (Join-Path $fallbackCandidate '.git')) -and (Test-UltraShellTrustedRepositoryOrigin -RepositoryPath $fallbackCandidate)) {
$repoDir = $fallbackCandidate
$repoSource = 'fallback'
}
elseif (Test-Path (Join-Path $fallbackCandidate '.git')) {
Write-Host "Se ignoró el fallback local porque su origen Git no coincide con llopgui/UltraShell." -ForegroundColor Yellow
}
}
}
if ($repoDir -and -not (Get-CachedCommand 'git')) {
Write-Host "Git no está disponible en PATH; se usará actualización por descarga." -ForegroundColor Yellow
$repoDir = $null
$repoSource = $null
}
if ($repoDir) {
# Modo Git: pull + reinstalar
Write-Host "Actualizando UltraShell desde repositorio Git..." -ForegroundColor Cyan
Write-Host " Repositorio: $repoDir" -ForegroundColor Gray
if ($repoSource -eq 'fallback') {
Write-Host " Origen fallback validado contra repositorio oficial." -ForegroundColor Gray
}
if (-not $Force) {
$response = Read-Host "¿Continuar con la actualización? (S/n)"
if ($response -eq 'n' -or $response -eq 'N') {
Write-Host "Actualización cancelada." -ForegroundColor Yellow
return
}
}
Push-Location $repoDir
try {
$pullOutput = git pull 2>&1
if ($LASTEXITCODE -ne 0) {
Write-Host "Error en git pull: $pullOutput" -ForegroundColor Red
return
}
Write-Host $pullOutput -ForegroundColor Gray
# Reinstalar desde el repo
$installScript = Join-Path $repoDir 'install.ps1'
if (Test-Path $installScript) {
$pwshCommand = Get-Command pwsh -ErrorAction SilentlyContinue
if (-not $pwshCommand) {
Write-Host "No se encontró 'pwsh' para ejecutar install.ps1 de forma aislada." -ForegroundColor Red
return
}
$installerArgs = @('-NoLogo', '-NoProfile')
if ($IsWindows) {
$installerArgs += @('-ExecutionPolicy', 'Bypass')
}
# Evita prompts de dependencias durante update para mantener ejecución no interactiva.
$installerArgs += @('-File', $installScript, '-Local', '-NoBackup', '-SkipDependencies')
# Ejecutar el instalador en proceso aislado evita que un 'exit' cierre esta sesión.
& $pwshCommand.Source @installerArgs
$installExitCode = $LASTEXITCODE
if ($installExitCode -ne 0) {
Write-Host "`ninstall.ps1 devolvió código $installExitCode; la actualización fue abortada." -ForegroundColor Red
return
}
}
Write-Host "`n✓ UltraShell actualizado. Recarga con: . `$PROFILE" -ForegroundColor Green
}
finally {
Pop-Location
}
}
else {
# Modo descarga: descargar última versión
Write-Host "Actualizando UltraShell por descarga..." -ForegroundColor Cyan
if (-not $Force) {
$response = Read-Host "¿Descargar última versión desde GitHub? (S/n)"
if ($response -eq 'n' -or $response -eq 'N') {
Write-Host "Actualización cancelada." -ForegroundColor Yellow
return
}
}
$repoUrl = "https://raw.githubusercontent.com/llopgui/UltraShell/main"
$staging = Join-Path ([System.IO.Path]::GetTempPath()) "ultrashell-update-$([guid]::NewGuid().ToString('N'))"
New-Item -Path $staging -ItemType Directory -Force | Out-Null
try {
$stagingProfile = Join-Path $staging 'Microsoft.PowerShell_profile.ps1'
Invoke-WebRequest -Uri "$repoUrl/Microsoft.PowerShell_profile.ps1" -OutFile $stagingProfile -UseBasicParsing -ErrorAction Stop
$stagingHostCfg = Join-Path $staging 'powershell.config.json'
Invoke-WebRequest -Uri "$repoUrl/powershell.config.json" -OutFile $stagingHostCfg -UseBasicParsing -ErrorAction Stop
$stagingMods = Join-Path $staging 'modules'
New-Item -Path $stagingMods -ItemType Directory -Force | Out-Null
foreach ($mod in $moduleLoadOrder) {
Invoke-WebRequest -Uri "$repoUrl/modules/$mod.ps1" -OutFile (Join-Path $stagingMods "$mod.ps1") -UseBasicParsing -ErrorAction Stop
}
$stagingTplRoot = Join-Path $staging 'templates'
$templateFiles = @('python/fastapi.json', 'python/basic.json', 'powershell/module.json', 'nodejs/basic.json', 'rust/basic.json', 'go/basic.json', 'custom/example.json')
foreach ($tpl in $templateFiles) {
$destPath = Join-Path $stagingTplRoot $tpl
$destDir = Split-Path $destPath -Parent
if (-not (Test-Path -LiteralPath $destDir)) { New-Item -Path $destDir -ItemType Directory -Force | Out-Null }
Invoke-WebRequest -Uri "$repoUrl/templates/$tpl" -OutFile $destPath -UseBasicParsing -ErrorAction Stop
}
Invoke-UltraShellUpdatePromotion `
-SourceProfilePath $stagingProfile `
-SourceHostConfigPath $stagingHostCfg `
-SourceModulesDir $stagingMods `
-SourceTemplatesDir $stagingTplRoot `
-DestinationProfilePath $PROFILE `
-DestinationProfileDir $profileDir
$configDest = Join-Path $profileDir 'config.psd1'
if (-not (Test-Path -LiteralPath $configDest)) {
try {
$stagingCfg = Join-Path $staging 'config.psd1'
Invoke-WebRequest -Uri "$repoUrl/config.psd1" -OutFile $stagingCfg -UseBasicParsing -ErrorAction Stop
Copy-Item -Path $stagingCfg -Destination $configDest -Force
}
catch {
Write-Host "No se pudo descargar config.psd1 (opcional)." -ForegroundColor Yellow
}
}
Write-Host "`n✓ UltraShell actualizado (perfil, host JSON, módulos y templates). Recarga con: . `$PROFILE" -ForegroundColor Green
}
catch {
Write-Host "Error al actualizar por descarga: $($_.Exception.Message)" -ForegroundColor Red
Write-Host "Actualización abortada. No se aplicará estado de éxito si falla la promoción." -ForegroundColor Yellow
Write-Host "Intenta: git clone https://github.com/llopgui/UltraShell && cd UltraShell && .\install.ps1 -Local" -ForegroundColor Yellow
}
finally {
Remove-Item -LiteralPath $staging -Recurse -Force -ErrorAction SilentlyContinue
}
}
}
# ================================================================================================
# AYUDA DEL PERFIL
# ================================================================================================
<#
.SYNOPSIS
Muestra la ayuda con todos los comandos y aliases disponibles del perfil.
.EXAMPLE
Show-ProfileHelp
help-profile
#>
function Show-ProfileHelp {
[CmdletBinding()]
param()
Write-Host "`n╔══════════════════════════════════════════════════════════════╗" -ForegroundColor Cyan
Write-Host "║ ⚡ UltraShell v3.2.0 - Ayuda ║" -ForegroundColor Cyan
Write-Host "╚══════════════════════════════════════════════════════════════╝`n" -ForegroundColor Cyan
Write-Host "═══ NAVEGACIÓN Y ARCHIVOS ═══" -ForegroundColor Yellow
Write-Host " ll " -NoNewline -ForegroundColor Green; Write-Host "- Lista archivos en el directorio actual"
Write-Host " la " -NoNewline -ForegroundColor Green; Write-Host "- Lista todos los archivos (incluyendo ocultos)"
Write-Host " touch <archivo> " -NoNewline -ForegroundColor Green; Write-Host "- Crea archivo o actualiza timestamp"
Write-Host " which <comando> " -NoNewline -ForegroundColor Green; Write-Host "- Muestra ubicación de un comando"
Write-Host " open [ruta] " -NoNewline -ForegroundColor Green; Write-Host "- Abre explorador en el directorio"
Write-Host " up [niveles] " -NoNewline -ForegroundColor Green; Write-Host "- Sube N niveles en directorios"
Write-Host " mkcd <dir> " -NoNewline -ForegroundColor Green; Write-Host "- Crea directorio y navega a él"
Write-Host " ff <patrón> " -NoNewline -ForegroundColor Green; Write-Host "- Busca archivos por nombre"
Write-Host " fsize [ruta] " -NoNewline -ForegroundColor Green; Write-Host "- Calcula tamaño de directorio"
Write-Host "`n═══ GIT ═══" -ForegroundColor Yellow
Write-Host " g " -NoNewline -ForegroundColor Green; Write-Host "- Alias de git"
Write-Host " gs / gst " -NoNewline -ForegroundColor Green; Write-Host "- Estado de Git detallado y colorido"
Write-Host " gitcommit <msg> " -NoNewline -ForegroundColor Green; Write-Host "- Añade todo y hace commit"
Write-Host " gitbr <nombre> " -NoNewline -ForegroundColor Green; Write-Host "- Crea y cambia a nueva branch"
Write-Host "`n═══ PYTHON ═══" -ForegroundColor Yellow
Write-Host " py " -NoNewline -ForegroundColor Green; Write-Host "- Alias de python"
Write-Host " pup " -NoNewline -ForegroundColor Green; Write-Host "- Actualiza pip a última versión"
Write-Host " Clear-PythonCache" -NoNewline -ForegroundColor Green; Write-Host " - Limpia archivos __pycache__"
Write-Host "`n═══ UTILIDADES ═══" -ForegroundColor Yellow
Write-Host " devinfo " -NoNewline -ForegroundColor Green; Write-Host "- Muestra info del entorno de desarrollo"
Write-Host " Clear-PSHistory " -NoNewline -ForegroundColor Green; Write-Host "- Limpia historial de PowerShell"
Write-Host " Update-UltraShell" -NoNewline -ForegroundColor Green; Write-Host " - Actualiza UltraShell a última versión"
Write-Host " Show-ProfileHelp" -NoNewline -ForegroundColor Green; Write-Host " - Muestra esta ayuda"
Write-Host "`n═══ DOCKER ═══" -ForegroundColor Yellow
Write-Host " dps " -NoNewline -ForegroundColor Green; Write-Host "- Estado de contenedores Docker"
Write-Host " dcu " -NoNewline -ForegroundColor Green; Write-Host "- Docker Compose up"
Write-Host " dcd " -NoNewline -ForegroundColor Green; Write-Host "- Docker Compose down"
Write-Host " Clear-DockerResources" -NoNewline -ForegroundColor Green; Write-Host " - Limpia recursos Docker no usados"
Write-Host " dockerfile " -NoNewline -ForegroundColor Green; Write-Host "- Genera Dockerfile (FastAPI/Python/Node)"
Write-Host "`n═══ WSL ═══" -ForegroundColor Yellow
Write-Host " wsl-here " -NoNewline -ForegroundColor Green; Write-Host "- Abre WSL en directorio actual"
Write-Host " wslrun <cmd> " -NoNewline -ForegroundColor Green; Write-Host "- Ejecuta comando en WSL"
Write-Host " Get-WSLDistributions" -NoNewline -ForegroundColor Green; Write-Host " - Lista distros WSL instaladas"
Write-Host "`n═══ WINGET ═══" -ForegroundColor Yellow
Write-Host " wg " -NoNewline -ForegroundColor Green; Write-Host "- Alias de winget"
Write-Host " Install-WingetPackage <id> " -NoNewline -ForegroundColor Green; Write-Host "- Instala paquete"
Write-Host " Search-WingetPackage <query> " -NoNewline -ForegroundColor Green; Write-Host "- Busca paquetes"
Write-Host " Update-WingetPackages " -NoNewline -ForegroundColor Green; Write-Host "- Actualiza todos los paquetes"
Write-Host "`n═══ MONITOREO ═══" -ForegroundColor Yellow
Write-Host " sysinfo " -NoNewline -ForegroundColor Green; Write-Host "- Información completa del sistema"
Write-Host " topcpu [n] " -NoNewline -ForegroundColor Green; Write-Host "- Top procesos por CPU"
Write-Host " topmem [n] " -NoNewline -ForegroundColor Green; Write-Host "- Top procesos por memoria"
Write-Host " diskinfo " -NoNewline -ForegroundColor Green; Write-Host "- Uso de disco"
Write-Host "`n═══ TEMAS ═══" -ForegroundColor Yellow
Write-Host " theme [n] " -NoNewline -ForegroundColor Green; Write-Host "- Cambia tema Oh My Posh"
Write-Host " next-theme " -NoNewline -ForegroundColor Green; Write-Host "- Siguiente tema"
Write-Host " Install-OhMyPoshTheme <name>" -NoNewline -ForegroundColor Green; Write-Host " - Descarga tema a carpeta local"
Write-Host "`n═══ SNIPPETS ═══" -ForegroundColor Yellow
Write-Host " snip-save <name> <cmd>" -NoNewline -ForegroundColor Green; Write-Host " - Guarda snippet"
Write-Host " snip-get <name> " -NoNewline -ForegroundColor Green; Write-Host "- Obtiene snippet"
Write-Host " snip-list " -NoNewline -ForegroundColor Green; Write-Host "- Lista snippets"
Write-Host " Remove-Snippet <name>" -NoNewline -ForegroundColor Green; Write-Host " - Elimina snippet"
Write-Host "`n═══ PROYECTOS ═══" -ForegroundColor Yellow
Write-Host " New-PythonProject <name> " -NoNewline -ForegroundColor Green; Write-Host " - Proyecto Python (default: FastAPI)"
Write-Host " New-PowerShellProject <name> " -NoNewline -ForegroundColor Green; Write-Host " - Módulo PowerShell profesional"
Write-Host " New-NodeProject <name> " -NoNewline -ForegroundColor Green; Write-Host " - Proyecto Node.js"
Write-Host " New-Project -Name <n> -Template <t>" -NoNewline -ForegroundColor Green; Write-Host " - Desde cualquier template JSON"
Write-Host " New-Project -Interactive " -NoNewline -ForegroundColor Green; Write-Host " - Modo interactivo guiado"
Write-Host " Get-ProjectTemplate " -NoNewline -ForegroundColor Green; Write-Host " - Lista templates disponibles"
Write-Host "`n═══ PYTHON ═══" -ForegroundColor Yellow
Write-Host " Init-UvProject " -NoNewline -ForegroundColor Green; Write-Host "- Inicializa proyecto Python con uv (venv + sync)"
Write-Host " Enable-PythonVirtualEnv" -NoNewline -ForegroundColor Green; Write-Host " - Activa entorno virtual del proyecto"
Write-Host "`n═══ ENTORNO (.env) ═══" -ForegroundColor Yellow
Write-Host " env-load [ruta] " -NoNewline -ForegroundColor Green; Write-Host "- Carga variables desde archivo .env"
Write-Host " env-show [ruta] " -NoNewline -ForegroundColor Green; Write-Host "- Muestra variables del .env (oculta valores)"
Write-Host " env-edit [ruta] " -NoNewline -ForegroundColor Green; Write-Host "- Abre .env en editor por defecto"
Write-Host "`n═══ RED ═══" -ForegroundColor Yellow
Write-Host " Test-Port <host> <port>" -NoNewline -ForegroundColor Green; Write-Host " - Verifica si un puerto está abierto"
Write-Host " Get-PublicIP " -NoNewline -ForegroundColor Green; Write-Host "- Muestra tu IP pública"
Write-Host " Test-WebEndpoint <url>" -NoNewline -ForegroundColor Green; Write-Host " - Verifica estado de un endpoint HTTP"
Write-Host "`n═══ GIT STASH ═══" -ForegroundColor Yellow
Write-Host " gss [mensaje] " -NoNewline -ForegroundColor Green; Write-Host "- Guarda cambios en stash"
Write-Host " gsp [índice] " -NoNewline -ForegroundColor Green; Write-Host "- Restaura stash"
Write-Host " gsl " -NoNewline -ForegroundColor Green; Write-Host "- Lista stashes guardados"
Write-Host "`n═══ HISTORIAL ═══" -ForegroundColor Yellow
Write-Host " cmdstats " -NoNewline -ForegroundColor Green; Write-Host "- Estadísticas de comandos más usados"
Write-Host "`n═══ LOGGING ═══" -ForegroundColor Yellow
Write-Host " Set-ProfileLogging -Enable `$true" -NoNewline -ForegroundColor Green; Write-Host " - Activa/desactiva logging"
Write-Host " Show-ProfileLog " -NoNewline -ForegroundColor Green; Write-Host "- Muestra el log del perfil"
Write-Host "`n╔══════════════════════════════════════════════════════════════╗" -ForegroundColor Cyan
Write-Host "║ ⚡ UltraShell v3.2.0 - Usa 'Get-Help <función>' ║" -ForegroundColor Cyan
Write-Host "║ 📚 https://github.com/llopgui/UltraShell ║" -ForegroundColor Cyan
Write-Host "╚══════════════════════════════════════════════════════════════╝`n" -ForegroundColor Cyan
}
# Alias para la ayuda
Set-Alias -Name 'help-profile' -Value Show-ProfileHelp -Force -Scope Global
Set-Alias -Name 'profile-help' -Value Show-ProfileHelp -Force -Scope Global
# ================================================================================================
# INFORMACIÓN DEL SISTEMA (inicio)
# ================================================================================================
<#
.SYNOPSIS
Muestra información relevante del sistema y versiones de componentes UltraShell al iniciar.
.DESCRIPTION
Lista versiones de: PowerShell, Python, Git, Node.js, winget, Docker, oh-my-posh y WSL.
Usa Get-CachedCommand para evitar llamadas repetidas. Muestra "No disponible" si no está instalado.
.EXAMPLE
Show-SystemInformation
#>
function Show-SystemInformation {
[CmdletBinding()]
param()
if (-not (Test-ShouldShowMessages)) { return }
try {
Write-ProfileMessage "=== INFORMACIÓN DEL SISTEMA ===" -Level "Info" -Force
Write-ProfileMessage "PowerShell: $($PSVersionTable.PSVersion) ($($PSVersionTable.PSEdition))" -Level "Info" -Force
# Python (con cache)
if (-not $Script:PythonVersion) {
if (Get-CachedCommand 'python') {
$pythonVersionOutput = python --version 2>$null
if ($LASTEXITCODE -eq 0 -and $pythonVersionOutput) {
$Script:PythonVersion = $pythonVersionOutput.Trim()
}
else {
$Script:PythonVersion = "No disponible"
}
}
else {
$Script:PythonVersion = "No disponible"
}
}
Write-ProfileMessage "Python: $Script:PythonVersion" -Level "Info" -Force
# Git
$gitVer = if (Get-CachedCommand 'git') {
$v = git --version 2>$null
if ($LASTEXITCODE -eq 0 -and $v) { $v.Replace('git version ', '').Trim() } else { "No disponible" }
} else { "No disponible" }
Write-ProfileMessage "Git: $gitVer" -Level "Info" -Force
# Node.js
$nodeVer = if (Get-CachedCommand 'node') {
$v = node --version 2>$null
if ($LASTEXITCODE -eq 0 -and $v) { $v.Trim() } else { "No disponible" }
} else { "No disponible" }
Write-ProfileMessage "Node.js: $nodeVer" -Level "Info" -Force
# winget
$wingetVer = if (Get-CachedCommand 'winget') {
$v = winget --version 2>$null
if ($LASTEXITCODE -eq 0 -and $v) { $v.Trim() } else { "Instalado" }
} else { "No disponible" }
Write-ProfileMessage "winget: $wingetVer" -Level "Info" -Force
# Docker
$dockerVer = if (Get-CachedCommand 'docker') {
$v = docker --version 2>$null
if ($LASTEXITCODE -eq 0 -and $v) { $v.Replace('Docker version ', '').Split(',')[0].Trim() } else { "Instalado" }
} else { "No disponible" }
Write-ProfileMessage "Docker: $dockerVer" -Level "Info" -Force
# Oh My Posh
$ompVer = if (Get-CachedCommand 'oh-my-posh') {
$v = oh-my-posh --version 2>$null
if ($LASTEXITCODE -eq 0 -and $v) { $v.Trim() } else { "Instalado" }
} else { "No disponible" }
Write-ProfileMessage "Oh My Posh: $ompVer" -Level "Info" -Force
# WSL
$wslVer = if (Get-CachedCommand 'wsl') {
$v = wsl --version 2>$null
if ($LASTEXITCODE -eq 0 -and $v) { ($v -split "`n")[0].Trim() } else { "Instalado" }
} else { "No disponible" }
Write-ProfileMessage "WSL: $wslVer" -Level "Info" -Force
Write-ProfileMessage "Directorio: $(Get-Location)" -Level "Info" -Force
Write-ProfileMessage "=================================" -Level "Info" -Force
}
catch {
Write-ProfileMessage "Error al obtener información del sistema: $($_.Exception.Message)" -Level "Error"
}
}
# ================================================================================================
# INICIALIZACIÓN PRINCIPAL
# ================================================================================================
<#
.SYNOPSIS
Función principal que inicializa todo el perfil de PowerShell.
.DESCRIPTION
Orquesta la inicialización de todos los componentes del perfil en el orden correcto,
manejando errores y proporcionando feedback sobre el estado de cada componente.
Incluye benchmark de tiempos de carga.
.EXAMPLE
Initialize-PowerShellProfile
#>
function Initialize-PowerShellProfile {
[CmdletBinding()]
param()
Write-ProfileMessage "Iniciando carga del perfil PowerShell..." -Level "Info"
# Snippets de ejemplo (solo si el directorio está vacío)
if (Get-Command Initialize-ExampleSnippets -ErrorAction SilentlyContinue) {
Initialize-ExampleSnippets