Timetombs

泛义的工具是文明的基础,而确指的工具却是愚人的器物

共 66h / 121a 篇
,更新于 2026-11-08T20:40:11Z+08:00 by   2f83c1f

[PowerShell] Script

版权声明 - CC BY-NC-SA 4.0

1 Script File List

bat文件列表
shutdown /r /fw /t 0
ps1文件列表
#####################################################
# current user powershell profile entry script file.
#####################################################

# params
Param(
    [switch]$Init = $False,
    [string]$GitUserName = 'lnh',
    [string]$GitUserEmail = 'lnhdyx@outlook.com'
)

@(
    '/function-console.ps1',
    '/function-format.ps1',
    '/link.ps1',
    '/os.ps1',
    '/env.ps1',
    '/file.ps1',
    '/git.ps1',
    '/vscode.ps1',
    '/gui.ps1',
    '/hosts.ps1',
    '/profile.ps1',
    '/prompt.ps1',
    '/sln.ps1',
    '/ui.ps1',
    '/vm.ps1',
    '/http.ps1',
    '/yaml.ps1',
    '/ip.ps1',
    '/k8s.ps1',
    '/docker.ps1',
    '/drive.ps1',
    '/blog.ps1',
    '/java.ps1',
    '/wlan.ps1',
    '/directory.ps1',
    '/idea.ps1',
    '/auto-complete.ps1',
    '/fast-copy.ps1',
    '/dism.ps1',
    '/hiwifi.ps1',
    '/v2ray.ps1',
    '/alias.ps1'
) | Foreach-Object { . "$PSScriptRoot$_" }

if ($Init) {

    Profile-AddScriptFile -ProfilePath $PROFILE -ScriptFilePath $PSCOMMANDPATH

    Git-Set-Global-Alias

    Git-Set-Global-Config

    Git-Set-Global-User -UserName $GitUserName -UserEmail $GitUserEmail

    Git-Get-Config

    # Update-Help
}

Git-Import-Posh-Git

# Kubernetes-Import-PS-Kubectl-Completion
# UI-SetDisplayOptions

Console-Debug-Name-Value -Name 'Get-ExecutionPolicy' -Value $(Get-ExecutionPolicy)
################################
# powershell alias functions
################################

Set-Alias -Name b -Value blog
Set-Alias -Name bs -Value blog-server
Set-Alias -Name d -Value Directory-To
Set-Alias -Name dq -Value Directory-Search-Path-List-From-Quick-Access
Set-Alias -Name dql -Value Directory-List-Quick-Access
Set-Alias -Name c -Value VsCode-Open
Set-Alias -Name i -Value Idea-Open

Set-Alias -Name dr -Value Docker-Run
Set-Alias -Name dre -Value Docker-Run-entrypoint
Set-Alias -Name drs -Value Docker-Run-entrypoint-sh
Set-Alias -Name drb -Value Docker-Run-entrypoint-bash
Set-Alias -Name dc -Value docker-compose
Set-Alias -Name dm -Value docker-machine
Set-Alias -Name k -Value kubectl
Set-Alias -Name mk -Value minikube

Set-Alias -Name e -Value Gui-Open-Explorer

Set-Alias -Name g -Value git

Set-Alias -Name gti -Value git

Set-Alias -Name hs -Value http-server
Set-Alias -Name hst -Value http-server-temp
Set-Alias -Name hss -Value http-server-share

Set-Alias -Name env -Value Env-GetAllVariable

Set-Alias -Name path -Value Env-GetPathVariavle

Set-Alias -Name yj -Value Yaml-ToJson

Set-Alias -Name jy -Value Yaml-FromJson

Set-Alias -Name grep -Value Select-String

Set-Alias -Name k8sgtp -Value Kubernetes-Get-Terminated-Pod

Set-Alias -Name ja -Value Java-Arthas
# https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/register-argumentcompleter?view=powershell-7.1

Register-ArgumentCompleter -CommandName Directory-To -ParameterName Path -ScriptBlock $__QUICK_ACCESS_DIRECTORY_SCRIPT_BLOCK
Register-ArgumentCompleter -CommandName VsCode-Open -ParameterName Path -ScriptBlock $__QUICK_ACCESS_DIRECTORY_SCRIPT_BLOCK
Register-ArgumentCompleter -CommandName Idea-Open -ParameterName Path -ScriptBlock $__QUICK_ACCESS_DIRECTORY_SCRIPT_BLOCK
Register-ArgumentCompleter -CommandName Gui-Open-Explorer -ParameterName Path -ScriptBlock $__QUICK_ACCESS_DIRECTORY_SCRIPT_BLOCK

Register-ArgumentCompleter -Native -CommandName winget -ScriptBlock {
    param($wordToComplete, $commandAst, $cursorPosition)
    [Console]::InputEncoding = [Console]::OutputEncoding = $OutputEncoding = [System.Text.Utf8Encoding]::new()
    $Local:word = $wordToComplete.Replace('"', '""')
    $Local:ast = $commandAst.ToString().Replace('"', '""')
    winget complete --word="$Local:word" --commandline "$Local:ast" --position $cursorPosition | ForEach-Object {
        [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
    }
}

Register-ArgumentCompleter -Native -CommandName dotnet -ScriptBlock {
    param($wordToComplete, $commandAst, $cursorPosition)
    dotnet complete --position $cursorPosition $commandAst.ToString() | ForEach-Object {
        [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
    }
}

# https://docs.microsoft.com/en-us/powershell/module/psreadline/get-psreadlinekeyhandler?view=powershell-7.1
# Get-PSReadLineKeyHandler
function Hugo-Server() {
    Console-Debug " hugo server --config hugo.yml --watch --buildDrafts --forceSyncStatic --panicOnWarning --port 13131"
    hugo server --config hugo.yml --watch --buildDrafts --forceSyncStatic --panicOnWarning --port 13131
}

function Blog() {
    cd d:/_code/blog
}

function Blog-Server() {
    Blog
    Hugo-Server
}
$__QUICK_ACCESS_DIRECTORY = [System.Collections.Generic.List[PSObject]]::new();

$__QUICK_ACCESS_DIRECTORY_SCRIPT_BLOCK = {
    param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)
    Directory-Search-Path-List-From-Quick-Access -Search $wordToComplete | ForEach-Object {
        [System.Management.Automation.CompletionResult]::new($_.FullPath, $_.FullPath, 'ParameterValue', $_.FullPath)
    }
}

function Directory-Exists-And-Is-Directory {
    param (
        [Parameter(Mandatory = $TRUE)]
        [string] $Path = $(throw "Path param is null!")
    )

    if (![System.IO.Directory]::Exists($Path)) {
        throw "path $Path is not exist."
    }

    if ([System.IO.File]::Exists($Path)) {
        throw "path $Path is a file."
    }

    return $TRUE;
}

function script:Directory-Get-Abbr {
    param (
        [Parameter(Mandatory = $TRUE)]
        [string] $Name = $(throw "Name param is null!")
    )
    $Abbr = "";
    $Words = $Name.Split(" _.-".ToCharArray(), [System.StringSplitOptions]::RemoveEmptyEntries);
    $Words | ForEach-Object {
        $Abbr += $_[0];
    }
    return $Abbr;
}

function script:Directory-Convert-To-Dir-Object {
    param ($Raw)
    $FullPath = $Raw.FullName;
    $Name = (Split-Path -Path $FullPath -Leaf);
    $NameAbbr = (Directory-Get-Abbr -Name $Name);

    $Parent = (Split-Path -Path $FullPath -Parent);
    $ParentName = (Split-Path -Path $Parent -Leaf);
    $ParentNameAbbr = (Directory-Get-Abbr -Name $ParentName);
    $Dir = New-Object PSObject -Property @{
        #Raw      = $Raw;
        Abbr     = "$ParentNameAbbr$NameAbbr";
        NameAbbr = $NameAbbr;
        FullPath = $FullPath;
    }
    return $Dir
}

function Directory-Add-To-Quick-Access {
    param (
        [string] $Path
    )

    if (Directory-Exists-And-Is-Directory -Path $Path) {
        Get-ChildItem -Path $Path | ForEach-Object {
            if (Test-Path -Path $_.FullName -PathType Container) {
                $__QUICK_ACCESS_DIRECTORY.Add((Directory-Convert-To-Dir-Object -Raw $_))
            }
        }
    }
}

function Directory-List-Quick-Access {
    $__QUICK_ACCESS_DIRECTORY | Format-Table -AutoSize
}

function Directory-Search-Path-List-From-Quick-Access {
    param (
        [Parameter(Mandatory = $TRUE)]
        [string] $Search = $(throw "Search param is null!")
    )

    $ResultWithScopeIndex = [PSObject[][]]::new(10);
    $__QUICK_ACCESS_DIRECTORY | ForEach-Object {
        $Score = Directory-Search-Score -Dir $_ -Search $Search
        if ($Score -gt -1) {
            $ResultWithScopeIndex[$Score] += $_
        }
    }
    [array]::Reverse($ResultWithScopeIndex);

    $Result = [System.Collections.Generic.List[PSObject]]::new();
    $ResultWithScopeIndex | ForEach-Object {
        if ($_ -ne $NULL) {
            $Result.AddRange($_)
        }
    }

    return $Result;
}

function script:Directory-Search-Score {
    param ($Dir, [string] $Search )
    if ($Dir.FullPath.Contains($Search, [StringComparison]::OrdinalIgnoreCase)) {
        return 9;
    }
    if ($Dir.Abbr.Contains($Search, [StringComparison]::OrdinalIgnoreCase)) {
        return 8;
    }
    if ($Dir.NameAbbr.Contains($Search, [StringComparison]::OrdinalIgnoreCase)) {
        return 7;
    }
    if (Filter-Directory-Item -Dir $Dir -Search $Search) {
        return 1;
    }

    return -1;
}


function script:Filter-Directory-Item {
    param ($Dir, [string] $Search )
    $StartIndex = 0;
    for ($i = 0; $i -lt $Search.Length; $i++) {
        $char = $Search[$i];
        $charIndex = $Dir.FullPath.IndexOf($char, $StartIndex);
        if ($charIndex -eq -1) {
            return $FALSE;
        }
        else {
            $StartIndex = $charIndex;
        }
    }
    return $TRUE;
}

function Directory-To {
    param (
        [Parameter(Mandatory = $TRUE)]
        [string] $Path = $(throw "Path param is null!")
    )
    if (Directory-Exists-And-Is-Directory -Path $Path) {
        Console-Debug "cd $Path".ToLower()
        Set-Location $Path
    }
}

Directory-Add-To-Quick-Access -Path d:/_code/
Directory-Add-To-Quick-Access -Path d:/_github/
Directory-Add-To-Quick-Access -Path d:/
Directory-Add-To-Quick-Access -Path d:/_app/
Directory-Add-To-Quick-Access -Path d:/_cache/
################################
# FastCopy env functions
################################


function Dism-Backup-Os {
    param (
        [string] $SourcePath = 'c:\',
        [string] $TargetPath = 'f:\_backup\'
    )

    [string]$OsName = Dism-Get-Os-Name;
    [string]$Date = $(Get-Date -Format 'yyyy-MM-dd');
    [string]$Name = "${OsName}-${Date}".ToLower();
    [string]$ImageFile = "${TargetPath}${OsName}.wim";

    $CaptureImageCommand = "DISM /Capture-Image /CaptureDir:${SourcePath} /Name:${Name} /ImageFile:${ImageFile}";
    $GetImageCommand = "DISM /Get-ImageInfo /ImageFile:$ImageFile";
    $BatFilePath = "d:\dism-${OsName}.bat";

    $CaptureImageCommand | Out-File -FilePath $BatFilePath
    $GetImageCommand | Out-File -Append -FilePath $BatFilePath
    Get-Content -Path $BatFilePath
}

function Dism-Backup-Os-Append {
    param (
        [string] $SourcePath = 'c:\',
        [string] $ImageFile
    )
    $GetImageCommand = "DISM /Get-ImageInfo /ImageFile:$ImageFile";

    [string]$OsName = Dism-Get-Os-Name;
    [string]$Date = $(Get-Date -Format 'yyyy-MM-dd');
    [string]$Name = "${OsName}-${Date}".ToLower();

    $AppendCommand = "DISM /Append-Image /CaptureDir:${SourcePath} /Name:${Name} /ImageFile:$ImageFile";
    $BatFilePath = "d:\dism-${OsName}-append.bat";

    $GetImageCommand | Out-File -FilePath $BatFilePath
    $AppendCommand | Out-File -Append -FilePath $BatFilePath
    $GetImageCommand | Out-File -Append -FilePath $BatFilePath
    Get-Content -Path $BatFilePath
}

function Dism-Get-Image-Info {
    param (
        [string] $ImageFile
    )
    DISM /Get-ImageInfo /ImageFile:$ImageFile
}

function Dism-Get-Intl {
    Console-Debug 'DISM /Online /Get-Intl';
    DISM /Online /Get-Intl
}

function Dism-Get-Lang {
    Console-Debug 'Get-Culture | Format-List -Property *';
    Get-Culture | Format-List -Property *
}

function Dism-Get-Os-Name {
    $ComputerInfo = Get-ComputerInfo;
    [string]$CsName = $ComputerInfo.CsName.Trim().ToLower();
    [string]$OsName = $($($ComputerInfo.OsName.ToLower() -Replace 'microsoft', '').Trim() -Replace ' ', '-');
    return "${CsName}-${OsName}";
}

# https://www.cnblogs.com/lindexi/p/17679590.html
# https://learn.microsoft.com/zh-cn/windows-hardware/manufacture/desktop/clean-up-the-winsxs-folder?view=windows-11
# https://learn.microsoft.com/zh-cn/windows-hardware/manufacture/desktop/dism-operating-system-package-servicing-command-line-options?view=windows-11#cleanup-image
function Dism-WinSxs-Stats {
    Console-Debug 'DISM /Online /Cleanup-Image /AnalyzeComponentStore'
    DISM /Online /Cleanup-Image /AnalyzeComponentStore
}

function Dism-WinSxs-Clean {
    Console-Debug 'DISM /online /Cleanup-Image /StartComponentCleanup'
    DISM /online /Cleanup-Image /StartComponentCleanup
}

function Dism-WinSxs-Clean-All {
    Console-Debug 'DISM /online /Cleanup-Image /StartComponentCleanup /ResetBase'
    DISM /online /Cleanup-Image /StartComponentCleanup /ResetBase
}

function Dism-WinSxs-Repair {
    Console-Debug '/Cleanup-Image /RestoreHealth /Source:X:\Sources\install.wim /LimitAccess'
    DISM /Online /Cleanup-Image /RestoreHealth
    # sfc /scannow
    # DISM /Online /Cleanup-Image /RestoreHealth /Source:wim:z:\win11\Sources\install.wim:1 /LimitAccess
}
function Docker-Run() {
    Console-Debug "docker run --rm --tty --interactive" $Args
    docker run --rm --tty --interactive $Args
}
function Docker-Run-Entrypoint() {
    Console-Debug "docker run --rm --tty --interactive --entrypoint" $Args
    docker run --rm --tty --interactive --entrypoint $Args
}

function Docker-Run-Entrypoint-Sh() {
    Console-Debug "docker run --rm --tty --interactive --entrypoint sh" $Args
    docker run --rm --tty --interactive --entrypoint sh $Args
}

function Docker-Run-Entrypoint-Bash() {
    Console-Debug "docker run --rm --tty --interactive --entrypoint bash" $Args
    docker run --rm --tty --interactive --entrypoint bash $Args
}
# -----------------------------------------------------------------------------
# 函数 0: 获取分区的 Volume GUID
# -----------------------------------------------------------------------------
function Drive-Get-Volume-Guid-From-Partition {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        $Partition
    )

    # GPT 分区有 Guid; MBR 分区没有 Guid,只能从 AccessPaths (\\?\Volume{GUID}\) 中解析
    if ($Partition.Guid) {
        return $Partition.Guid.Trim('{}')
    }

    foreach ($accessPath in $Partition.AccessPaths) {
        if ($accessPath -match 'Volume\{([0-9a-fA-F-]+)\}') {
            return $matches[1]
        }
    }

    return $null
}

