我的ps配置
2022年3月21日小于 1 分钟
我的ps配置
提示
查询 profile位置: $PROFILE
配置文件
function fluship {
    ipconfig /flushdns
}
function yarnDev {
    yarn --registry=https://registry.npmmirror.com && yarn dev
}
function yarnInstall {
    yarn install --registry=https://registry.npmmirror.com
}
function removeItem {
    Remove-Item -Recurse -Force
}
function getCmdPath() {
    start (Get-ChildItem (Get-Command -Name $args[0]).Source).Directory
}
function deletePnpm {
    Copy-Item .\package.json -Destination .\package.jsonbak;
    Remove-Item .\package.json;
    if (Test-Path "pnpm-lock.yml") {
        Remove-Item  "pnpm-lock.yml";
    }
    Write-Output '删除node_modules中'
    pnpm init && pnpm add axios
    Remove-Item -Force -Recurse .\node_modules;
    Remove-Item .\package.json;
    Copy-Item .\package.jsonbak -Destination .\package.json;
    Remove-Item .\package.jsonbak
    # 删除文件名中包含lock字符的文件
    Remove-Item   '*lock*'
    Write-Output '已完成'
}
function deleteNodemodules {
    Copy-Item .\package.json -Destination .\package.jsonbak;
    Remove-Item .\package.json;
    Write-Output '删除node_modules中'
    yarn init -y && yarn add axios;
    Remove-Item -Force -Recurse .\node_modules;
    Remove-Item .\package.json;
    Copy-Item .\package.jsonbak -Destination .\package.json;
    Remove-Item .\package.jsonbak
    # 删除文件名中包含lock字符的文件
    Remove-Item   '*lock*'
    Write-Output '已完成'
}
function gbFun {
    git pull --rebase
}
function glogFun {
    git log --graph --pretty='%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%ar) %C(bold blue)<%an>%Creset'
}
function gpFunc {
    git add -A && git commit -m $args[0] && git push origin main
}
function gcacheFun {
    git checkout --orphan dev ;
    git add -A ;
    git branch -D main ;
    git branch -m main ;
    git commit -m 'Initial commit' ;
    git push origin main -f ;
    git gc --aggressive --prune=all
}
function Format-FileSize() {
    Param ([int]$size)
    If ($size -gt 1TB) { [string]::Format("{0:0.00} TB", $size / 1TB) }
    ElseIf ($size -gt 1GB) { [string]::Format("{0:0.00} GB", $size / 1GB) }
    ElseIf ($size -gt 1MB) { [string]::Format("{0:0.00} MB", $size / 1MB) }
    ElseIf ($size -gt 1KB) { [string]::Format("{0:0.00} kB", $size / 1KB) }
    ElseIf ($size -gt 0) { [string]::Format("{0:0.00} B", $size) }
    Else { "" }
}
function lsmFunc() {
    Get-ChildItem | Select-Object Name, LastWriteTime, @{Name = "Size"; Expression = { Format-FileSize($_.Length) } }
}
# # PowerShell parameter completion shim for the dotnet CLI
Register-ArgumentCompleter -Native -CommandName dotnet -ScriptBlock {
    param($commandName, $wordToComplete, $cursorPosition)
    dotnet complete --position $cursorPosition "$wordToComplete" | ForEach-Object {
        [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
    }
}
Remove-Alias -Name ni -Force
Set-Alias yr deleteNodemodules
Set-Alias pr deletePnpm
Set-Alias ip fluship
Set-Alias yd yarnDev
Set-Alias y yarnInstall
Set-Alias gitp gpFunc
Set-Alias gitc gcacheFunq
Set-Alias gcp getCmdPath
Set-Alias gb gbFun
Set-Alias glog glogFun
Set-Alias kate "C:\Program Files\Kate\bin\kate.exe"
Set-Alias lsm lsmFunc
# #chcp 65001
# #chcp 936
if ($env:TERM_PROGRAM -eq "vscode") {
    . "$env:USERPROFILE\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\contrib\terminal\browser\media\shellIntegration.ps1"
}
# if ($env:TERM_PROGRAM -eq "vscode") { . "$(code --locate-shell-integration-path pwsh)" }
# # PSReadLine
Import-Module PSReadLine
Import-Module -Name Terminal-Icons
# # Enable Prediction History
Set-PSReadLineOption -PredictionSource History
# # Advanced Autocompletion for arrow keys
Set-PSReadlineKeyHandler -Key UpArrow -Function HistorySearchBackward
Set-PSReadlineKeyHandler -Key DownArrow -Function HistorySearchForward
Import-Module posh-git
oh-my-posh init pwsh --config "$env:POSH_THEMES_PATH\negligible.omp.json" | Invoke-Expression
#
# #conda activate condapkg
克隆王道的文档
$prefix = 'https://github.com/wangdoc/'
$suffix = '.git'
$cur = $PWD
$gitRepos = 'bash-tutorial', 'git-tutorial', 'node-tutorial', 'javascript-tutorial', 'clang-tutorial', 'css-tutorial', 'es6-tutorial', 'ssh-tutorial', 'html-tutorial', 'webapi-tutorial'
# 这里填你的docs文件夹
 
$dest = 'E:\myblogs\wangdoc\docs\'
# 系统临时文件路径
$tmpPath = $env:tmp + '\wang\'
Write-Host  '设置临时文件路径'$tmpPath -ForegroundColor Cyan
if (-not (Test-Path $tmpPath)) {
    mkdir $tmpPath
}
Set-Location $tmpPath
# 克隆所有文件
function cloneAll {
    foreach ($item in $gitRepos) {
        git clone $prefix$item$suffix
        Set-Location $item
        Copy-Item -Recurse -Force docs $dest$item
    } 
    Set-Location $cur
    delTmpPath
    
    
}
function cloneOnlyDocs {
    foreach ($item in $gitRepos) {
        if (-not (Test-Path  $item)) {
            mkdir $item 
        }
        
         
        Set-Location $item
    
        Write-Host '当前路径'$PWD -ForegroundColor Cyan
        if (Test-Path ".git" ) {
            Write-Host  '已有git文件夹' -ForegroundColor Cyan
            switch ($item) {
                'ssh-tutorial' {  
                    git pull origin main
                } 
                'clang-tutorial' {  
                    git pull origin main
                }
                Default {
                    git pull origin master
                }
            }
            Write-Host '从docs复制到'$dest$item -ForegroundColor Cyan
            # 注意下面的\文件夹分割
            Copy-Item  -Path 'docs'-Destination  $dest$item -Recurse -Force
            Set-Location ../
        }
        else {
            git init
            git remote add origin $prefix$item$suffix
            # 设置允许克隆子目录
            git config core.sparsecheckout true 
            Write-Host  '没有git文件夹,正在克隆' -ForegroundColor Cyan
            Write-Host '当前路径'$PWD -ForegroundColor Cyan
            Write-Output 'docs' >> '.git/info/sparse-checkout'  
            switch ($item) {
                'ssh-tutorial' {  
                    git pull origin main
                } 
                'clang-tutorial' {  
                    git pull origin main
                }
                Default {
                    git pull origin master
                }
            }
            # 注意下面的\文件夹分割 -Force 覆盖文件
            Copy-Item  -Path 'docs'  -Destination  $dest$item -Recurse -Force
            Set-Location ../
        }
    } 
     
}
function delTmpPath {
    Remove-Item -Recurse -Force $tmpPath
    
}
cloneOnlyDocs
Set-Location $cur
小爬虫
#This is a crawler for baidu images
<#
All these funuctions would be used to implementation crawler's target
#>
function Get-Random-String {
    $fileName = -join ([char[]](65..90 + 97..122) | Get-Random -Count 6)
    $fileName
}
function Resolve-Directory {
    param (
        [Parameter(Mandatory)]
        [string]
        $Path
    )
    if (-not (Test-Path -LiteralPath $Path)) {
        New-Item -Path $Path -ItemType Directory -ErrorAction SilentlyContinue
    }
}
function Invoke-MD5 {
    param (
        # Parameter Path
        [Parameter(Mandatory)]
        [string]
        $Path
    )
    begin {
        $global:hashTable = @{ }
    }
    process {
        Get-ChildItem -Path $Path | Where-Object {
            $hash = Get-FileHash -Path $_.FullName -Algorithm MD5
            $hashTable[$hash.Hash] = $hash.Path
        }
    }
    end { }
}
function Get-Images {
    param (
        [Parameter(ValueFromPipeline)]
        [int]
        $page = 1,
        [Parameter(Mandatory)]
        [string]
        $Path,
        [Parameter(Mandatory)]
        [string]
        $keyword
    )
    begin {
        Resolve-Directory -Path $Path
        Invoke-MD5 -Path $Path
        $headers = @{
            'Accept'                    = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3'
            'Accept-Encoding'           = 'gzip, deflate, br'
            'Accept-Language'           = 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7'
            'Host'                      = 'image.baidu.com'
            'Upgrade-Insecure-Requests' = '1'
            'User-Agent'                = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'
        }
    }
    process {
        $n = ($page * 20)
        $word = [uri]::EscapeDataString($keyword)
        $url = "https://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=${word}&pn=$n"
        Write-Host "Handling $url`n"
        $web = (Invoke-WebRequest -Uri $url -Method GET -Headers $headers)
        $web | Select-String '"objURL":"https?://+[^\s]+[\w]' -AllMatches | ForEach-Object { $_.Matches } | Foreach-Object {
            $_ -match 'https?://.+.'
            $Matches.Values | ForEach-Object {
                Write-Host "Fetching from $_" -ForegroundColor 3
                $ext = ([regex]'\.(jpe?g|png|gif|tif|bmp)').Match($_).Value
                if ([String]::IsNullOrEmpty($ext)) {
                    $ext = ".jpg"
                }
                $fileFullName = (Get-Random-String) + $ext
                $TargetPath = Join-Path -Path $Path -ChildPath $fileFullName
                Invoke-WebRequest -Uri $_ -PassThru -TimeoutSec 20000 -OutFile $TargetPath -ErrorAction SilentlyContinue
                # calculate the md5 value
                if ((Test-Path $TargetPath)) {
                    $hashValue = (Get-FileHash -Path $TargetPath -Algorithm MD5).Hash
                    if ($hashValue -and $hashTable.ContainsKey($hashValue)) {
                        Remove-Item -Path $TargetPath -Force -ErrorAction SilentlyContinue
                    }
                }
                Start-Sleep -Milliseconds 1000
            }
        }
        #ii $Path
    }
}
0..10 | Get-Images -Path "d:\temp\baiduimages" -keyword "soft cat"
获取安装的软件
<#
.Synopsis
   Get installed software list by retrieving registry.
.DESCRIPTION
   The function return a installed software list by retrieving registry from below path;
   1.'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'
   2.'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall'
   3.'HKLM:SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
   Author: Mosser Lee (http://www.pstips.net/author/mosser/)
.EXAMPLE
   Get-InstalledSoftwares
.EXAMPLE
   Get-InstalledSoftwares  | Group-Object Publisher
#>
function Get-InstalledSoftwares {
    #
    # Read registry key as product entity.
    #
    function ConvertTo-ProductEntity {
        param([Microsoft.Win32.RegistryKey]$RegKey)
        $product = '' | select Name, Publisher, Version
        $product.Name = $_.GetValue("DisplayName")
        $product.Publisher = $_.GetValue("Publisher")
        $product.Version = $_.GetValue("DisplayVersion")
        if ( -not [string]::IsNullOrEmpty($product.Name)) {
            $product
        }
    }
    $UninstallPaths = @(,
        # For local machine.
        'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall',
        # For current user.
        'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall')
    # For 32bit softwares that were installed on 64bit operating system.
    if ([Environment]::Is64BitOperatingSystem) {
        $UninstallPaths += 'HKLM:SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
    }
    $UninstallPaths | foreach {
        Get-ChildItem $_ | foreach {
            ConvertTo-ProductEntity -RegKey $_
        }
    }
}
获取文件夹大小
$startFolder = "D:\flutter"
$colItems = (Get-ChildItem $startFolder  | Where-Object {$_.PSIsContainer -eq $True} | Sort-Object)
foreach ($i in $colItems)
{
    $subFolderItems = (Get-ChildItem $i.FullName -recurse | Measure-Object -property length -sum)
    $FileSize="{0:N2}" -f ($subFolderItems.sum / 1GB)
    $Unit='GB'
    if($FileSize -lt 1)
    {
        $FileSize="{0:N2}" -f ($subFolderItems.sum / 1MB)
        $Unit='MB'
    }
    write-host $i.FullName  ' -- '  $FileSize  $Unit -fore green
}
获取文件夹内的文件数量
[System.IO.Directory]::GetFiles("d:\flutter", '*', 'AllDirectories').Count
或者
Get-ChildItem -Path "d:\flutter" -Force -Recurse -ErrorAction SilentlyContinue |
 Where-Object { $_.PSIsContainer -eq $false } |
 Measure-Object | 
 Select-Object -ExpandProperty Count
