Tìm kiếm trang web

Cấu hình từ xa PowerShell với Windows Terminal


Tôi đã đi sâu hơn và cam kết hoàn toàn sử dụng Windows Terminal làm môi trường PowerShell mặc định của mình. Tôi thích có một giao diện với các tab cho các cấu hình thiết bị đầu cuối khác nhau. Windows Terminal giúp tôi dễ dàng mở các tab cho PowerShell 7, Windows PowerShell, phiên bản Ubuntu hoặc thậm chí là phiên PowerShell không có cấu hình. Phần cuối cùng tôi cần là một cách dễ dàng để khởi chạy cấu hình Windows Terminal và kết nối với máy tính từ xa. Bạn muốn xem tôi đã làm nó như thế nào?

Đầu tiên tôi tạo một hồ sơ mới trong cài đặt Windows Terminal của mình. Tôi sẽ cho rằng bạn biết cách làm điều đó hoặc có thể tìm ra nó. Nếu bạn sao chép và dán hồ sơ hiện có, đừng quên đặt GUID mới. Đối với cấu hình từ xa đầu tiên của tôi, tôi muốn tạo phiên từ xa PowerShell cho bộ điều khiển miền thử nghiệm DOM1 của mình. Đây là hồ sơ Windows Terminal của tôi cho phần đó.

{
        "acrylicOpacity": 0.5,
        "background": "#0a52e2",
        "closeOnExit": true,
        "colorScheme": "Jeff",
        "commandline": "powershell.exe -nologo -noprofile -noexit -file c:\\scripts\\wtpsremote.ps1 dom1",
        "cursorColor": "#FFFFFF",
        "cursorShape": "underscore",
        "fontFace": "Cascadia Code",
        "fontSize": 14,
        "guid": "{b89c512a-cd2b-4fb4-a6d2-3366cee85970}",
        "historySize": 9001,
        "icon": "ms-appx:///ProfileIcons/{61c54bbd-c2c6-5271-96e7-009a87ff44bf}.png",
        "name": "DOM1",
        "padding": "0, 0, 0, 0",
        "snapOnInput": true,
        "startingDirectory": "%USERPROFILE%",
        "tabTitle": "PSRemote: DOM1.Company.Pri",
        "useAcrylic": false
   },

Các bit ma thuật được tập trung vào cài đặt dòng lệnh. Trong hồ sơ của tôi, tôi đang yêu cầu Windows Terminal khởi động Windows PowerShell mà không có logo, không có hồ sơ và không thoát. Sau đó tôi sẽ cung cấp một tệp và đối số cho tập lệnh đó. Ban đầu tôi loay hoay với -Command nhưng cuối cùng thấy việc gọi một tệp tập lệnh trở nên dễ dàng hơn. Tệp wtpsremote.ps1 tạo phiên từ xa.

#requires -version 5.1

#wtpsremote.ps1

[cmdletbinding()]
Param(
    [Parameter(Position = 0, Mandatory, HelpMessage = "Specify remote computer name")]
    [ValidateNotNullOrEmpty()]
    [string]$Computername,
    [pscredential]$Credential,
    [Parameter( HelpMessage = "A profile script to run in the remote session")]
    [ValidateScript( {Test-Path $_})]
    [string]$RemoteProfile = "C:\scripts\RemoteProfile.ps1",
    [Parameter(HelpMessage = "Specify a remote endpoint other than the default Microsoft.powershell")]
    [string]$ConfigurationName,
    [int32]$Port,
    [switch]$UseSSL
)

#remove this this parameter if specified since it can't be used to create a new PSSession
[void]($PSBoundParameters.Remove("RemoteProfile"))

#Create a new remoting session splatting the parameters passed to this script
$remote = New-PSSession @PSBoundParameters

#run the remote profile script
if ($RemoteProfile) {
    Invoke-Command -Session $remote -FilePath $RemoteProfile -HideComputerName |
        Select-Object -property * -ExcludeProperty runspaceID |
        Format-Table -AutoSize
}

#open the pssession
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