# -----------------------------------------------------------------------------
# 函数 1: 获取所有分区的 Volume 列表
# -----------------------------------------------------------------------------
function Drive-List-Volume {
    [CmdletBinding()]
    param()

    $diskByNumber = @{}
    Get-Disk | ForEach-Object {
        $diskByNumber[$_.Number] = $_
    }

    # DeviceId 与 Get-Disk 的 Number 对应,用字符串做键避免 UInt32/Int32 的类型差异
    $physicalDiskByNumber = @{}
    Get-PhysicalDisk | ForEach-Object {
        $physicalDiskByNumber[$_.DeviceId.Trim()] = $_
    }

    $volumeByGuid = @{}
    Get-Volume | ForEach-Object {
        if ($_.UniqueId -match '\{([0-9a-fA-F-]+)\}') {
            $volumeByGuid[$matches[1].ToLower()] = $_
        }
    }

    # 分区的 Guid 与卷的 UniqueId (\\?\Volume{GUID}\) 一一对应
    $getVolume = {
        param($Partition)
        $guid = Drive-Get-Volume-Guid-From-Partition -Partition $Partition
        if (-not $guid) {
            return $null
        }
        return $volumeByGuid[$guid.ToLower()]
    }

    Get-Partition |
    #Where-Object { $_.AccessPaths -ne $null -and $_.Guid -ne $null }  |
    Sort-Object DiskNumber, PartitionNumber |
    Format-Table -AutoSize -Property @{
        Label      = '#';
        Expression = {
            # DriveLetter 没有盘符时是 [char]0,直接格式化会写入 NUL 字符,导致后续列错位
            $letter = $_.DriveLetter ? $_.DriveLetter : " "
            "{0}.{1} {2}" -f $_.DiskNumber, $_.PartitionNumber, $letter
        };
        Alignment  = 'Left'
    }, @{
        Label      = 'Label';
        Expression = {
            $volume = & $getVolume $_
            if ($volume -and $volume.FileSystemLabel) {
                $volume.FileSystemLabel
            }
            else {
                $_.Type
            }
        };
        Alignment  = 'Right'
    }, @{
        Name       = 'Size';
        Expression = { Format-Byte -Value $_.Size -Split ' ' };
        Alignment  = 'Right'
    }, @{
        Label      = 'FS';
        Expression = {
            $volume = & $getVolume $_
            $volume.FileSystemType
        }
    }, @{
        Label      = 'Volume Guid';
        Expression = { Drive-Get-Volume-Guid-From-Partition -Partition $_ }
    }, @{
        Label      = 'Status';
        Expression = { $_.OperationalStatus }
    }, @{
        Label      = 'Disk Friendly Name';
        Expression = {
            if ($diskByNumber.ContainsKey($_.DiskNumber)) {
                $diskByNumber[$_.DiskNumber].FriendlyName
            }
        };
        Alignment  = 'Left'
    }, @{
        Label      = 'Type';
        Expression = {
            $physicalDisk = $physicalDiskByNumber["$($_.DiskNumber)"]
            if ($physicalDisk -and $physicalDisk.MediaType -ne 'Unspecified') {
                $physicalDisk.MediaType
            }
        }
    }, @{
        Label      = 'Bus';
        Expression = {
            if ($diskByNumber.ContainsKey($_.DiskNumber)) {
                $diskByNumber[$_.DiskNumber].BusType
            }
        }
    }, @{
        Label      = 'Part';
        Expression = {
            if ($diskByNumber.ContainsKey($_.DiskNumber)) {
                $diskByNumber[$_.DiskNumber].PartitionStyle
            }
        }
    }
}

# -----------------------------------------------------------------------------
# 函数 2: 根据 Volume GUID 分配盘符
# -----------------------------------------------------------------------------
function Drive-Assign-Letter-By-Guid {
    [CmdletBinding(SupportsShouldProcess)]
    param(
        [Parameter(Mandatory = $true)]
        [string]$VolumeGuid,

        [Parameter(Mandatory = $true)]
        [ValidatePattern("^[A-Z]$")]
        [string]$DriveLetter
    )

    try {
        # 1. 查找对应的分区对象
        $partition = Get-Partition | Where-Object {
            $_.AccessPaths -like "*$VolumeGuid*"
        }

        if (-not $partition) {
            throw "未找到 Volume GUID 为 $VolumeGuid 的分区。请检查 GUID 是否正确。"
        }

        if ($partition.DriveLetter) {
            Write-Warning "该分区当前已分配盘符: $($partition.DriveLetter):"
            #$confirm = Read-Host "是否覆盖原有盘符并分配为 ${DriveLetter}: ? (Y/N)"
            #if ($confirm -ne 'Y') { return }
            return
        }

        # 2. 执行分配
        Set-Partition -InputObject $partition -NewDriveLetter $DriveLetter

        Write-Host "✅ 成功: 已将盘符 ${DriveLetter}: 分配给 GUID $VolumeGuid" -ForegroundColor Green
    }
    catch {
        Write-Error "❌ 失败: $_"
    }
}

# -----------------------------------------------------------------------------
# 函数 3: 根据 Volume GUID 移除盘符
# -----------------------------------------------------------------------------
function Drive-Remove-Letter-By-Guid {
    [CmdletBinding(SupportsShouldProcess)]
    param(
        [Parameter(Mandatory = $true)]
        [string]$VolumeGuid
    )

    try {
        # 1. 查找对应的分区对象
        $partition = Get-Partition | Where-Object {
            $_.AccessPaths -like "*$VolumeGuid*"
        }

        if (-not $partition) {
            throw "未找到 Volume GUID 为 $VolumeGuid 的分区。"
        }

        if (-not $partition.DriveLetter) {
            Write-Warning "该分区当前没有分配盘符,无需移除。"
            return
        }

        $currentLetter = $partition.DriveLetter
        $accessPath = "${currentLetter}:\"

        # 2. 执行移除
        Remove-PartitionAccessPath -InputObject $partition -AccessPath $accessPath

        Write-Host "✅ 成功: 已移除 GUID $VolumeGuid 的盘符 ${currentLetter}:" -ForegroundColor Yellow
    }
    catch {
        Write-Error "❌ 失败: $_"
    }
}

# -----------------------------------------------------------------------------
# 函数 4: 写满指定盘符所在的分区
# -----------------------------------------------------------------------------
function Drive-Fill-Disk {
    [CmdletBinding(SupportsShouldProcess)]
    param(
        [Parameter(Mandatory = $true)]
        [ValidatePattern('^[A-Za-z]:?$')]
        [string]$Drive,

        # 单个文件的大小(MB),写满后自动写下一个文件,避免 FAT32 等单文件 4GB 限制
        [ValidateRange(1, 4096)]
        [int]$FileSizeMB = 1024
    )

    $letter = $Drive.Trim().TrimEnd(':').ToUpperInvariant()
    $volume = Get-Volume -DriveLetter $letter -ErrorAction SilentlyContinue
    if (-not $volume) {
        Write-Error "❌ 失败: 未找到盘符 ${letter}: 对应的分区。"
        return
    }

    $root = "${letter}:\"
    if (-not (Test-Path -LiteralPath $root)) {
        Write-Error "❌ 失败: ${root} 不可访问。"
        return
    }

    $label = $volume.FileSystemLabel ? $volume.FileSystemLabel : $volume.FileSystemType
    Write-Warning "即将写满分区 ${root} (${label},可用 $(Format-Byte -Value $volume.SizeRemaining)),写入期间系统可能变慢。"
    Write-Warning "生成的文件不会被自动删除,需要手工清理 ${root}fill-disk-<序号>-<随机 GUID>.bin。"

    # 第一次确认
    if (-not $PSCmdlet.ShouldProcess($root, '写满该分区')) {
        Write-Host "已取消。" -ForegroundColor Yellow
        return
    }

    # 第二次确认: 必须手工输入盘符
    $confirm = Read-Host "二次确认: 请输入盘符 $letter 以继续"
    if ($confirm.Trim().TrimEnd(':').ToUpperInvariant() -ne $letter) {
        Write-Host "输入的盘符不匹配,已取消。" -ForegroundColor Yellow
        return
    }

    $chunk = New-Object byte[] (1MB)
    $maxFileSize = [long]$FileSizeMB * 1MB
    # 每次执行随机生成一个 GUID,保证不会与之前生成的文件重名
    $runGuid = [guid]::NewGuid().ToString()
    $fileIndex = 0
    $fileCount = 0
    $totalBytes = [long]0
    $stream = $null
    $stopwatch = [System.Diagnostics.Stopwatch]::StartNew()

    try {
        while ($true) {
            $filePath = Join-Path $root ('fill-disk-{0:D6}-{1}.bin' -f $fileIndex, $runGuid)
            $fileIndex++

            # CreateNew 保证不会覆盖分区上已有的同名文件
            $stream = [System.IO.File]::Open($filePath, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None)
            $fileCount++

            $fileBytes = [long]0
            while ($fileBytes -lt $maxFileSize) {
                $stream.Write($chunk, 0, $chunk.Length)
                $fileBytes += $chunk.Length
                $totalBytes += $chunk.Length
            }

            $stream.Dispose()
            $stream = $null
        }
    }
    catch [System.IO.IOException] {
        # ERROR_DISK_FULL(112) / ERROR_HANDLE_DISK_FULL(39) 表示分区已经写满
        if ($_.Exception.HResult -eq -2147024784 -or $_.Exception.HResult -eq -2147024857) {
            Write-Host "✅ 完成: 分区 ${root} 已写满。" -ForegroundColor Green
        }
        else {
            Write-Error "❌ 失败: $($_.Exception.Message)"
        }
    }
    catch {
        Write-Error "❌ 失败: $($_.Exception.Message)"
    }
    finally {
        if ($stream) {
            $stream.Dispose()
        }

        $stopwatch.Stop()
        $remaining = (Get-Volume -DriveLetter $letter).SizeRemaining
        Write-Host ("写入 {0} 个文件,共 {1},耗时 {2},剩余可用空间 {3}" -f $fileCount, (Format-Byte -Value $totalBytes), $stopwatch.Elapsed, (Format-Byte -Value $remaining))
    }
}
################################
# powershell env functions
################################

