PowerShell-自定义的配置文件

发布时间 2023-05-03 12:14:48作者: 狂自私

PowerShell 5.1

一般Windows 10自带的是这个版本的PowerShell,这个版本的自定义配置文件的文件编码要保存为ANSI才行。

PowerShell 7

这个是通过github另外下载的,这个版本的自定义配置文件的文件编码要保存为utf-8才行。

 

配置文件代码

其实也没啥,主要加了一个时间显示和我可能用到的命令

#--------------------------------定义的别名------------------------------------------------
#Set-Alias -Name wget -Value Invoke-WebRequest

#↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑定义的别名↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
#↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓定义的变量↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
#系统启动时间(日期)
$script:sysstartTime_date = 0
#系统启动时间(时间)
$script:sysstartTime_time = 0
#↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑定义的变量↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

#**************************************定义的函数*******************************************
#定义命令提示符提示的内容
Function Prompt()
{
    switch ($PSPromptMode)
    {
        'Cmd'
        {
            "$($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) "
        }
        'Arrow'
        {
            '> '
        }
        'None'
        {
            "PS $((Get-Date).DateTime) $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) "
        }
        'Simple'
        {
            'PS> '
        }
        Default
        {
            "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) "
        }
    }
}

<#
.Synopsis
    设置控制台提示风格
.DESCRIPTION
    设置控制台提示风格,支持五种风格:Normal,Cmd,Arrow,Simple,None
#>
Function Set-Prompt
{
    param(
        [Parameter(Mandatory=$true)]
        [ValidateSet('Normal','Cmd','Arrow','Simple', 'None',IgnoreCase = $true)]
        $Mode
    )
    $varPSPromptMode = (Get-Variable 'PSPromptMode' -ea SilentlyContinue)
    #配置变量不存在则新建
    if ( $varPSPromptMode -eq $null)
    {
        New-Variable -Name 'PSPromptMode' -Value $Mode -Scope 'Global'
        $varPSPromptMode = Get-Variable -Name 'PSPromptMode'
        $varPSPromptMode.Description = '提示函数配置变量'

        #限制配置变量的取值集合
        $varPSPromptModeAtt = New-Object System.Management.Automation.ValidateSetAttribute('Normal','Cmd','Arrow','Simple','None')
        $varPSPromptMode.Attributes.Add($varPSPromptModeAtt)

        #限制配置变量为只读并且可以贯穿所有作用域ls
        $varPSPromptMode.Options = 'ReadOnly, AllScope'
    }
    #更新配置
    #只读变量可以通过-force选项更新值
    Set-Variable -Name PSPromptMode -Value $Mode -Force
}

#UpTime:系统启动时间,截止当前的运行时间
# Function get_sysstartTime(){
    # $sysinfo  = systeminfo.exe
    # $regex = [regex]"(?<=系统启动时间:).+"
    # $sysstartTime = $regex.Match($sysinfo)

    # $null  = $sysstartTime -match "\d{4}-\d{2}-\d{2}"
    # $script:sysstartTime_date = $Matches[0]
    # $null = $sysstartTime -match "\d{2}:\d{2}:\d{2}"
    # $script:sysstartTime_time = $Matches[0]
# }
# Function uptime(){
    # $systime = $script:sysstartTime_date + " " + $script:sysstartTime_time
    # (New-TimeSpan -end (Get-Date -Format "yyyy-MM-dd HH:mm:ss") -Start $systime).ToString()
# }

