Perfiles de PowerShell multiplataforma con terminal de Windows
A principios de esta semana, compartí mis técnicas para crear un perfil de Terminal de Windows que abriría una sesión remota de PowerShell. Pero con PowerShell 7, también puedo conectarme a máquinas que no sean Windows mediante SSH. Entonces, ¿por qué no ampliar mi código para permitir la conexión a una máquina Linux? Antes de intentar cualquier cosa que voy a compartir, asegúrese de poder crear e ingresar manualmente una PSSession en su destino Linux usando SSH. Si puede hacer eso, puede crear un perfil de Terminal de Windows.
El guión de conexión
Modifiqué mi script existente para crear la sesión remota. Como tendré que invocar pwsh en lugar de powershell, podría haber creado un segundo script con los parámetros adecuados. Pero entonces tendría que mantener los guiones. Entonces, en lugar de eso, modifiqué mi script wtpsremote.ps1 y usé conjuntos de parámetros.
Actualicé el script para incluir también mensajes detallados que ayudan a solucionar problemas. Y un mejor manejo de errores.
#requires -version 5.1
<#
.Synopsis
Create a remote PowerShell session
.Description
This script is intended to be called from a Windows Terminal profile to create
a PowerShell remoting session. If you are using the ssh parameter set, you
will need to invoke this script with pwsh.
.Link
New-PSSession
.Link
Enter-PSSession
#>
[cmdletbinding(DefaultParameterSetName = "Computer")]
Param(
[Parameter(Position = 0, Mandatory, HelpMessage = "Specify remote computer name",ParameterSetName="Computer")]
[ValidateNotNullOrEmpty()]
[string]$Computername,
[Parameter(ParameterSetName="Computer")]
[pscredential]$Credential,
[Parameter( HelpMessage = "A profile script to run in the remote session")]
[ValidateScript( {Test-Path $_})]
[string]$RemoteProfile,
[Parameter(HelpMessage = "Specify a remote endpoint other than the default Microsoft.powershell")]
[string]$ConfigurationName,
[Parameter(HelpMessage = "Specify an alternate port number")]
[int32]$Port,
[Parameter(ParameterSetName="Computer")]
[switch]$UseSSL,
[Parameter(Position = 0, Mandatory,ParameterSetName = "ssh")]
[ValidateNotNullorEmpty()]
[string]$Hostname,
[Parameter(ParameterSetName = "ssh")]
[string]$Username,
[Parameter(ParameterSetName = "ssh")]
[string]$Subsystem,
[Parameter(ParameterSetName = "ssh")]
[string]$KeyFilePath
)
Write-Verbose "Starting $($MyInvocation.MyCommand)"
Write-Verbose "Using parameter set $($pscmdlet.parametersetname)"
if ($PSCmdlet.ParameterSetName -eq "ssh") {
Write-Verbose "adding SSHTransport parameter"
[void]($PSBoundParameters.add("SSHTransport",$True))
}
#remove this this parameter if specified since it can't be used to create a new PSSession
if ($PSBoundParameters.ContainsKey("RemoteProfile")) {
Write-Verbose "Removing RemoteProfile bound parameter"
[void]($PSBoundParameters.Remove("RemoteProfile"))
}
#Create a new remoting session splatting the parameters passed to this script
Try {
Write-Verbose "Using these parameters to create the PSSession"
$PSBoundParameters | Out-String | Write-Verbose
$remote = New-PSSession @PSBoundParameters -errorAction Stop
$remote | Out-String | Write-Verbose
}
Catch {
Write-Verbose "Failed to create remoting session"
Throw $_
}
#run the remote profile script
if ($RemoteProfile) {
Write-Verbose "Running remote profile script $RemoteProfile"
Invoke-Command -Session $remote -FilePath $RemoteProfile -HideComputerName |
Select-Object -property * -ExcludeProperty runspaceID
}
#open the pssession
Write-Verbose "Entering session"
Enter-PSSession -session $remote
$msg = @"
-------------------------------------------------------------------------------------
| Reminder: |
| Remove the `$remote pssession after you exit and before you close the profile tab. |
| |
| PS C:\> `$remote | Remove-PSSession |
| PS C:\> exit |
-------------------------------------------------------------------------------------
"@
#you may need to adjust colors based on your profile settings
Write-host $msg -ForegroundColor Magenta -BackgroundColor Gray
El perfil de terminal de Windows
Con este script puedo crear un perfil de Terminal de Windows para mi sesión de Linux.
{
"acrylicOpacity": 0.8,
"closeOnExit": true,
"colorScheme": "Campbell",
"commandline": "C:\\Program Files\\PowerShell\\7-preview\\preview\\pwsh-preview.cmd -nologo -noprofile -noexit -file c:\\scripts\\wtpsremote.ps1 -hostname fred-company-com -username jeff -remoteprofile c:\\scripts\\lxprofile.ps1",
"cursorColor": "#FFFFFF",
"cursorShape": "underscore",
"fontFace": "Cascadia Code",
"fontSize": 14,
"guid": "{5668446e-620a-448f-874b-db766831b2ab}",
"historySize": 9001,
"icon": "ms-appx:///ProfileIcons/{574e775e-4f2a-5b96-ac1e-a2962a402336}.png",
"name": "Fred",
"padding": "0, 0, 0, 0",
"snapOnInput": true,
"startingDirectory": "C:\\",
"tabTitle": "PSRemote: Fred",
"backgroundImage": "C:\\users\\jeff\\Pictures\\smoking-penguin.jpg",
"backgroundImageAlignment": "center",
"backgroundImageStretchMode": "none",
"backgroundImageOpacity": 0.3,
"useAcrylic": true
}
Con el tiempo, actualizaré este perfil para utilizar la ruta final a pwsh.
El script de perfil de Linux
Sigo ofreciendo la opción de ejecutar un script de perfil remoto. Después de todo, sigue siendo una PSSession. Este es el archivo de script que uso para mis conexiones de Linux.
# this is for Linux based computers
$os = $PSVersionTable.OS
$lsb = lsb_release -d
$osver = ($lsb -split ":")[1].Trim()
$elevated = "N/A"
$user = [System.Environment]::UserName
$computer = [System.Environment]::MachineName
#object properties will be displayed in the order they are listed here
[pscustomObject]@{
User = $user
Elevated = $elevated
Computername = $computer
OperatingSystem = $os
OSVersion = $osver
PSVersion = $PSVersionTable.PSVersion.ToString()
Edition = $PSVersionTable.PSEdition
PSHost = $host.Name
WSMan = $PSVersionTable.WSManStackVersion.ToString()
ExecutionPolicy = (Get-ExecutionPolicy)
Culture = [System.Globalization.CultureInfo]::CurrentCulture.NativeName
}
$initiated = Get-Date
$remotePrompt = {
#display the session runtime without the milliseconds
$ts = ((Get-Date) - $initiated).ToString().split(".")[0]
Write-Host ">$ts< " -ForegroundColor yellow -nonewline "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) ";
}
Set-Item -Path function:\prompt -Value $remotePrompt -ForceEstoy usando el mismo concepto de mensaje para mostrar cuánto tiempo lleva ejecutándose la sesión. Aquí está el resultado final
En este punto, puedo usar Windows Terminal para todas mis necesidades de comunicación remota de PowerShell y tener todo lo que necesito en un solo lugar. Espero que me cuentes qué piensas de estas actualizaciones.