[string]$APP_DIR = 'd:\_app\';
[string]$HOME_DIR = 'd:\_home';
[string]$LANG_DIR = 'd:\_lang\';
[string]$CACHE_DIR = 'd:\_cache\';
[string]$CONFIG_DIR = 'd:\_config\';
[string]$DATA_DIR = 'd:\_data\';
[string]$LOG_DIR = 'd:\_log\';
[string]$PATH_SPLIT = ';';

function script:Env-TrySetVariable (
    [string]$Variable = $(throw "Variable is null!"),
    [string]$Value = $(throw "Value is null!")
) {
    $Target = [System.EnvironmentVariableTarget]::Machine

    # 输出旧值
    [string]$OldValue = [System.Environment]::GetEnvironmentVariable($Variable, $Target);
    Console-Info "[$Target][$Variable] OLD_VALUE : " $OldValue

    if ($OldValue -eq $Value) {
        Console-Warn "[$Target][$Variable] NEW_VALUE : " $Value
        return
    }

    # 设置环境变量
    [System.Environment]::SetEnvironmentVariable($Variable, $Value, $Target)

    # 输出新值
    [string]$NewValue = [System.Environment]::GetEnvironmentVariable($Variable, $Target);
    Console-Debug "[$Target][$Variable] NEW_VALUE : " $NewValue
    Write-Host
}

function script:Env-TryAppendPathVariable (
    [string]$Value = $(throw "Value is null!")
) {
    $Target = [System.EnvironmentVariableTarget]::Machine
    $Variable = 'Path'
    # 获取旧值
    [string]$OldValue = [System.Environment]::GetEnvironmentVariable($Variable, $Target);
    [array]$OldValueArray = $OldValue -Split $PATH_SPLIT

    # 检测是否已经存在
    if ($OldValueArray -Contains $Value) {
        Console-Warn "[$Target][$Variable] EXISTS_VALUE : $Value"
        return
    }

    Console-Debug "[$Target][$Variable] APPEND_VALUE : $Value"

    # 追加新值
    $OldValueArray += $Value;
    [string]$NewValue = $($OldValueArray | Where-Object { $_ } | Sort-Object -Unique -CaseSensitive:$false | Join-String -Separator $PATH_SPLIT);

    Env-TrySetVariable -Variable $Variable -Value $NewValue
}


function Env-TrySetAll() {
    Get-Command -Name 'Env-Set*EnvironmentVariable' -CommandType Function | ForEach-Object {
        Console-Info "RUN : $($_.Name)"
        Invoke-Expression -Command $_.Name
        Write-Host
        Write-Host
    }
}

function Env-GetAllVariable() {
    Get-ChildItem ENV:
}

function Env-GetPathVariavle() {
    $ENV:PATH -Split $PATH_SPLIT | Sort-Object
}

# https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
function Env-SetXDGEnvironmentVariable() {
    Env-TrySetVariable -Variable 'XDG_CONFIG_HOME' -Value $CONFIG_DIR
    Env-TrySetVariable -Variable 'XDG_CACHE_HOME' -Value $CACHE_DIR
    Env-TrySetVariable -Variable 'XDG_DATA_HOME' -Value $DATA_DIR
}

function Env-SetHomeEnvironmentVariable() {
    Env-TrySetVariable -Variable 'HOME_D' -Value $HOME_DIR
    Env-TrySetVariable -Variable 'HOME_APP' -Value $APP_DIR
    Env-TrySetVariable -Variable 'HOME_APP_LOG' -Value $LOG_DIR
    Env-TrySetVariable -Variable 'HOME_APP_CONFIG' -Value $CONFIG_DIR
    Env-TrySetVariable -Variable 'HOME_APP_CACHE' -Value $CACHE_DIR
    Env-TrySetVariable -Variable 'HOME_APP_DATA' -Value $DATA_DIR
}

# https://github.com/MicrosoftArchive/redis/releases
function Env-SetRedisEnvironmentVariable() {
    $APP_REDIS_DIR = $LANG_DIR + '_redis\';

    Env-TryAppendPathVariable -Value $APP_REDIS_DIR
}

# https://www.mongodb.org/dl/win32/x86_64-2008plus-ssl
function Env-SetMongoDBEnvironmentVariable() {
    $APP_MONGO_DIR = $LANG_DIR + '_mongo\';

    Env-TryAppendPathVariable -Value $APP_MONGO_DIR
}

# https://www.putty.org/
# https://the.earth.li/~sgtatham/putty/latest/w64/putty.zip
function Env-SetPuttyEnvironmentVariable() {
    $APP_PUTTY_DIR = $APP_DIR + '_putty\';

    Env-TryAppendPathVariable -Value $APP_PUTTY_DIR
}

# https://github.com/shadowsocks/shadowsocks-windows
# function Env-SetShadowsocksEnvironmentVariable() {
#     $APP_SHADOWSOCKS_DIR = $APP_DIR + '_shadowsocks\';

#     Env-TryAppendPathVariable -Value $APP_SHADOWSOCKS_DIR
# }

# https://adoptopenjdk.net/upstream.html
# https://developers.redhat.com/products/openjdk/download
# https://arthas.aliyun.com/arthas-boot.jar
function Env-SetJavaEnvironmentVariable() {
    $APP_JAVA_DIR = $LANG_DIR + '_java\';
    $APP_ARTHAS_BOOT_DIR = $LANG_DIR + '_arthas_boot\';
    $APP_JAVA_BIN_DIR = $APP_JAVA_DIR + 'bin\';

    #Env-TrySetVariable -Variable 'JAVA_TOOL_OPTIONS' -Value '-Dfile.encoding=UTF-8'

    Env-TrySetVariable -Variable 'JAVA_HOME' -Value $APP_JAVA_DIR
    Env-TrySetVariable -Variable 'ARTHAS_BOOT_HOME' -Value $APP_ARTHAS_BOOT_DIR

    Env-TryAppendPathVariable -Value $APP_JAVA_BIN_DIR
}

# https://golang.org/doc/install
function Env-SetGoEnvironmentVariable() {
    $APP_GO_DIR = $LANG_DIR + '_go\';
    $APP_GO_BIN_DIR = $APP_GO_DIR + 'bin\';

    $CACHE_GO_DIR = $CACHE_DIR + '_go\';

    Env-TrySetVariable -Variable 'GOROOT' -Value $APP_GO_DIR
    Env-TrySetVariable -Variable 'GOCACHE' -Value $CACHE_GO_DIR
    Env-TryAppendPathVariable -Value $APP_GO_BIN_DIR
}

# https://rubyinstaller.org/downloads/
function Env-SetRubyEnvironmentVariable() {
    $APP_RUBY_DIR = $LANG_DIR + '_ruby\';
    $APP_RUBY_BIN_DIR = $APP_RUBY_DIR + 'bin\';

    Env-TrySetVariable -Variable 'RUBY_HOME' -Value $APP_RUBY_DIR
    Env-TryAppendPathVariable -Value $APP_RUBY_BIN_DIR
}

# https://nodejs.org/en/download/
# https://nodejs.org/download/release/latest/
function Env-SetNodeEnvironmentVariable() {
    $APP_NODE_DIR = $LANG_DIR + '_node\';
    $APP_NODE_MODULES_DIR = $APP_NODE_DIR + 'node_modules\';

    $CACHE_NODE_DIR = $CACHE_DIR + '_node\';

    Env-TrySetVariable -Variable 'NODE_PATH' -Value $APP_NODE_MODULES_DIR
    Env-TryAppendPathVariable -Value $APP_NODE_DIR

    npm config set cache $CACHE_NODE_DIR --global
    npm config set registry "http://registry.npmmirror.com" --global
    npm install -g cnpm --registry=http://registry.npmmirror.com
}


# https://kotlinlang.org/docs/tutorials/command-line.html
function Env-SetKotlinEnvironmentVariable() {
    $APP_KOTLIN_DIR = $LANG_DIR + '_kotlin\'
    $APP_KOTLIN_BIN_DIR = $APP_KOTLIN_DIR + 'bin\'

    Env-TryAppendPathVariable -Value $APP_KOTLIN_BIN_DIR
}


# https://dotnet.github.io/
# https://docs.microsoft.com/en-us/dotnet/core/tools/telemetry
function Env-SetNetEnvironmentVariable() {
    Env-TrySetVariable -Variable 'DOTNET_CLI_TELEMETRY_OPTOUT' -Value "true"
}

# https://www.python.org/downloads/windows/
# Windows x86-64 embeddable zip file
function Env-SetPythonEnvironmentVariable() {
    $APP_PYTHON_DIR = $LANG_DIR + '_python\';
    $APP_PYTHON_SCRIPTS_DIR = $APP_PYTHON_DIR + 'scripts\';

    Env-TryAppendPathVariable -Value $APP_PYTHON_DIR
    Env-TryAppendPathVariable -Value $APP_PYTHON_SCRIPTS_DIR
}

# https://github.com/icsharpcode/ILSpy/releases
function Env-SetILSpyEnvironmentVariable() {
    $APP_ILSPY_DIR = $LANG_DIR + '_ilspy\';

    Env-TryAppendPathVariable -Value $APP_ILSPY_DIR
}

# https://www.nuget.org/downloads
# https://docs.microsoft.com/en-us/nuget/tools/cli-ref-environment-variables
function Env-SetNugetEnvironmentVariable() {
    $APP_NUGET_DIR = $LANG_DIR + '_nuget\';

    Env-TryAppendPathVariable -Value $APP_NUGET_DIR
}

# https://developer.android.com/studio/releases/platform-tools.html
function Env-SetADBEnvironmentVariable() {
    $APP_ADB_DIR = $APP_DIR + '_adb\';

    Env-TryAppendPathVariable -Value $APP_ADB_DIR
}

# https://www.cpuid.com/softwares/cpu-z.html
function Env-SetCPUZEnvironmentVariable() {
    $APP_CPUZ_DIR = $APP_DIR + '_cpu-z\';

    Env-TryAppendPathVariable -Value $APP_CPUZ_DIR
}

# https://www.techpowerup.com/gpuz/
function Env-SetGPUZEnvironmentVariable() {
    $APP_GPUZ_DIR = $APP_DIR + '_gpu-z\';

    Env-TryAppendPathVariable -Value $APP_GPUZ_DIR
}

# http://www.superpi.net/Download/
function Env-SetPIEnvironmentVariable() {
    $APP_PI_DIR = $APP_DIR + '_pi\';

    Env-TryAppendPathVariable -Value $APP_PI_DIR
}

# https://maven.apache.org/
# https://maven.apache.org/settings.html
function Env-SetMavenEnvironmentVariable() {
    $APP_MAVEN_DIR = $LANG_DIR + '_maven\'
    $APP_MAVEN_BIN_DIR = $APP_MAVEN_DIR + 'bin\'

    # for maven 1
    Env-TrySetVariable -Variable 'MAVEN_HOME' -Value $APP_MAVEN_DIR

    # for maven 2 or 3
    Env-TrySetVariable -Variable 'M2_HOME' -Value $APP_MAVEN_DIR

    # http://maven.apache.org/configure.html
    Env-TrySetVariable -Variable 'MAVEN_OPTS' -Value '-Xms256m -Xmx1024m'

    Env-TryAppendPathVariable -Value $APP_MAVEN_BIN_DIR
}

# https://maven.apache.org/configure.html
function Env-SetMvndEnvironmentVariable() {
    $APP_MVND_DIR = $LANG_DIR + '_mvnd\'
    $APP_MVND_BIN_DIR = $APP_MVND_DIR + 'bin\'

    Env-TryAppendPathVariable -Value $APP_MVND_BIN_DIR
}

# https://gradle.org/releases/
# https://docs.gradle.org/current/userguide/installation.html
# https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_environment_variables
function Env-SetGradleEnvironmentVariable() {
    $APP_GRADLE_DIR = $LANG_DIR + '_gradle\';
    $APP_GRADLE_BIN_DIR = $APP_GRADLE_DIR + 'bin\';

    $CACHE_GRADLE_DIR = $CACHE_DIR + '_gradle\';

    Env-TrySetVariable -Variable 'GRADLE_HOME' -Value $APP_GRADLE_DIR
    Env-TrySetVariable -Variable 'GRADLE_USER_HOME' -Value $CACHE_GRADLE_DIR
    Env-TryAppendPathVariable -Value $APP_GRADLE_BIN_DIR
}

# https://projects.spring.io/spring-boot/
function Env-SetSpringBootCliEnvironmentVariable() {
    $APP_SPRING_BOOT_CLI_DIR = $LANG_DIR + '_spring-boot-cli\';
    $APP_SPRING_BOOT_CLI_BIN_DIR = $APP_SPRING_BOOT_CLI_DIR + 'bin\';

    Env-TryAppendPathVariable -Value $APP_SPRING_BOOT_CLI_BIN_DIR
}

# http://httpd.apache.org/download.cgi
function Env-SetHttpdEnvironmentVariable() {
    $APP_HTTPD_DIR = $LANG_DIR + '_httpd\';
    $APP_HTTPD_BIN_DIR = $APP_HTTPD_DIR + 'bin\';

    Env-TryAppendPathVariable -Value $APP_HTTPD_BIN_DIR
}

