当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 带有 Windows 终端的跨平台 PowerShell 配置文件

作者:精品下载站 日期:2024-12-14 07:57:18 浏览:16 分类:玩电脑

带有 Windows 终端的跨平台 PowerShell 配置文件


本周早些时候,我分享了创建可打开远程 PowerShell 会话的 Windows 终端配置文件的技术。但借助 PowerShell 7,我还可以使用 SSH 连接到非 Windows 计算机。那么为什么不扩展我的代码以允许连接到 Linux 机器呢?在尝试我要分享的任何内容之前,请确保您可以使用 SSH 手动创建 PSSession 并将其输入到您的 Linux 目标。如果您能做到这一点,那么您就可以创建 Windows 终端配置文件。

连接脚本

我修改了现有脚本来创建远程处理会话。因为我必须调用 pwsh 而不是 powershell,所以我可以使用正确的参数创建第二个脚本。但随后我就必须编写脚本来维护。因此,我修改了 wtpsremote.ps1 脚本并使用了参数集。

[玩转系统] 带有 Windows 终端的跨平台 PowerShell 配置文件

我已经更新了脚本,还包含了有助于排除故障的详细消息。以及更好的错误处理。

#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

Windows 终端配置文件

使用此脚本,我可以为我的 Linux 会话创建 Windows 终端配置文件。

{
"acrylicOpacity":0.8,
"closeOnExit":true,
"colorScheme":"Campbell",
"commandline":"C:\ProgramFiles\PowerShell\7-preview\preview\pwsh-preview.cmd-nologo-noprofile-noexit-filec:\scripts\wtpsremote.ps1-hostnamefred-company-com-usernamejeff-remoteprofilec:\scripts\lxprofile.ps1",
"cursorColor":"#FFFFFF",
"cursorShape":"underscore",
"fontFace":"CascadiaCode",
"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
}

最终,我将更新此配置文件以使用 pwsh 的最终路径。

Linux 配置文件脚本

我仍然提供运行远程配置文件脚本的选项。毕竟它仍然是一个 PSSession。这是我用于 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 -Force

我使用相同的提示概念来显示会话已经运行了多长时间。这是最终结果

[玩转系统] 带有 Windows 终端的跨平台 PowerShell 配置文件

此时,我可以使用 Windows 终端来满足所有 PowerShell 远程处理需求,并将所需的一切集中在一处。我希望您能让我知道您对这些更新的看法。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