Windows Terminali ile PowerShell Konsept Kanıtı


Yakın zamanda Windows 10 sistemlerimi 1903 sürümüne güncelledim. Bunun nedenlerinden biri yeni Windows Terminal önizlemesini denemek istememdi. Windows Mağazasında bulabilirsiniz. Bu çok yeni bir şey ve tam olmaktan uzak ama harika bir katkı olacağa benziyor. Artık tüm komut terminallerinizi tek bir sekmeli uygulamada bulundurabilecek ve bunlar arasında kolayca geçiş yapabileceksiniz. Söylediğim gibi bu bitmiş ve cilalanmış bir ürün olmaktan çok uzak. Şu anda yeni bir profil eklemek istiyorsanız, yani başka bir terminal, bir json dosyasını manuel olarak düzenlemeniz gerekiyor. VS Code'unuz kuruluysa dosya burada açılacaktır. Aksi takdirde, .json uzantısıyla ilişkilendirilen uygulamayı alacağınızı varsayıyorum.

Json formatını umursamıyorum çünkü bu PowerShell ile kullanabileceğim bir şey. Bazı insanlar grafiksel bir profil düzenleyiciyi umut ederken, ben de PowerShell'i kullanmaktan bir o kadar mutluyum. Bu amaçla, profiles.json dosyanıza yeni bir profil eklemeye yönelik bir işlevi bir araya getirdim. Windows Terminali gibi bu da kesinlikle devam eden bir çalışmadır ve tamamlanmaktan çok uzaktır. Ancak biraz daha olgunlaştığında Windows Terminalini yönetecek bir modül yazmayı öngörebiliyorum.

Şimdilik işlevi Github özeti olarak bulabilirsiniz.

New-WindowsTerminalProfile.ps1:


Function New-WindowsTerminalProfile {
    [cmdletbinding(SupportsShouldProcess)]
    Param(
        [Parameter(Position = 0, Mandatory)]
        [ValidateNotNullOrEmpty()]
        [alias("name")]
        [string]$ProfileName,
        [Parameter( Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Commandline,
        [string]$StartingDirectory,
        [ValidateSet("Campbell", "Solarized Light", "SolarizedDark", "One Half Dark", "One Half Light")]
        [string]$ColorScheme = "Campbell",
        [string]$FontFace = "Consolas",
        [int32]$FontSize = 10,
        [ValidateSet("bar", "emptyBox", "filledBox", "underscore", "vintage")]
        #cursor shape values are case sensitive
        [string]$CursorShape = "bar",
        [ValidatePattern("^#\w{6}$")]
        [string]$CursorColor = "#FFFFFF",
        [validateSet("PowerShell", "Linux", "CMD")]
        [string]$Icon = "PowerShell",
        [Validatescript( {Test-Path $_})]
        [string]$BackgroundImage,
        [ValidateSet("none", "fill", "uniform", "uniformtofill")]
        [string]$StretchMode = "uniform",
        [double]$Opacity = 0.9,
        [switch]$EnableOpacity
    )
    Begin {
        Write-Verbose "[$((Get-Date).TimeofDay) BEGIN  ] Starting $($myinvocation.mycommand)"
        #get the profiles.json file
        $Path = (Get-Childitem $env:localappdata\packages\Microsoft.WindowsTerminal*\profiles.json -Recurse).fullname
        Write-Verbose "[$((Get-Date).TimeofDay) BEGIN  ] Getting settings from $Path"
        #get the current settings
        $settings = Get-content -Path $path | ConvertFrom-Json

        #private helper function
        Function _getdatestamp {
            (Get-Date -format s).replace(":", "_")
        }
    } #begin

    Process {
        Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Creating terminal profile $ProfileName "
        Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Using icon for $icon"
        switch ($Icon) {

            "Powershell" { $iconpath = "ms-appx:///ProfileIcons/{61c54bbd-c2c6-5271-96e7-009a87ff44bf}.png"}
            "Linux" { $iconpath = "ms-appx:///ProfileIcons/{9acb9455-ca41-5af7-950f-6bca1bc9722f}.scale-100.png"}
            "CMD" { $iconpath = "ms-appx:///ProfileIcons/{0caa0dad-35be-5f56-a8ff-afceeeaa6101}.png"}
        }

        $guid = New-Guid

        $new = @{
            acrylicOpacity = $Opacity
            closeOnExit    = $True
            colorScheme    = $ColorScheme
            commandline    = $commandline
            cursorColor    = $CursorColor
            cursorShape    = $CursorShape
            fontFace       = $FontFace
            fontSize       = $FontSize
            guid           = "{$guid}"
            historySize    = 9001
            icon           = $iconPath
            name           = $ProfileName
            padding        = "0, 0, 0, 0"
            snapOnInput    = $True
            useAcrylic     = $EnableOpacity.ToBool()
        }

        if ($StartingDirectory) {
            Write-Verbose "[$((Get-Date).TimeofDay) PROCESS]  Setting Starting Directory to $StartingDirectory"
            #escape slashes in the path
            $new.add("startingDirectory", $StartingDirectory)
        }
        if ($BackgroundImage) {
            Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Adding background image $BackgroundImage"
            $new.Add("backgroundImage", $BackgroundImage)
            $new.Add("backgroundImageStretchMode", $StretchMode)
            $new.useAcrylic = $False
        }

        $newprof = New-Object -typename PSObject -property $new

        $settings.profiles += $newprof

        $out = [PSCustomobject]@{
            globals  = $settings.globals
            profiles = $settings.profiles
            schemes  = $settings.schemes
        }

        if ($pscmdlet.ShouldProcess($($newProf | Out-String))) {
            $parent = Split-Path -path $path
            $backpath = Join-Path -Path $parent -ChildPath "profiles_$(_getdatestamp).json"
            Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Creating a backup copy of $Path to $Backpath"

            Copy-item -path $path -Destination $backpath

            Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Writing updates to $Path"
            $out | ConvertTo-Json -depth 3  | Out-File -FilePath $path
        } #if should process
    } #process

    End {
        Write-Verbose "[$((Get-Date).TimeofDay) END    ] Ending $($myinvocation.mycommand)"
    } #end

} #close New-WindowsTerminalProfile

Anlayabildiğim kadarıyla, json dosya yapısı büyük/küçük harfe duyarlıdır, bu nedenle ValidateSet özniteliğine sahip bir parametre ayarlamak istiyorsanız PowerShell sekmesinin değeri tamamlamasına izin verin. Şu anda varsayılan profildeki renk şemalarını kullanıyorum. Bir noktada, tanımlanmış şemaları profiles.json dosyasından almak mantıklı olabilir ve zor olmayacaktır. Komut size bazı güzel ayrıntılı bilgiler verecek ve -WhatIf'i destekleyecektir. Aynı dizinde profiles.json dosyasının bir kopyasını profiller_2019-07-08T11_10_48.json gibi bir dosya adıyla oluşturma işlevini de ekledim.

Fonksiyonla şunun gibi yeni bir terminal profili oluşturabilirsiniz:

New-WindowsTerminalProfile -ProfileName Netsh -Commandline "cmd /c netsh" -Icon CMD -CursorShape vintage -CursorColor '#008080' -Opacity 0.8 -EnableOpacity -FontSize 18 -verbose

İşte sonuç:

Şimdilik, terminal ayarlarına ince ayar yapmak için profiles.json dosyasını düzenleyeceğim.

Windows Terminal'in gelişmeye devam edeceğini umuyorum ve onu daha da harika hale getirmek için PowerShell komutları oluşturmayı sabırsızlıkla bekliyorum! Eğlence.

İlgili makaleler