# https://jmeter.apache.org/download_jmeter.cgi
function Env-SetJmeterEnvironmentVariable() {
    $APP_JMETER_DIR = $LANG_DIR + '_jmeter\';
    $APP_JMETER_BIN_DIR = $APP_JMETER_DIR + 'bin\';

    Env-TryAppendPathVariable -Value $APP_JMETER_BIN_DIR
}

# http://nginx.org/en/download.html
function Env-SetNginxEnvironmentVariable() {
    $APP_NGINX_DIR = $LANG_DIR + '_nginx\';

    Env-TryAppendPathVariable -Value $APP_NGINX_DIR
}

# https://kubernetes.io/docs/tasks/tools/install-kubectl
function Env-SetKubectlEnvironmentVariable() {
    $APP_KUBECTL_DIR = $LANG_DIR + '_kubectl\';

    $CONFIG_KUBECTL_DIR = $CONFIG_DIR + '_kubectl\';
    $CONFIG_KUBECTL_CONFIG_FILE = $CONFIG_KUBECTL_DIR + 'config.yml';

    Env-TrySetVariable -Variable 'KUBECONFIG' -Value $CONFIG_KUBECTL_CONFIG_FILE
    Env-TryAppendPathVariable -Value $APP_KUBECTL_DIR
}

# https://github.com/kubernetes/minikube/releases
# function Env-SetMinikubeEnvironmentVariable() {
#     $APP_MINIKUBE_DIR = $LANG_DIR + '_minikube\';
#     $DATA_MINIKUBE_DIR = 'e:\_minikube\';

#     Env-TrySetVariable -Variable 'MINIKUBE_HOME' -Value $DATA_MINIKUBE_DIR
#     Env-TrySetVariable -Variable 'MINIKUBE_WANTUPDATENOTIFICATION' -Value 'false'
#     Env-TrySetVariable -Variable 'MINIKUBE_WANTREPORTERRORPROMPT' -Value 'false'
#     Env-TrySetVariable -Variable 'CHANGE_MINIKUBE_NONE_USER' -Value 'true'
#     Env-TryAppendPathVariable -Value $APP_MINIKUBE_DIR
# }

# https://docs.docker.com/engine/reference/commandline/cli/#environment-variables
# https://docs.docker.com/engine/reference/commandline/dockerd/#daemon-socket-option
function Env-SetDockerEnvironmentVariable() {
    $APP_DOCKER_DIR = $APP_DIR + '_docker\';
    $CONFIG_DOCKER_DIR = $CONFIG_DIR + '_docker\';

    Env-TrySetVariable -Variable 'DOCKER_CONFIG' -Value $CONFIG_DOCKER_DIR
    Env-TrySetVariable -Variable 'DOCKER_HOST' -Value 'tcp://127.0.0.1:2375'
    Env-TryAppendPathVariable -Value $APP_DOCKER_DIR
}

# https://docs.docker.com/machine
# https://docs.docker.com/machine/drivers/hyper-v/
# function Env-SetDockerMachineEnvironmentVariable() {
#     $APP_DOCKER_DIR = $APP_DIR + '_docker\';
#     $BOOT2DOCKER_ISO_DIR = 'file://' + $APP_DOCKER_DIR + 'boot2docker.iso';

#     $DATA_DOCKER_DIR = 'e:\_docker\';

#     Env-TrySetVariable -Variable 'MACHINE_STORAGE_PATH' -Value $DATA_DOCKER_DIR
#     Env-TrySetVariable -Variable 'MACHINE_NATIVE_SSH' -Value 1
#     Env-TrySetVariable -Variable 'HYPERV_BOOT2DOCKER_URL' -Value $BOOT2DOCKER_ISO_DIR
#     Env-TrySetVariable -Variable 'HYPERV_VIRTUAL_SWITCH' -Value 'HVS'
#     Env-TrySetVariable -Variable 'HYPERV_CPU_COUNT' -Value 1
#     Env-TrySetVariable -Variable 'HYPERV_MEMORY' -Value 1024
#     Env-TrySetVariable -Variable 'HYPERV_DISK_SIZE' -Value 10240

#     Env-TryAppendPathVariable -Value $APP_DOCKER_DIR
# }

# https://helm.sh/docs
# https://github.com/helm/helm-www
# https://github.com/helm/helm/releases
function Env-SetHelmEnvironmentVariable() {
    $APP_HLEM_DIR = $LANG_DIR + '_helm\';

    Env-TryAppendPathVariable -Value $APP_HLEM_DIR
}

# https://github.com/mholt/caddy
# https://caddyserver.com/docs/cli
# function Env-SetCaddyEnvironmentVariable() {
#     $APP_CADDY_DIR = $LANG_DIR + '_caddy\';

#     Env-TryAppendPathVariable -Value $APP_CADDY_DIR
# }

# https://coreos.com/os/docs/1911.5.0/overview-of-ct.html
# https://github.com/coreos/container-linux-config-transpiler
# function Env-SetCoreOSEnvironmentVariable() {
#     $APP_COREOS_DIR = $LANG_DIR + '_coreos\';

#     Env-TryAppendPathVariable -Value $APP_COREOS_DIR
# }

# https://docs.microsoft.com/en-us/powershell/scripting/overview?view=powershell-6
function Env-SetPowerShellEnvironmentVariable() {
    Env-TrySetVariable -Variable 'POWERSHELL_TELEMETRY_OPTOUT' -Value 'true'
}

# https://github.com/v2ray/v2ray-core
function Env-SetV2RayEnvironmentVariable() {
    $APP_V2RAY_DIR = $APP_DIR + '_v2ray\';

    Env-TryAppendPathVariable -Value $APP_V2RAY_DIR
}

function Env-SetLocaleEnvironmentVariable() {
    Env-TrySetVariable -Variable 'LC_ALL' -Value 'zh_CN.UTF-8'
    Env-TrySetVariable -Variable 'LANG' -Value 'C.UTF-8'
}

# https://www.alex-is.de/PHP/fusion/downloads.php?cat_id=4&download_id=9
function Env-SetASSSDBenchmarkEnvironmentVariable() {
    $APP_AS_SSD_BENCHMARK_DIR = $APP_DIR + '_as-ssd-benchmark\';

    Env-TryAppendPathVariable -Value $APP_AS_SSD_BENCHMARK_DIR
}

# https://crystalmark.info/en/download/
function Env-SetDiskInfoEnvironmentVariable() {
    $APP_DISK_INFO_DIR = $APP_DIR + '_disk-info\';

    Env-TryAppendPathVariable -Value $APP_DISK_INFO_DIR
}

# https://github.com/pbatard/rufus
function Env-SetRufusEnvironmentVariable() {
    $APP_RUFUS_DIR = $APP_DIR + '_rufus\';

    Env-TryAppendPathVariable -Value $APP_RUFUS_DIR
}

# https://github.com/FFmpeg/FFmpeg
function Env-SetFFmpegEnvironmentVariable() {
    $APP_FFMPEG_DIR = $APP_DIR + '_ffmpeg\bin';

    Env-TryAppendPathVariable -Value $APP_FFMPEG_DIR
}

# https://www.rust-lang.org/
function Env-SetRustEnvironmentVariable() {
    $APP_RUSTUP_DIR = $LANG_DIR + '_rustup\';
    $APP_CARGO_DIR = $LANG_DIR + '_cargo\';
    $APP_CARGO_BIN_DIR = $APP_CARGO_DIR + 'bin\';

    # https://github.com/rust-lang/rustup.rs#environment-variables
    Env-TrySetVariable -Variable 'RUSTUP_HOME' -Value $APP_RUSTUP_DIR
    Env-TrySetVariable -Variable 'RUSTUP_DIST_SERVER' -Value 'http://mirrors.ustc.edu.cn/rust-static'
    Env-TrySetVariable -Variable 'RUSTUP_UPDATE_ROOT' -Value 'http://mirrors.ustc.edu.cn/rust-static/rustup'

    # https://github.com/rust-lang/cargo/blob/master/src/doc/src/reference/environment-variables.md
    Env-TrySetVariable -Variable 'CARGO_HOME' -Value $APP_CARGO_DIR

    Env-TrySetVariable -Variable 'RUST_BACKTRACE' -Value 'full'
    Env-TrySetVariable -Variable 'RUST_TEST_NOCAPTURE' -Value '0'

    Env-TryAppendPathVariable -Value $APP_CARGO_BIN_DIR
}

# https://github.com/gohugoio/hugo
function Env-SetHugoEnvironmentVariable() {
    $APP_HUGO_DIR = $APP_DIR + '_hugo\';
    $CACHE_HUGO_DIR = $CACHE_DIR + '_hugo\';

    Env-TryAppendPathVariable -Value $APP_HUGO_DIR
    Env-TrySetVariable -Variable 'HUGO_CACHEDIR' -Value $CACHE_HUGO_DIR
}

# https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
# https://wiki.wireshark.org/TLS
function Env-SetSslKeyLogFileEnvironmentVariable() {
    $CACHE_SSL_DIR = $CACHE_DIR + '_ssl\';

    $SSLKEYLOGFILE = $CACHE_SSL_DIR + 'ssl.log';

    Env-TrySetVariable -Variable 'SSLKEYLOGFILE' -Value $SSLKEYLOGFILE
}

# https://dev.mysql.com/downloads/mysql/
# https://dev.mysql.com/doc/refman/8.0/en/windows-install-archive.html
# https://dev.mysql.com/doc/refman/8.0/en/environment-variables.html
function Env-SetMySqlEnvironmentVariable() {
    $APP_MYSQL_DIR = $LANG_DIR + '_mysql\';
    $CACHE_MYSQL_DIR = $CACHE_DIR + '_mysql\';
    $DATA_MYSQL_DIR = $DATA_DIR + '_mysql\';
    $APP_MYSQL_BIN_DIR = $APP_MYSQL_DIR + 'bin\';
    $MYSQL_HISTFILE = $CACHE_MYSQL_DIR + '.history';

    Env-TrySetVariable -Variable 'MYSQL_HOME' -Value $APP_MYSQL_DIR
    Env-TrySetVariable -Variable 'MYSQL_DATA' -Value $DATA_MYSQL_DIR
    Env-TrySetVariable -Variable 'MYSQL_HISTFILE' -Value $MYSQL_HISTFILE
    Env-TryAppendPathVariable -Value $APP_MYSQL_BIN_DIR
}

# https://github.com/svenstaro/miniserve
function Env-SetMiniServeEnvironmentVariable() {
    $APP_MINISERVE_DIR = $APP_DIR + '_miniserve\';

    Env-TryAppendPathVariable -Value $APP_MINISERVE_DIR
}

# https://github.com/wagoodman/dive
function Env-SetDiveEnvironmentVariable() {
    $APP_DIVE_DIR = $APP_DIR + '_dive\';

    Env-TryAppendPathVariable -Value $APP_DIVE_DIR
}

# https://www.voidtools.com/zh-cn/
function Env-SetEverythingEnvironmentVariable() {
    $APP_EVERYTHING_DIR = $APP_DIR + '_everything\';

    Env-TryAppendPathVariable -Value $APP_EVERYTHING_DIR
}

# iperf2 https://sourceforge.net/projects/iperf2/
# iperf3 https://iperf.fr/
function Env-SetIperfEnvironmentVariable() {
    $APP_IPERF_DIR = $APP_DIR + '_iperf\';

    Env-TryAppendPathVariable -Value $APP_IPERF_DIR
}

# https://download.sysinternals.com/files/SysinternalsSuite.zip
# https://learn.microsoft.com/zh-cn/sysinternals/downloads/
function Env-SetSysinternalsEnvironmentVariable() {
    $APP_SYSINTERNALS_DIR = $APP_DIR + '_sysinternals\';

    Env-TryAppendPathVariable -Value $APP_SYSINTERNALS_DIR
}


# https://github.com/winscp/winscp
# https://winscp.net/eng/index.php
# https://winscp.net/download/WinSCP-6.5.2-Portable.zip/download
function Env-SetWinScpEnvironmentVariable() {
    $APP_WINSCP_DIR = $APP_DIR + '_winscp\';

    Env-TryAppendPathVariable -Value $APP_WINSCP_DIR
}


# https://github.com/hacdias/webdav
# https://github.com/hacdias/webdav/releases/download/v5.8.0/windows-amd64-webdav.zip
function Env-SetWebDavEnvironmentVariable() {
    $APP_WEBDAV_DIR = $APP_DIR + '_webdav\';

    Env-TryAppendPathVariable -Value $APP_WEBDAV_DIR
}

# https://github.com/sigoden/dufs
# https://github.com/sigoden/dufs/releases/download/v0.43.0/dufs-v0.43.0-x86_64-pc-windows-msvc.zip
function Env-SetDuFsEnvironmentVariable() {
    $APP_DUFS_DIR = $APP_DIR + '_dufs\';

    Env-TryAppendPathVariable -Value $APP_DUFS_DIR
}

