Tìm kiếm trang web

Cấu hình PowerShell đa nền tảng với Windows Terminal


Đầu tuần này, tôi đã chia sẻ các kỹ thuật tạo cấu hình Windows Terminal để mở phiên PowerShell từ xa. Nhưng với PowerShell 7, tôi cũng có thể kết nối với các máy không chạy Windows bằng SSH. Vậy tại sao không mở rộng mã của tôi để cho phép kết nối với hộp Linux? Trước khi bạn thử bất cứ điều gì tôi sắp chia sẻ, hãy đảm bảo bạn có thể tạo và nhập PSSession theo cách thủ công vào mục tiêu Linux của mình bằng SSH. Nếu bạn có thể làm điều đó thì bạn có thể tạo cấu hình Windows Terminal.

Tập lệnh kết nối

Tôi đã sửa đổi tập lệnh hiện có của mình để tạo phiên từ xa. Vì tôi sẽ phải gọi pwsh thay vì powershell nên tôi có thể tạo tập lệnh thứ hai với các tham số thích hợp. Nhưng sau đó tôi phải duy trì các kịch bản. Vì vậy, thay vào đó, tôi đã sửa đổi tập lệnh wtpsremote.ps1 của mình và sử dụng các bộ tham số.

Tôi đã cập nhật tập lệnh để bao gồm các thông báo chi tiết giúp ích khi khắc phục sự cố. Và xử lý lỗi tốt hơn.

#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

Cấu hình thiết bị đầu cuối Windows

Với tập lệnh này, tôi có thể tạo cấu hình Windows Terminal cho phiên Linux của mình.

{
    "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
}

Cuối cùng, tôi sẽ cập nhật hồ sơ này để sử dụng đường dẫn cuối cùng tới pwsh.

Tập lệnh hồ sơ Linux

Tôi vẫn cung cấp tùy chọn chạy tập lệnh hồ sơ từ xa. Rốt cuộc thì nó vẫn là một PSSession. Đây là tệp tập lệnh tôi sử dụng cho các kết nối Linux của mình.

# 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 -Force

Tôi đang sử dụng khái niệm lời nhắc tương tự để cho biết phiên đã chạy được bao lâu. Đây là kết quả cuối cùng

Tại thời điểm này, tôi có thể sử dụng Windows Terminal cho tất cả các nhu cầu điều khiển từ xa PowerShell của mình và có mọi thứ tôi cần ở một nơi. Tôi hy vọng bạn sẽ cho tôi biết suy nghĩ của bạn về những cập nhật này.

Bài viết liên quan