Function get-SystemStartTime(){
<#
.SYNOPSIS
    显示Windows系统启动的时间以及自上次启动以来,运行了多长时间
.DESCRIPTION
    本函数无参数,直接运行即可
.example
    get-SystemStartTime()

#>
    Set-Variable -Description "记录系统启动时间" -Name "system_start_time" -Scope "private" -Value ((Get-CimInstance Win32_OperatingSystem).LastBootUpTime) 
    $时间段 = New-TimeSpan -Start (Get-Variable -Name "system_start_time").Value -End (Get-Date)
    $运行时间 = ''
    if($时间段.Days -ge 365){
        #计算年,大于等于365
        $运行时间 += ([int][Math]::Floor($时间段.Days / 365)).ToString()+""
        $时间段.Days = $时间段.Days%365
    }
    if($时间段.Days -lt 365 -and $时间段.Days -gt 0){
        #计算天,0-365天
        $运行时间 += $时间段.Days.ToString() + ""
    }
    $运行时间 += $时间段.Hours.ToString() + "" + $时间段.Minutes.ToString() + "" + $时间段.Seconds.ToString() + ""
    Write-Host -Object $运行时间
}
Add-Type -MemberDefinition '[DllImport("Shlwapi.dll", CharSet=CharSet.Auto)]public static extern int StrFormatByteSize(long fileSize, System.Text.StringBuilder pwszBuff, int cchBuff);' -Name "ShlwapiFunctions" -namespace ShlwapiFunctions
Function Format-ByteSize([Long]$Size) {
<#
.SYNOPSIS
    将数值转换为表示数字的字符串,该数字表示为以字节、千字节、兆字节或千兆字节为单位的大小值,具体取决于大小。
    输入值:以字节大小表示的值
    返回值:结果的字符串形式;若是转换失败,则原样返回$Size参数值
.example
    将1234友好显示
    > Format-ByteSize -Size 1234
    1.20 KB

.example
    使得输出结果单行显示
    Format-ByteSize -Size 1234 | Write-Host -NoNewline
    1.20 KB
#>
    <#
        String 对象不可变。
        若要修改字符串(而不新建对象),可以使用 System.Text.StringBuilder 类。
        https://learn.microsoft.com/zh-cn/dotnet/api/system.text.stringbuilder.-ctor?view=net-7.0#system-text-stringbuilder-ctor(system-int32)
        新建一个System.Text.StringBuilder对象,并为其构造函数传入参数20,即表示创建一个长度为20的System.Text.StringBuilder对象
    #>
    $Bytes = New-Object -TypeName "System.Text.StringBuilder" -ArgumentList 20
    <#
        函数说明参考:https://learn.microsoft.com/zh-cn/windows/win32/api/shlwapi/nf-shlwapi-strformatbytesizew
    #>
    $Return = [ShlwapiFunctions.ShlwapiFunctions]::StrFormatByteSize($Size, $Bytes, $Bytes.Capacity)
    If ($Return) {
        return $Bytes.ToString()
    }
    else{
        return $Size
    }
}

Function du{
<#
.SYNOPSIS
    类似于Linux的du命令;
.description
    直接运行该命令将获取当前路径下的所有文件大小和该目录的大小
.example
    获取当前所在路径的大小
    du 
.example
    获取指定文件夹的大小
    du 
#>

    param
    (
    [Parameter(Position=0,
    HelpMessage="要检查的路径,若是文件,将只输出该文件的大小;若是目录,则 输出该目录以及该目录下的一级文件大小(一级目录则只输出目录本身的大小)",ValueFromPipeline)]
    [System.String]$LiteralPath = '.'
    )
    if(Test-Path -LiteralPath $LiteralPath){
        $LiteralPath = (Get-Item -LiteralPath $LiteralPath).FullName
        #目录存在
        Write-Verbose "目录存在。"
        $file_type = (Get-Item -LiteralPath $LiteralPath).GetType()
        if("DirectoryInfo" -eq $file_type.Name){
            #目录
            Write-Verbose "统计计算目录占用空间大小。"
            "$LiteralPath 占用空间为:" + (Format-ByteSize((Get-ChildItem -LiteralPath $LiteralPath -Force -Recurse 2>$null |Measure-Object -Property Length -Sum).Sum).ToString())
            Write-Verbose "输出$LiteralPath 目录下的子文件(目录)大小"
            Get-ChildItem -LiteralPath $LiteralPath -Force | Format-Table -Property Name,@{Name="大小";Expression={Format-ByteSize($_.Length)};Alignment="Right"}
        }
        elseif("FileInfo" -eq $file_type.Name){
            #文件
            Write-Verbose "输出$LiteralPath 目录下的子文件(目录)大小"
            Get-ChildItem -LiteralPath $LiteralPath -Force | Format-Table -Property Name,@{Name="大小";Expression={Format-ByteSize($_.Length)};Alignment="Right"}
        }
        else{
            #其他,这里做冗余处理,本质上跟文件的处理方式一样
            Write-Verbose "输出$LiteralPath 目录下的子文件(目录)大小"
            Get-ChildItem -LiteralPath $LiteralPath -Force | Format-Table -Property Name,@{Name="大小";Expression={Format-ByteSize($_.Length)};Alignment="Right"}
        }
    }
    else{
        Write-Host -Object "$LiteralPath 不存在!" -ForegroundColor Red -BackgroundColor Black
    }
}


#*******************************************执行函数************************
Set-Prompt -Mode None
#*******************************************执行命令************************
cd $home