# https://docs.sftpgo.com/
# https://github.com/drakkan/sftpgo
# https://github.com/drakkan/sftpgo/releases/download/v2.6.6/sftpgo_v2.6.6_windows_portable.zip
function Env-SetSFTPGoEnvironmentVariable() {
    $APP_SFTOPGO_DIR = $APP_DIR + '_sftpgo\';

    Env-TryAppendPathVariable -Value $APP_SFTOPGO_DIR
}

# https://www.hibitsoft.ir/
# https://www.hibitsoft.ir/HiBitUninstaller/HiBitUninstaller-Portable-3.2.70.zip
# https://www.hibitsoft.ir/HibitStartup/HiBitStartupManager-Portable-2.6.60.zip
# https://www.hibitsoft.ir/HiBitSysynfo/HiBitSysInfo-Portable-2.1.30.zip
function Env-SetOtherEnvironmentVariable() {
    $APP_HIBIT_DIR = $APP_DIR + '_hibit\';

    Env-TryAppendPathVariable -Value $APP_HIBIT_DIR
}

# 杂项工具
function Env-SetOtherEnvironmentVariable() {
    $APP_OTHER_DIR = $APP_DIR + '_other\';

    Env-TryAppendPathVariable -Value $APP_OTHER_DIR
}
################################
# FastCopy env functions
################################

function PS-Fast-Copy() {
    param($source, $target)
    $fcpPath = 'c:\_fast-copy\fastcopy.exe';
    $option = '/cmd=diff /open_window /estimate /balloon /error_stop=FALSE /speed=full /stream /acl';
    $commonExclude = '\$RECYCLE.BIN\;\System Volume Information\;\Recovery\;';
    $exclude = "/exclude='\_app2\;\_cache\;\_code\;\_data\;\_github\;\_lang\;\_vhd\;\_video2\;$commonExclude'";
    $command = "$fcpPath $option $exclude `"$source`" /to=`"$target`""
    Console-Debug $command
    Invoke-Expression $command
}

function PS-Fast-Copy-Driver {
    param($driver, $targetDir)
    PS-Fast-Copy -source "${driver}:\" -target "y:\${targetDir}\"
}

function PS-Fast-Copy-Home {
    PS-Fast-Copy-Driver -driver d -targetDir _home
}

function PS-Fast-Copy-Blob {
    PS-Fast-Copy-Driver -driver e -targetDir _blob
}

function PS-Fast-Copy-Mirror {
    PS-Fast-Copy-Driver -driver f -targetDir _mirror
}

function PS-Fast-Copy-Media {
    PS-Fast-Copy-Driver -driver g -targetDir _media
}

function PS-Fast-Copy-All {
    PS-Fast-Copy-Home
    PS-Fast-Copy-Blob
    PS-Fast-Copy-Mirror
    PS-Fast-Copy-Media
}
################################
# powershell file functions
################################

function File-Get-Big-Files ([int]$top = 20) {
    $begin = Get-Date
    Console-Debug "begin..." $begin

    Get-ChildItem -Path $(Get-Location) -File -Recurse |
    Sort-Object Length -Descending |
    Select-Object -First $top |
    Format-Table -Property @{Label = "Size"; Expression = { ($_.Length / 1MB).ToString(('0.000')) + 'MB' } }, FullName -Wrap

    $end = Get-Date
    Console-Debug "end..." $end
    Console-Debug "elapsed times" ($end - $begin)
}


function File-Get-All {
    param (
        [string] $Path = $(Get-Location)
    )

    Get-ChildItem -Path $Path -Directory | ForEach-Object {
        File-GetAll -Path $_
    }

    Get-ChildItem -Path $Path -File | ForEach-Object {
        $_.FullName
    }
}

function File-Diff {
    param (
        [string] $PartFile,
        [string] $FullFile
    )

    $PartContent = $(Get-Content $PartFile)
    Get-Content -Path $FullFile | ForEach-Object {
        if ($PartContent.Contains($_) -eq $FALSE) {
            $_
        }
    }
}

function Console-ReadLine {
    param (
        [String]$Prompt,
        [String]$DefaultValue
    )
    $Input = Read-Host -Prompt "$Prompt,default $DefaultValue"
    $Input = (-not($input))?"$DefaultValue":"$Input"
    Write-host "$Prompt $Input" -ForegroundColor Green
    return $Input
}

function Console-Info() {
    Write-Host $Args -ForegroundColor Gray
}

function Console-Warn() {
    Write-Host $Args -ForegroundColor Yellow
}

function Console-Debug() {
    Write-Host $Args -ForegroundColor Green
}

function Console-Debug-Name-Value(
    [string] $Name,
    [int] $NamePadding,
    [string] $Value
) {
    Write-Host -NoNewline $Name.PadRight($NamePadding)" : "
    Write-Host $Value -ForegroundColor Green
}
function Format-Byte(
    [Parameter(ValueFromPipeline = $True)]
    [long]$Value,
    [string]$Split = ''
) {
    if ($Value -lt 1KB) {
        return $Value.ToString("#0${Split}B")
    }

    if ($Value -lt 1MB) {
        return "$(($Value / 1KB) | Format-Double -Digits 0)${Split}KB"
    }

    if ($Value -lt 1GB) {
        return "$(($Value / 1MB) | Format-Double -Digits 0)${Split}MB"
    }

    if ($Value -lt 1TB) {
        return "$(($Value / 1GB) | Format-Double -Digits 0)${Split}GB"
    }

    if ($Value -lt 1PB) {
        return "$(($Value / 1TB) | Format-Double -Digits 1)${Split}TB"
    }

    return "$(($Value / 1PB) | Format-Double -Digits 1)${Split}PB"
}

function Format-Double(
    [Parameter(ValueFromPipeline = $True)]
    [Double]$Value,
    [Parameter(ValueFromPipeline = $True)]
    [int]$Digits = 1
) {
    if ([System.Math]::Floor($Value).CompareTo($Value) -eq 0) {
        return [System.Math]::Floor($Value)
    }

    return [System.Math]::Round($Value, $Digits)
}

function Format-Mac(
    [Parameter(ValueFromPipeline = $True)]
    [string]$Mac
) {
    $Address = $Null
    if ([System.Net.NetworkInformation.PhysicalAddress]::TryParse($Mac, [ref] $Address) -eq $False) {
        return $Null
    }

    $Hex = $Address.GetAddressBytes() | ForEach-Object { Format-Byte-To-Hex -InputObject $_ }
    return [System.String]::Join(':', $Hex)
}

function Format-Byte-To-Hex() {
    param (
        [Parameter(ValueFromPipeline = $True)]
        [byte]$InputObject
    )
    return $InputObject.ToString('X2');
}
################################
# git functions
################################

# import posh-git module
function Git-Import-Posh-Git () {
    Import-Module posh-git
}

# install posh-git module
function Git-Install-Posh-Git () {
    Install-Module posh-git
}

function Git-Pull-Rebase-Recurse-Recurse () {
    Get-ChildItem -Attributes Directory -Path (Get-Location) | ForEach-Object {
        $Path = $_.FullName.ToLower()
        Log-Debug "`ncd $Path"
        Set-Location $Path

        Log-Debug 'Git-Pull-Rebase-Recurse'
        Git-Pull-Rebase-Recurse

        Set-Location -Path ..
    }
}

function Git-Warn-GC-Recurse-Recurse () {
    Get-ChildItem -Attributes Directory -Path (Get-Location) | ForEach-Object {
        $Path = $_.FullName.ToLower()
        Log-Debug "`ncd $Path"
        Set-Location $Path

        Log-Debug 'Git-Warn-GC-Recurse'
        Git-Warn-GC-Recurse

        Set-Location -Path ..
    }
}

# recurse git pull rebase
function Git-Pull-Rebase-Recurse () {
    Get-ChildItem -Attributes Directory -Path (Get-Location) | ForEach-Object {
        $Path = $_.FullName.ToLower()
        Console-Debug "`ncd $Path"
        Set-Location $Path

        Console-Debug 'git remote -v'
        git remote -v

        Console-Debug 'git symbolic-ref HEAD'
        git symbolic-ref HEAD

        Console-Debug "git pull --rebase"
        git pull --rebase

        Set-Location -Path ..
    }
}


function Git-Warn-GC () {
    Console-Debug "git reflog expire --expire=now --all"
    git warn-expire-reflog
    Console-Debug "git gc --prune=now --aggressive"
    git warn-gc-now
    Console-Debug "git count-objects -v -H"
    git size
}

function Git-Warn-GC-Recurse () {
    Get-ChildItem -Attributes Directory -Path (Get-Location) | ForEach-Object {
        $Path = $_.FullName.ToLower()
        Console-Debug "`ncd $Path"
        Set-Location $Path
        Git-Warn-GC
        Set-Location -Path ..
    }
}

function Git-Size-Recurse () {
    Get-ChildItem -Attributes Directory -Path (Get-Location) | ForEach-Object {
        $Path = $_.FullName.ToLower()
        Console-Debug "`ngit -C '$Path' count-objects -v -H"
        git -C "$Path" size
    }
}

function script:Git-Get-All-Objects () {
    $gitObjects = git rev-list --objects --all | git cat-file --batch-check='%(objecttype)|%(objectname)|%(objectsize)|%(rest)'
    return $gitObjects
}

function script:Git-Convert-To-PS-Object ($object) {
    $row = $object.Split('|')

    $gitObject = New-Object PSObject -Property @{
        type = $row[0];
        sha  = $row[1];
        size = [int]($row[2]);
        path = $row[3];
    }

    return $gitObject
}

function script:Git-Get-All-Blob-Objects () {
    $gitBlobObjects = @()
    Git-Get-All-Objects | Foreach-Object {
        if ($_.StartsWith('blob')) {
            $gitBlobObjects += (Git-Convert-To-PS-Object $_)
        }
    }
    return $gitBlobObjects
}


function Git-Get-Big-Files([int]$top = 20) {
    $begin = Get-Date
    Console-Debug "begin..." $begin

    Git-Get-All-Blob-Objects |
    Sort-Object size -Descending |
    Select-Object -First $top |
    Format-Table -Property sha, @{Label = "size"; Expression = { ($_.size / 1MB).ToString(('0.000')) + 'MB' } }, path -Wrap

    $end = Get-Date
    Console-Debug "end..." $end
    Console-Debug "elapsed times" ($end - $begin)
}

function Git-Set-Global-Alias () {

    # checkout
    git config --global alias.co checkout

    # commit
    git config --global alias.ci commit
    git config --global alias.alc 'commit --amend --no-edit'

    # status
    git config --global alias.st 'status --short --branch'

    # branch
    git config --global alias.br branch

    # pull
    git config --global alias.pr 'pull --rebase'

    # merge
    git config --global alias.mnf 'merge --no-ff'

    # diff
    git config --global alias.d diff
    git config --global alias.dt difftool

    # cherry-pick
    git config --global alias.cp cherry-pick

    # log
    git config --global alias.last 'log -1'
    git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"

    # count-objects
    git config --global alias.size 'count-objects -v -H'

    # reflog
    git config --global alias.rl "reflog --format='%cd %h %gs' --date=format:'%Y-%m-%d %H:%M:%S'"

    # gc
    git config --global alias.warn-expire-reflog "reflog expire --expire=now --all"
    git config --global alias.warn-gc-now "gc --prune=now --aggressive"

    # chmod +/- x
    git config --global alias.chmod644 "update-index --chmod=-x"
    git config --global alias.chmod755 "update-index --chmod=+x"

    # head
    git config --global alias.head 'symbolic-ref HEAD'
}

# set global config
function Git-Set-Global-Config () {

    git config --global init.defaultBranch main

    # gui
    git config --global gui.encoding 'utf-8'

    # i18n
    git config --global i18n.commitencoding 'utf-8'
    git config --global core.quotepath false

    # editor
    git config --global core.editor "code -w"
    git config --global core.autocrlf false
    git config --global core.safecrlf true
    git config --global core.filemode false

    # color
    git config --global color.ui true

    # branch pager
    git config --global pager.branch false
}

# set git global user
function Git-Set-Global-User (
    [string] $UserName = $(throw "UserName is null!"),
    [string] $UserEmail = $(throw "UserEmail is null!")
) {

    git config --global user.name $UserName
    git config --global user.email $UserEmail
}

# get git user
function Git-Get-Current-User () {

    $UserName = git config user.name
    $UserEmail = git config user.email
    return "$UserName@<$UserEmail>"
}

# git get config
function Git-Get-Config ([string]$Name) {
    if ($Name) {
        $Values = git config --get-all $Name
        $LocalValues = git config --get-all --local $Name
        $GlobalValues = git config --get-all --global $Name
        $SystemValues = git config --get-all --system $Name

        Write-Host "name   : $Name" -ForegroundColor Green
        Write-Host "value  : $Values" -ForegroundColor Green
        Write-Host "local  : $LocalValues" -ForegroundColor Green
        Write-Host "global : $GlobalValues" -ForegroundColor Green
        Write-Host "system : $SystemValues" -ForegroundColor Green
    }
    else {
        git config --list | Sort-Object
    }
}

