LinuxLoveWindows.psm1
# Module: LinuxLoveWindows # Description: # Provides functions to import and initialize Linux (WSL) commands for use in Windows PowerShell. # - Initialize-LinuxCommands: Loads Linux commands from a file and imports them into the session. # - Import-LinuxCommands: Extracts available Linux functions from WSL, saves them to a file, and initializes them in PowerShell. function Initialize-LinuxCommands { $file = "imported_linux_commands.txt" if (-not (Test-Path $file)) { Write-Warning "File '$file' not found." return } $fileInfo = Get-Item $file if ($fileInfo.Length -eq 0) { Write-Warning "File '$file' is empty." return } $commands = Get-Content $file -Raw if ($commands -match '[;|&><*?!()$\\''`]') { Write-Warning "Suspicious character detected in command string. Aborting import." return } try { Invoke-Expression "Import-WslCommand $commands" } catch { Write-Warning "Failed to import Linux commands: $_" } } function Import-LinuxCommands { param ( [switch]$All ) $file = "imported_linux_commands.txt" $toImport = @() $wslDistro = wsl -l | Select-String '\(' | ForEach-Object {($_ -split '\s{2,}')[0]} if ($wslDistro.Length -eq 0) { Write-Host "No default distro found." return } Write-Host "(1/3) Collecting Linux commands from WSL distro: $wslDistro" try { # Note: You may edit this command if it does not work for your Linux distribution. wsl bash -c "compgen -A function -back | sort | uniq | grep -E '^[a-zA-Z0-9_-]+$'" | Out-File -Encoding UTF8 $file } catch { Write-Warning "Failed to retrieve commands from WSL: $_" return } if (-not (Test-Path $file)) { Write-Warning "Command file not found after export." return } $commands = [System.IO.File]::ReadAllLines($file) | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } Write-Host "(2/3) Filtering and sorting commands" if ($All -or $env:LINUX_CMD -eq "all") { $toImport = $commands } else { $toImport = $commands | ForEach-Object -Parallel { if (-not (Get-Command $_ -ErrorAction SilentlyContinue)) { $_ } } } Write-Host "(3/3) Importing new commands into session" if ($toImport.Count -eq 0) { Write-Host "No new Linux commands to import." return } $diff = Compare-Object $toImport $commands -SyncWindow 0 if ($diff.Count -gt 0) { $quoted = $toImport | ForEach-Object { '"{0}"' -f $_.Trim() } $quoted -join ', ' | Set-Content -Encoding UTF8 $file try { Initialize-LinuxCommands Write-Host "Linux commands imported successfully." } catch { Write-Warning "Failed to import Linux commands: $_" } } else { Write-Host "No new Linux commands to import ($file unchanged)." } } Initialize-LinuxCommands |