Tập lệnh lấy một số tham số liên quan đến việc tạo một PSSession mới, nó thực hiện và sau đó kết nối với nó. Và kịch bản còn đi xa hơn một chút.

Thông thường, khi bạn khởi chạy phiên từ xa PowerShell, không có tập lệnh hồ sơ nào được chạy. Nhưng tập lệnh này cho phép bạn chỉ định tệp cục bộ có thể chạy từ xa, về bản chất là tập lệnh hồ sơ. Đây là mặc định tôi sử dụng.

#requires -version 5.1

#this is a remote profile script

#create a new prompt function for the remote session
#how long has this session been running?
$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

Set-Location C:\
Clear-Host

#display some information about the remote computer
Get-CimInstance -ClassName Win32_OperatingSystem |
Select-Object @{Name="Computer";Expression={$_.CSName}},
@{Name="OS";Expression = {$_.Caption}},
@{Name="PSVersion";Expression = {$PSVersionTable.PSVersion}},
@{Name="User";Expression = {Whoami.exe}}

Tập lệnh hồ sơ xác định lời nhắc cho phiên từ xa sẽ cho bạn biết bạn đã kết nối được bao lâu. Nó cũng hiển thị một bản tóm tắt về máy tính từ xa. Bạn có thể thêm bất kỳ thứ gì khác mà bạn có thể cần, chẳng hạn như xác định biến, bí danh hoặc nhập mô-đun.

Quay lại wtpsremote.ps`, bước cuối cùng là hiển thị lời nhắc. Nếu bạn chỉ đóng tab hồ sơ, phiên truy cập từ xa sẽ vẫn ở trạng thái ngắt kết nối cho đến khi máy tính từ xa dọn sạch hoặc khởi động lại. Để trở thành một công dân mạng tốt, khi bạn hoàn tất, hãy gõ 'exit' để rời khỏi phiên từ xa. Điều này sẽ đưa bạn trở lại cấu hình thiết bị đầu cuối chạy Windows PowerShell. Bạn nên xóa psession và sau đó bạn có thể thoát hoặc đóng tab hồ sơ.

Đây là những gì tôi nhận được khi mở hồ sơ Windows Terminal này.

Khi tôi sử dụng thiết bị đầu cuối, lời nhắc cập nhật sẽ cho tôi biết tôi đã kết nối được bao lâu. Khi hoàn tất, tôi có thể thoát ra.

Tại thời điểm này, tôi sẽ xóa psession và thoát khỏi tab.

Tập lệnh kết nối của tôi cũng cho phép bạn chỉ định thông tin xác thực thay thế và thậm chí cả điểm cuối thay thế. Đây là cấu hình dành cho SRV1 kết nối với thông tin xác thực cụ thể và kết nối với điểm cuối PowerShell 7.

{
    "acrylicOpacity": 0.5,
    "background": "#808285",
    "closeOnExit": true,
    "colorScheme": "Jeff",
    "commandline": "powershell.exe -nologo -noprofile -noexit -file c:\\scripts\\wtpsremote.ps1 -computername srv1 -credential company\\administrator -configurationname PowerShell.7.0.0-rc.2",
    "cursorColor": "#FFFFFF",
    "cursorShape": "underscore",
    "fontFace": "Cascadia Code",
    "fontSize": 14,
    "guid": "{173fd06c-883a-404b-97bd-9f955a0e85f0}",
    "historySize": 9001,
    "icon": "ms-appx:///ProfileIcons/{61c54bbd-c2c6-5271-96e7-009a87ff44bf}.png",
    "name": "SRV1",
    "padding": "0, 0, 0, 0",
    "snapOnInput": true,
    "startingDirectory": "%USERPROFILE%",
    "tabTitle": "PSRemote: SRV1.Company.Pri",
    "useAcrylic": false
},

Tôi nhận thấy các tab từ xa này rất hữu ích và hy vọng bạn cũng vậy. Thưởng thức!

Cập nhật

Tôi đã cập nhật các kỹ thuật và mã để tạo cấu hình từ xa trong Windows Terminal để hiện hỗ trợ đa nền tảng. Đọc về nó ở đây.

Bài viết liên quan