function Git-Proxy(
    [switch]$Set = $False
) {
    if ($Set) {
        git config --global http.proxy 'socks5://proxy:1080'
        git config --global https.proxy 'socks5://proxy:1080'
    }
    else {
        git config --global --unset http.proxy
        git config --global --unset https.proxy
        Console-Debug "unset proxy"
    }

    git config --global --get http.proxy
    git config --global --get https.proxy
}
git clone https://github.com/linianhui/benchmark-http.git
git clone https://github.com/linianhui/benchmark-nginx.git
git clone https://github.com/linianhui/blog.git
git clone https://github.com/linianhui/channel9-downloader.git
git clone https://github.com/linianhui/chrome-extensions.git
git clone https://github.com/linianhui/cnblogs-theme.git
git clone https://github.com/linianhui/code.git
git clone https://github.com/linianhui/code-guide.git
git clone https://github.com/linianhui/div.git
git clone https://github.com/linianhui/docker.git
git clone https://github.com/linianhui/example-aspnetcore.git
git clone https://github.com/linianhui/example-cake.git
git clone https://github.com/linianhui/example-java.git
git clone https://github.com/linianhui/example-mongodb.git
git clone https://github.com/linianhui/example-oidc.git
git clone https://github.com/linianhui/example-rabbitmq.git
git clone https://github.com/linianhui/example-spring.git
git clone https://github.com/linianhui/git-web.git
git clone https://github.com/linianhui/I-love-mommy.git
git clone https://github.com/linianhui/jvm.git
git clone https://github.com/linianhui/linianhui.github.io.git
git clone https://github.com/linianhui/networking.git
git clone https://github.com/linianhui/networking-programming.git
git clone https://github.com/linianhui/nuget-server.git

function Gui-Open-Explorer () {
    param (
        [Parameter(Mandatory = $TRUE)]
        [string] $Path = $(throw "Path param is null!")
    )
    if (Directory-Exists-And-Is-Directory -Path $Path) {
        Console-Debug "explorer $Path".ToLower()
        explorer $Path
    }
}
[string]$HIWIFI_GET_UUID_PATH = '/cgi-bin/turbo/proxy/router_info';
[string]$HIWIFI_GET_LOCAL_TOKEN_PATH = '/local-ssh/api?method=get';
[string]$HIWIFI_OPEN_SSH_PATH = '/local-ssh/api?method=valid&data=';
[string]$HIWIFI_CLOSE_SSH_PATH = '/local-ssh/api?method=stop';

function HiWifi-Open-Ssh {
    param (
        [string] $IP = "192.168.199.1"
    )
    $CloudToken = HiWifi-Calc-Cloud-Token -IP $IP

    $Url = "http://" + $IP + $HIWIFI_OPEN_SSH_PATH + $CloudToken
    Console-Debug-Name-Value -NamePadding 25 -Name "Open SSH URL" -Value $Url

    $Result = ((Invoke-WebRequest -Method GET -Uri $Url).Content)
    Console-Debug-Name-Value -NamePadding 25 -Name "Open SSH URL RESPONSE" -Value $Result

    Console-Debug-Name-Value -NamePadding 25 -Name "ssh -v -o KexAlgorithms=+diffie-hellman-group1-sha1 -o HostKeyAlgorithms=+ssh-rsa -o PubkeyAcceptedAlgorithms=+ssh-rsa -o MACs=+hmac-sha1 root@$IP"
    ssh -v -o KexAlgorithms=+diffie-hellman-group1-sha1 -o HostKeyAlgorithms=+ssh-rsa -o PubkeyAcceptedAlgorithms=+ssh-rsa -o MACs=+hmac-sha1 root@$IP
}

function HiWifi-Calc-Cloud-Token() {
    param (
        [Parameter(Mandatory = $TRUE)]
        [string] $IP
    )
    $UuidUrl = "http://" + $IP + $HIWIFI_GET_UUID_PATH
    Console-Debug-Name-Value -NamePadding 25 -Name "Get UUID URL" -Value $UuidUrl

    $UuidResponse = ((Invoke-WebRequest -Method GET -Uri $UuidUrl).Content)
    Console-Debug-Name-Value -NamePadding 25 -Name "Get UUID URL RESPONSE" -Value $UuidResponse

    $Uuid = ($UuidResponse | ConvertFrom-Json).data.uuid
    Console-Debug-Name-Value -NamePadding 25 -Name "UUID" -Value $Uuid

    $LocalTokenUrl = "http://" + $IP + $HIWIFI_GET_LOCAL_TOKEN_PATH
    Console-Debug-Name-Value -NamePadding 25 -Name "Get Local Token" -Value $LocalTokenUrl

    $LocalTokenResponse = ((Invoke-WebRequest -Method GET -Uri $LocalTokenUrl).Content)
    Console-Debug-Name-Value -NamePadding 25 -Name "Get Local Token RESPONSE" -Value $LocalTokenResponse

    $LocalToken = ($LocalTokenResponse | ConvertFrom-Json).data
    Console-Debug-Name-Value -NamePadding 25 -Name "Local Token" -Value $LocalToken

    $CloudToken = HiWifi-Calc-Cloud-Token-Core -Uuid $Uuid -LocalToken $LocalToken
    Console-Debug-Name-Value -NamePadding 25 -Name "Cloud Token" -Value $CloudToken
    return $CloudToken;
}

function HiWifi-Calc-Cloud-Token-Core() {
    param (
        [Parameter(Mandatory = $TRUE)]
        [string] $Uuid,
        [Parameter(Mandatory = $TRUE)]
        [string] $LocalToken
    )
    $Key = HiWifi-Calc-Cloud-Token-Key-Hex -Uuid $Uuid
    $Data = HiWifi-Calc-Cloud-Token-Data-Utf8 -LocalToken $LocalToken
    $HmacSha1 = New-Object System.Security.Cryptography.HMACSHA1
    $HmacSha1.key = [System.Convert]::FromHexString($Key)
    $Hash1 = $HmacSha1.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($Data))
    $Result = [System.Convert]::ToBase64String($Hash1)
    return $Result;
}

function HiWifi-Calc-Cloud-Token-Key-Hex() {
    param (
        [Parameter(Mandatory = $TRUE)]
        [string] $Uuid
    )
    $Stream = [System.IO.MemoryStream]::new()
    $Writer = [System.IO.StreamWriter]::new($Stream)
    $Writer.Write($Uuid)
    $Writer.Flush()
    $Stream.Position = 0
    $Hash = (Get-FileHash -InputStream $Stream -Algorithm SHA1)
    return $Hash.Hash;
}

function HiWifi-Calc-Cloud-Token-Data-Utf8() {
    param (
        [Parameter(Mandatory = $TRUE)]
        [string] $LocalToken
    )
    $UsedLocalTokenBase64 = $LocalToken.Substring(0, 40);
    $UsedLocalTokenBytes = [System.Convert]::FromBase64String($UsedLocalTokenBase64);
    $UsedLocalTokenUtf8 = [System.Text.Encoding]::UTF8.GetString($UsedLocalTokenBytes);
    $Time = $UsedLocalTokenUtf8.Substring(17, 13);
    [Int64]$TimeAdd1 = [System.Convert]::ToInt64($Time) + 1;
    $Result = $UsedLocalTokenUtf8.Replace($Time, $TimeAdd1.ToString());
    return $Result;
}

function Hosts-Edit () {
  code "$ENV:SYSTEMROOT\system32\drivers\etc\hosts"
}

# https://github.com/svenstaro/miniserve
function Http-Server() {
    param (
        [ValidateSet('dufs', 'miniserve', 'sftpgo')]
        [string] $App = 'miniserve',
        [string] $Path = $((Get-Location).Path)
    )

    if ($App -eq 'miniserve') {
        Http-Server-Mineserve -Path $Path
    }

    if ($App -eq 'dufs') {
        Http-Server-Dufs -Path $Path
    }

    if ($App -eq 'sftpgo') {
        Http-Server-SFTPGo -Path $Path
    }
}

# https://github.com/svenstaro/miniserve
function Http-Server-Mineserve() {
    param (
        [string] $Path = $((Get-Location).Path)
    )
    Console-Debug "miniserve --qrcode --upload-files --dirs-first --hide-theme-selector --enable-webdav --interfaces 192.168.2.2 $Path $Args"
    miniserve --qrcode --upload-files --dirs-first --hide-theme-selector --enable-webdav --interfaces 192.168.2.2 $Path
}

# https://github.com/sigoden/dufs
function Http-Server-Dufs() {
    param (
        [string] $Path = $((Get-Location).Path)
    )
    Console-Debug "dufs --bind 192.168.2.2 --port 8080 --allow-all --log-file ${env:HOME_APP_LOG}dufs.log $Path $Args"
    dufs --bind 192.168.2.2 --port 8080 --allow-all --log-file ${env:HOME_APP_LOG}dufs.log $Path
}

# https://docs.sftpgo.com/
function Http-Server-SFTPGo() {
    param (
        [string] $Path = $((Get-Location).Path)
    )
    Console-Debug "sftpgo serve --config-dir ${env:HOME_APP}/_sftpgo $Path $Args"
    sftpgo serve --config-dir ${env:HOME_APP}/_sftpgo $Path
}

function Http-Server-Temp() {
    param (
        [ValidateSet('dufs', 'miniserve', 'sftpgo')]
        [string] $App = 'miniserve'
    )
    Http-Server -App $App -Path 'z:/__temp'
}

function Http-Server-Share() {
    param (
        [ValidateSet('dufs', 'miniserve', 'sftpgo')]
        [string] $App = 'miniserve'
    )
    Http-Server -App $App -Path 'z:/_share'
}
function Idea-Open {
    param (
        [Parameter(Mandatory = $TRUE)]
        [string] $Path = $(throw "Path param is null!")
    )
    if (Directory-Exists-And-Is-Directory -Path $Path) {
        Console-Debug "idea64 $Path".ToLower()
        idea64 $Path
    }
}
################################
# powershell ip functions
################################

function IP-Set() {
    # show all ethernet interfaces
    netsh interface ipv4 show interfaces

    $defaultIdx = 1
    $idx = Console-ReadLine -Prompt "select interface idx" -DefaultValue $defaultIdx

    # show selected ethernet interface address
    netsh interface ipv4 show address name=$idx

    # set dhcp
    $dhcp = Console-ReadLine -Prompt "set source=[dhcp|static]" -DefaultValue 'static'

    if ('dhcp' -ieq $dhcp) {
        netsh interface ipv4 set address name=$idx source=dhcp

        Write-host "show interface $idx current address" -ForegroundColor Green
        netsh interface ipv4 show address name=$idx
        return
    }

    $defaultIP = '192.168.1.2'
    $ip = Console-ReadLine -Prompt 'set ip' -DefaultValue $defaultIP

    $defaultMask = '255.255.255.0'
    $mask = Console-ReadLine -Prompt 'set mask' -DefaultValue $defaultMask

    $defaultGateway = $defaultIP.Substring(0, $defaultIP.LastIndexOf('.')) + '.1'
    $gateway = Console-ReadLine -Prompt 'set gateway' -DefaultValue $defaultGateway

    netsh interface ipv4 set address name=$idx source=static address=$ip mask=$mask gateway=$gateway
    Write-host "netsh interface ipv4 show address name=$idx" -ForegroundColor Green
    netsh interface ipv4 show address name=$idx
}

function IP-Port-Forward-Add (
    [int] $Port,
    [string] $RemoteIp
) {
    Console-Debug "netsh interface portproxy add v4tov4 listenport=$Port connectaddress=$RemoteIp connectport=$Port"
    netsh interface portproxy add v4tov4 listenport=$Port connectaddress=$RemoteIp connectport=$Port
}

function IP-Port-Forward-Delete (
    [int] $Port
) {
    Console-Debug "netsh interface portproxy delete v4tov4 listenport=$Port"
    netsh interface portproxy delete v4tov4 listenport=$Port
}


function IP-Port-Forward-Show (
) {
    Console-Debug "netsh interface portproxy show all"
    netsh interface portproxy show all
}



function Ip-Forward() {
    [CmdletBinding()]
    param (
        [switch]$Stop = $False,
        [string]$RemoteIp = '192.168.2.201'
    )
    @(80, 2375) | ForEach-Object {
        if ($Stop) {
            Ip-Port-Forward-Delete -Port $_
        }
        else {
            Ip-Port-Forward-Add -Port $_ -RemoteIp $RemoteIp
        }
    }
    Ip-Port-Forward-Show
}
function Java-Arthas() {
    # https://arthas.gitee.io/install-detail.html
    Console-Debug "java -jar ${ENV:ARTHAS_BOOT_HOME}arthas-boot.jar --repo-mirror aliyun --use-http $ARGS"
    java -jar ${ENV:ARTHAS_BOOT_HOME}arthas-boot.jar --repo-mirror aliyun --use-http $ARGS
}

function Java-Set-Jdk {
    param (
        [ValidateSet('8', '11', '17', '21')]
        [string] $Version
    )
    $BasePath = 'd:\_lang\_java'
    $JdkPath = $BasePath + $Version

    $CurrentJdkPath = (Get-Item -Path $BasePath).Target
    Console-Info "current jdk path : $CurrentJdkPath"

    if ($JdkPath.Equals($CurrentJdkPath)) {
        Console-Warn "not need change"
    }
    else {
        Console-Warn "Remove-Item $BasePath -Force -Confirm:$False"
        Remove-Item $BasePath -Force -Confirm:$False

        Console-Info "New-Item -ItemType Junction -Path $BasePath -Target $JdkPath | Out-Null"
        Link-Soft -VirtualPath $BasePath -RealPath $JdkPath | Out-Null
    }

    Console-Debug "now jdk path : $((Get-Item -Path $BasePath).Target)"
    java -version
}

function Java8 {
    Java-Set-Jdk -Version 8
}

function Java11 {
    Java-Set-Jdk -Version 11
}

function Java17 {
    Java-Set-Jdk -Version 17
}

function Java21 {
    Java-Set-Jdk -Version 21
}

function Java-Maven-Repository-Soft-Link-Create() {
    Link-Soft -VirtualPath 'd:\_lang\_maven\repository' -RealPath "${ENV:HOME_D}\.m2\repository"
}

# https://github.com/mziyabo/PSKubectlCompletion
function Kubernetes-Import-PS-Kubectl-Completion () {
    Import-Module -Name PSKubectlCompletion
    Register-KubectlCompletion
}

function Kubernetes-Install-PS-Kubectl-Completion () {
    Install-Module PSKubectlCompletion
}

function Kubernetes-Get-Terminated-Pod() {
    kubectl get pods -o custom-columns-file=D:\_code\blog\src\k8s\kubectl\terminated-pod.txt --sort-by='{status.containerStatuses[0].lastState.terminated.finishedAt}' $Args
}
function Link-Soft() {
    param (
        [string] $VirtualPath,
        [string] $RealPath
    )
    Console-Debug "New-Item -ItemType SymbolicLink -Path $VirtualPath -Target $RealPath"
    New-Item -ItemType SymbolicLink -Path $VirtualPath -Target $RealPath
}

function Link-Reset-Home {
    param (
        [string] $Path
    )
    Link-Soft -VirtualPath "${ENV:USERPROFILE}\${Path}" -RealPath "${ENV:HOME_D}\${Path}"
}

function Link-Reset-Home-All {
    Link-Reset-Home -Path '.android'
    Link-Reset-Home -Path '.claude'
    Link-Reset-Home -Path '.copilot'
    Link-Reset-Home -Path '.dotnet'
    Link-Reset-Home -Path '.m2'
    Link-Reset-Home -Path '.ssh'
    Link-Reset-Home -Path '.vscode'
    Link-Reset-Home -Path '.vscode-shared'
    Link-Reset-Home -Path '.nuget'
    Link-Reset-Home -Path '.bash_history'
    Link-Reset-Home -Path '.claude.json'
    Link-Reset-Home -Path '.gitconfig'
}
## 禁用内存压缩 Disable-MMAgent -mc
################################
# powershell profile functions
################################

function script:Profile-New(
    [string] $ProfilePath = $(throw "ProfilePath is null!")
) {
    if (Test-Path $ProfilePath) {
        Console-Info "# $ProfilePath already existed."
    }
    else {
        New-Item -Path $Profile -ItemType File -Force
        Console-Debug "# Create [$ProfilePath] succeed."
    }
}

function Profile-AddScriptExpression (
    [string] $ProfilePath = $(throw "ProfilePath is null!"),
    [string] $ScriptExpression = $(throw "ScriptExpression is null!")
) {
    Profile-New -ProfilePath $ProfilePath

    $ProfileContent = Get-Content -Path $ProfilePath
    if ($ProfileContent -contains $ScriptExpression) {
        Console-Info "# [$ScriptExpression] already existed in $ProfilePath."
    }
    else {
        Set-Content -Path $ProfilePath -Value "$ProfileContent`r`n$ScriptExpression"
        Console-Debug "# [$ScriptExpression] append to $ProfilePath."
    }
}

function Profile-AddScriptFile (
    [string] $ProfilePath = $(throw "ProfilePath is null!"),
    [string] $ScriptFilePath = $(throw "ScriptFilePath is null!")
) {
    if (!(Test-Path $ScriptFilePath)) {
        throw "$ScriptFilePath not found."
    }

    Profile-AddScriptExpression -ProfilePath $ProfilePath -ScriptExpression ". ""$ScriptFilePath"""
}
################################
# powershell prompt functions
################################

function prompt () {
    # hold last exit code
    $OLD_LASTEXITCODE = $LASTEXITCODE

    $Now = [System.DateTimeOffset]::Now
    $CurrentYearLastDay = New-Object -TypeName System.DateOnly -ArgumentList ($Now.Year, 12, 31)
    $DateTime = $Now.ToString('yy-MM-dd HH:mm:ss K')
    $DayOfWeek = [System.Int32]$Now.DayOfWeek
    $Week = $DayOfWeek.Equals(0)?7:$DayOfWeek
    $DayOfYear = $Now.DayOfYear
    $WeekOfYear = [System.Math]::Round(($DayOfYear + 7) / 7)
    $ResidueWeekOfYear = [System.Math]::Round(($CurrentYearLastDay.DayOfYear - $DayOfYear) / 7)
    $DayOfNewYear = $CurrentYearLastDay.DayOfYear - $DayOfYear
    $UnixTimeMilliseconds = $Now.ToUnixTimeMilliseconds()
    $UserPrompt = UI-GetUserPrompt
    $UserPromptPrefix = $UserPrompt.Prefix
    $UserPromptText = $UserPrompt.Text
    $UserPromptCurrentPath = $UserPrompt.CurrentPath

    Write-Host -NoNewline "`n$UserPromptPrefix $UserPromptCurrentPath $DateTime $UnixTimeMilliseconds w$Week-$WeekOfYear-$ResidueWeekOfYear d$DayOfYear-$DayOfNewYear" -ForegroundColor Gray
    if ($OLD_LASTEXITCODE -gt 0) {
        Write-Host -NoNewline " $OLD_LASTEXITCODE" -ForegroundColor Red
    }

    # if working directory is git repository
    if (Get-GitStatus) {

        # get git user.name and user.email
        $GitUser = Git-Get-Current-User

        # show git user.name and user.email
        Write-Host -NoNewline "`n$UserPromptPrefix $GitUser :" -ForegroundColor Gray

        # show git status
        Write-Host -NoNewline (Write-VcsStatus)
    }

    Write-Host

    # show current work directory in window title
    # $Host.UI.RawUI.WindowTitle = $UserPromptText

    # reset last exit code
    $LASTEXITCODE = $OLD_LASTEXITCODE

    return "$UserPromptPrefix "
}
########################################
# powershell open visual studio sln file
########################################

function script:Sln-GetFiles() {
    $currentPath = Get-Location
    Console-Debug 'current path : ' $currentPath

    $slnFiles = Get-ChildItem -Path $currentPath -File -Filter *.sln

    return $slnFiles
}

function script:Sln-SelectFile($slnFiles) {
    if ($slnFiles.Count -eq 0) {
        throw 'sln file not found.'
    }

    if ($slnFiles.Count -eq 1) {
        return $slnFiles[0]
    }

    [int]$i = 0
    $slnFiles | ForEach-Object {
        Write-Host $i ': ' $_.Name
        $i++
    }

    [int]$index = Read-Host 'find more sln file, please input index (default 0) :'
    return $slnFiles[$index]
}

function Sln() {
    $slnFiles = Sln-GetFiles
    $slnFile = Sln-SelectFile $slnFiles
    Console-Debug 'opening...   : ' $slnFile
    Invoke-Item $slnFile
}
################################
# powershell ui functions
################################

function Ui-Test-Administrator {
    $CurrentUser = [Security.Principal.WindowsIdentity]::GetCurrent();
    $CurrentPrincipal = New-Object Security.Principal.WindowsPrincipal $CurrentUser;
    return $CurrentPrincipal.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}

function script:UI-GetUserName() {
    $UserName = $ENV:USERNAME.ToLower();
    if ($UserName -eq 'administrator') {
        return 'admin';
    }
    return $UserName;
}

function script:UI-GetComputerName() {
    return $ENV:COMPUTERNAME.ToLower();
}

function UI-GetUserPrompt() {
    $Role = '$';
    $UserName = UI-GetUserName
    $ComputerName = UI-GetComputerName
    $CurrentPath = $(Get-Location).ToString().ToLower();
    if (Ui-Test-Administrator) {
        $Role = '#'
    }

    return @{
        Prefix       = $Role;
        UserName     = $UserName;
        ComputerName = $ComputerName;
        CurrentPath  = $CurrentPath;
        Text         = "$Role $UserName@$ComputerName $CurrentPath"
    }
}

function UI-SetDisplayOptions () {
    $Host.UI.RawUI.WindowPosition.X = 0;
    $Host.UI.RawUI.WindowPosition.Y = 0;

    $Host.UI.RawUI.BufferSize.Width = 80;
    $Host.UI.RawUI.BufferSize.Height = 2000;

    $Host.UI.RawUI.WindowSize.Width = 80;
    $Host.UI.RawUI.WindowSize.Height = 40;

    $Host.UI.RawUI.MaxWindowSize.Width = 80;
    $Host.UI.RawUI.MaxWindowSize.Height = 40;

    $Host.UI.RawUI.ForegroundColor = "White";
    $Host.UI.RawUI.BackgroundColor = "Black";
}
function V2Ray-Upload-Install-Script {
    param (
        [string] $ServerHost,
        [bool] $DryRun = $False
    )
    Log-DEBUG "scp `"d:\_code\blog\src\tool\v2ray\init.sh`" ${ServerHost}:~/v2ray-init.sh"
    if ($DryRun -eq $false) {
        scp "d:\_code\blog\src\tool\v2ray\init.sh" "${ServerHost}:~/v2ray-init.sh"
    }
}

function V2Ray-Download-Client-Config {
    param (
        [string] $ServerHost,
        [bool] $DryRun = $False
    )
    Log-DEBUG "scp ${ServerHost}:~/v2ray-client-config.json `"d:/_app/_v2ray/${ServerHost}-config.json`""
    if ($DryRun -eq $false) {
        scp "${ServerHost}:~/v2ray-client-config.json" "d:/_app/_v2ray/${ServerHost}-config.json"
    }
}

function V2Ray-Upload-Client-Config {
    param (
        [string] $ServerHost,
        [string] $ClientHost,
        [bool] $DryRun = $False
    )
    Log-DEBUG "scp `"d:/_app/_v2ray/${ServerHost}-config.json`" ${ClientHost}:/etc/config/v2ray.json"
    if ($DryRun -eq $false) {
        scp "d:/_app/_v2ray/${ServerHost}-config.json" "${ClientHost}:/etc/config/v2ray.json"
    }
}

function V2Ray-Init-Server-And-Client {
    param (
        [string] $ServerHost,
        [string] $ClientHost = "root@192.168.2.123",
        [bool] $DryRun = $False
    )
    $ServerIP = ($ServerHost -split '@')[-1]
    $ClientIP = ($ClientHost -split '@')[-1]
    V2Ray-Upload-Install-Script -ServerHost $ServerHost -DryRun $DryRun

    $InstallCommand = "chmod +x ./v2ray-init.sh;./v2ray-init.sh ${ServerIP} ${ClientIP};exit"
    Log-DEBUG "ssh ${ServerHost} `"${InstallCommand}`""
    if ($DryRun -eq $False) {
        ssh -t ${ServerHost} "${InstallCommand}"
    }

    V2Ray-Download-Client-Config -ServerHost $ServerHost -DryRun $DryRun

    V2Ray-Upload-Client-Config -ServerHost $ServerHost -ClientHost $ClientHost -DryRun $DryRun

    Log-DEBUG "ssh $ClientHost `"reboot`""
    if ($DryRun -eq $False) {
        ssh -t $ClientHost "reboot"
    }
}
################################
# powershell vm(hyper-v) functions
################################

function vm ([string] $name) {
    if ([String]::IsNullOrEmpty($name)) {
        Get-VM
    }
    else {
        Get-VM -Name $name
    }
}

# https://docs.microsoft.com/en-us/powershell/module/hyper-v/new-vhd?view=win10-ps
function vhd-create(
    [string] $Path,
    [uint64] $Size = 128GB
) {
    Console-Debug "New-VHD -Dynamic -Path $Path -SizeBytes $Size"
    New-VHD `
        -Dynamic `
        -Path $Path `
        -SizeBytes $Size
}

# https://www.altaro.com/hyper-v/customize-vm-powershell/
# https://docs.microsoft.com/en-us/powershell/module/hyper-v/new-vm?view=win10-ps
# https://docs.microsoft.com/en-us/powershell/module/hyper-v/set-vm?view=win10-ps
# https://docs.microsoft.com/en-us/powershell/module/hyper-v/set-vmdvddrive?view=win10-ps
# https://learn.microsoft.com/zh-cn/windows-server/virtualization/hyper-v/best-practices-for-running-linux-on-hyper-v
function Vm-From-Json(
    [string] $JsonFilePath
) {
    $NamePadding = 22
    if ((Test-Path -Path $JsonFilePath -PathType Leaf) -eq $False) {
        Console-Debug-Name-Value -Name 'not_found' -NamePadding $NamePadding -Value "$JsonFilePath"
        Console-Debug-Name-Value -Name 'help' -NamePadding $NamePadding -Value 'https://linianhui.github.io/powershell/hyper-v/#config'
        return
    }

    if ((Ui-Test-Administrator) -eq $False) {
        Console-Debug-Name-Value -Name 'no_permission' -NamePadding $NamePadding -Value "need use administrator"
        return
    }

    $Json = Get-Content -Path $JsonFilePath | ConvertFrom-Json

    $VhdPath = ($Json.vhd.path + "\" + $Json.name + ".vhdx")
    if ((Test-Path -Path $VhdPath -PathType Leaf) -eq $False) {
        New-VHD `
            -Dynamic `
            -Path $VhdPath `
            -BlockSizeBytes $Json.vhd.blockSize `
            -SizeBytes $Json.vhd.size | Out-Null
    }

    $VM = Get-VM -Name $Json.name -ErrorAction Ignore
    if ($VM -eq $NULL) {
        New-VM `
            -Name $Json.name `
            -Generation $Json.generation `
            -Path $Json.path `
            -SwitchName $Json.net.switch `
            -VHDPath $VhdPath | Out-Null
    }

    if ($VM.Generation -eq 2) {
        # https://learn.microsoft.com/en-us/powershell/module/hyper-v/set-vmfirmware?view=windowsserver2019-ps
        Set-VMFirmware `
            -VMName $Json.name `
            -EnableSecureBoot $Json.boot.secure
    }

    # https://learn.microsoft.com/en-us/powershell/module/hyper-v/set-vm?view=windowsserver2019-ps
    Set-VM `
        -Name $Json.name `
        -AutomaticStartAction $Json.automatic.start `
        -AutomaticStopAction $Json.automatic.stop `
        -AutomaticCheckpointsEnabled $Json.automatic.checkpoint `
        -CheckpointType $Json.checkpoint.type

    Get-VMIntegrationService -VMName $Json.name | ForEach-Object {
        Enable-VMIntegrationService -VMName $Json.name -Name $_.Name
    }

    # print vm
    $VM = Get-VM -Name $Json.name
    Console-Debug-Name-Value -Name 'name' -NamePadding $NamePadding -Value $VM.Name
    Console-Debug-Name-Value -Name 'generation' -NamePadding $NamePadding -Value $VM.Generation
    Console-Debug-Name-Value -Name 'path' -NamePadding $NamePadding -Value $VM.Path
    Console-Debug-Name-Value -Name 'state' -NamePadding $NamePadding -Value $VM.State
    if ($VM.Generation -eq 2) {
        $VMFirmware = Get-VMFirmware -VMName $Json.name
        Console-Debug-Name-Value -Name 'boot.secure' -NamePadding $NamePadding -Value $VMFirmware.SecureBoot.ToString()
    }
    else {
        Console-Debug-Name-Value -Name 'boot.secure' -NamePadding $NamePadding -Value 'Off'
    }
    Console-Debug-Name-Value -Name 'automatic.start' -NamePadding $NamePadding -Value $VM.AutomaticStartAction
    Console-Debug-Name-Value -Name 'automatic.stop' -NamePadding $NamePadding -Value $VM.AutomaticStopAction
    Console-Debug-Name-Value -Name 'automatic.checkpoint' -NamePadding $NamePadding -Value $VM.AutomaticCheckpointsEnabled
    Console-Debug-Name-Value -Name 'checkpoint.type' -NamePadding $NamePadding -Value $VM.CheckpointType

    # https://learn.microsoft.com/en-us/powershell/module/hyper-v/set-vmprocessor?view=windowsserver2019-ps
    Set-VMProcessor `
        -VMName $Json.name `
        -Count $Json.cpu.count
    $CPU = Get-VMProcessor -VMName $Json.name
    # print cpu
    Console-Debug-Name-Value -Name 'cpu.count' -NamePadding $NamePadding -Value $CPU.Count


    # https://learn.microsoft.com/en-us/powershell/module/hyper-v/set-vmmemory?view=windowsserver2019-ps
    Set-VMMemory `
        -VMName $Json.name `
        -DynamicMemoryEnabled $True `
        -StartupBytes $Json.mem.min `
        -MinimumBytes $Json.mem.min `
        -MaximumBytes $Json.mem.max
    $MEM = Get-VMMemory -VMName $Json.name
    # print mem
    Console-Debug-Name-Value -Name 'mem.dynamic' -NamePadding $NamePadding -Value $MEM.DynamicMemoryEnabled
    Console-Debug-Name-Value -Name 'mem.startup' -NamePadding $NamePadding -Value ($MEM.Startup | Format-Byte)
    Console-Debug-Name-Value -Name 'mem.min' -NamePadding $NamePadding -Value ($MEM.Minimum | Format-Byte)
    Console-Debug-Name-Value -Name 'mem.max' -NamePadding $NamePadding -Value ($MEM.Maximum | Format-Byte)


    if ($Json.net.mac) {
        Set-VMNetworkAdapter `
            -VMName $Json.name `
            -StaticMacAddress $Json.net.mac
    }
    $VM = Get-VM -Name $Json.name
    # print net
    Console-Debug-Name-Value -Name 'net.switch' -NamePadding $NamePadding -Value $VM.NetworkAdapters[0].SwitchName
    Console-Debug-Name-Value -Name 'net.connected' -NamePadding $NamePadding -Value $VM.NetworkAdapters[0].Connected
    Console-Debug-Name-Value -Name 'net.mac' -NamePadding $NamePadding -Value ($VM.NetworkAdapters[0].MacAddress | Format-Mac)


    $VHD = Get-VHD -Path $VhdPath
    $HDD = Get-VMHardDiskDrive -VMName $Json.name
    # print hdd
    Console-Debug-Name-Value -Name 'vhd.type' -NamePadding $NamePadding -Value $VHD.VhdType
    Console-Debug-Name-Value -Name 'vhd.path' -NamePadding $NamePadding -Value $VHD.Path
    Console-Debug-Name-Value -Name 'vhd.format' -NamePadding $NamePadding -Value $VHD.VhdFormat
    Console-Debug-Name-Value -Name 'vhd.size' -NamePadding $NamePadding -Value ($VHD.Size | Format-Byte)
    Console-Debug-Name-Value -Name 'vhd.blocksize' -NamePadding $NamePadding -Value ($VHD.BlockSize | Format-Byte)
    Console-Debug-Name-Value -Name 'vhd.fileSize' -NamePadding $NamePadding -Value ($VHD.FileSize | Format-Byte)
    Console-Debug-Name-Value -Name 'vhd.controllerType' -NamePadding $NamePadding -Value $HDD.ControllerType
    Console-Debug-Name-Value -Name 'vhd.controllerNumber' -NamePadding $NamePadding -Value $HDD.ControllerNumber
    Console-Debug-Name-Value -Name 'vhd.controllerLocation' -NamePadding $NamePadding -Value $HDD.ControllerLocation


    if ($Json.dvd.iso) {
        if (Test-Path -Path $Json.dvd.iso -PathType Leaf) {
            if ((Get-VMDvdDrive -VMName $Json.name) -eq $Null) {
                Add-VMDvdDrive `
                    -VMName $Json.name `
                    -Path $Json.dvd.iso`
                    -ErrorAction Ignore
            }
        }
        $DVD = Get-VMDvdDrive -VMName $Json.name
        if ($DVD.Path) {
            # print dvd
            Console-Debug-Name-Value -Name 'dvd.type' -NamePadding $NamePadding -Value $DVD.DvdMediaType
            Console-Debug-Name-Value -Name 'dvd.path' -NamePadding $NamePadding -Value $DVD.Path
            Console-Debug-Name-Value -Name 'dvd.fileSize' -NamePadding $NamePadding -Value ((Get-Item $DVD.Path).Length | Format-Byte)
            Console-Debug-Name-Value -Name 'dvd.controllerType' -NamePadding $NamePadding -Value $DVD.ControllerType
            Console-Debug-Name-Value -Name 'dvd.controllerNumber' -NamePadding $NamePadding -Value $DVD.ControllerNumber
            Console-Debug-Name-Value -Name 'dvd.controllerLocation' -NamePadding $NamePadding -Value $DVD.ControllerLocation
        }
    }
}


function Vm-To-Json() {
    param (
        [string] $VMName = $(throw "VMName is null!")
    )

    $NamePadding = 22

    if ((Ui-Test-Administrator) -eq $False) {
        Console-Debug-Name-Value -Name 'no_permission' -NamePadding $NamePadding -Value 'need use administrator'
        return
    }

    $VM = Get-VM -Name $VMName -ErrorAction Ignore
    if ($VM -eq $NULL) {
        Console-Debug-Name-Value -Name 'not_found' -NamePadding $NamePadding -Value $VMName
        return
    }

    $AutomaticJson = [ordered]@{
        'start'      = $VM.AutomaticStartAction.ToString()
        'stop'       = $VM.AutomaticStopAction.ToString()
        'checkpoint' = $VM.AutomaticCheckpointsEnabled
    }

    $CheckpointJson = [ordered]@{
        'type' = $VM.CheckpointType.ToString()
    }

    $BootJson = [ordered]@{
        'secure' = 'Off'
    }
    if ($VM.Generation -eq 2) {
        $Boot = Get-VMFirmware -VMName $VM.Name
        $BootJson.secure = $Boot.SecureBoot.ToString()
    }

    $Cpu = Get-VMProcessor -VMName $VM.Name
    $CpuJson = [ordered]@{
        'count' = $Cpu.Count
    }

    $Mem = Get-VMMemory -VMName $VM.Name
    $MemJson = [ordered]@{
        'min' = ($Mem.Minimum | Format-Byte)
        'max' = ($Mem.Maximum | Format-Byte)
    }

    $NetJson = [ordered]@{
        'switch' = $VM.NetworkAdapters[0].SwitchName
        'mac'    = ($VM.NetworkAdapters[0].MacAddress | Format-Mac)
    }

    $VhdPath = (Get-VMHardDiskDrive -VMName $VM.Name)[0].Path
    $Vhd = Get-VHD -Path $VhdPath
    $VhdJson = [ordered]@{
        'path'      = (Get-ChildItem -Path $Vhd.Path).DirectoryName.ToLower()
        'size'      = ($Vhd.Size | Format-Byte)
        'blockSize' = ($Vhd.BlockSize | Format-Byte)
    }

    $Dvd = Get-VMDvdDrive -VMName $VM.Name
    $DvdJson = [ordered]@{
        "iso" = $Dvd.Path?.ToLower()
    }

    $Json = [ordered]@{
        'name'       = $VM.Name
        'generation' = $VM.Generation
        'path'       = $VM.Path.ToLower()
        'automatic'  = $AutomaticJson
        'boot'       = $BootJson
        'checkpoint' = $CheckpointJson
        'cpu'        = $CpuJson
        'mem'        = $MemJson
        'net'        = $NetJson
        'vhd'        = $VhdJson
        'dvd'        = $DvdJson
    }

    $Json | ConvertTo-Json
}

function vm-run ([string] $name) {
    if ((Ui-Test-Administrator) -eq $False) {
        Console-Debug-Name-Value -Name 'no_permission' -NamePadding 20 -Value 'use administrator run vm'
        return
    }
    Get-VM -Name $name | Start-VM
}

function vm-stop ([string] $name) {
    if ((Ui-Test-Administrator) -eq $False) {
        Console-Debug-Name-Value -Name 'no_permission' -NamePadding 10 -Value 'use administrator stop vm'
        return
    }
    Get-VM -Name $name | Stop-VM
}

function vm-ssh (
    [string]$username,
    [string]$hostname,
    [string]$port = 22) {

    Console-Debug "run [$hostname] hyper-v vm"
    vm-run -name $hostname

    Console-Debug "ssh $username@$hostname -p $port"
    ssh "$username@$hostname" -p $port
}

function ubt1 () {
    vm-ssh -username root -hostname ubt1
}

function ubt2 () {
    vm-ssh -username root -hostname ubt2
}

function ubt3 () {
    vm-ssh -username root -hostname ubt3
}

function ceos () {
    vm-ssh -username root -hostname ceos
}

function deb1 () {
    vm-ssh -username root -hostname deb1
}

function deb2 () {
    vm-ssh -username root -hostname deb2
}

function deb3 () {
    vm-ssh -username root -hostname deb3
}
function VsCode-Open {
    param (
        [Parameter(Mandatory = $TRUE)]
        [string] $Path = $(throw "Path param is null!")
    )
    if (Directory-Exists-And-Is-Directory -Path $Path) {
        Console-Debug "code $Path".ToLower()
        code $Path
    }
}
function WLAN-Export {
    Console-Debug "netsh wlan export profile key=clear"
    netsh wlan export profile key=clear
}
# https://github.com/jeremyfa/yaml.js
# cnpm install -yamljs -g

function Yaml-ToJson() {
    Console-Debug "yaml2json --pretty --indentation 2" $Args

    yaml2json --pretty --indentation 2 $Args
}

function Yaml-FromJson() {
    Console-Debug "json2yaml --depth 64 --indentation 2" $Args

    json2yaml --depth 64 --indentation 2 $Args
}
上一篇 : [PowerShell] Help
下一篇 : [PowerShell] Hyper-V