PowerShell片段

玖亖伍
2023-01-18 / 0 评论 / 245 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2023年01月18日,已超过555天没有更新,若内容或图片失效,请留言反馈。

简单片段

  1. 查找命令(示例: 包含Module的命令)

    Get-Command | Out-String -Stream | Select-String -Pattern "Module" -SimpleMatch -CaseSensitive
  2. 查看帮助(示例: 查看命令Get-InstalledModule的帮助)

    Get-Help -Name Get-InstalledModule
  3. 在线查找模块(示例: 搜索模块Pode)

    Find-Module -Filter Pode
  4. 信任仓库PSGallery

    # 查看仓库
    Get-PSRepository
    # 信任仓库
    Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted
  5. 安装包(示例: 安装模块Pode)

    Install-Module -Name Pode -AllowClobber -Force
  6. 自定义对象(类似于 C# 的 匿名类型)

    [PSCustomObject]@{
        'Command' = [string]'git'
    }
  7. 查看对象成员

    # 实例化对象
    $obj = [PSCustomObject]@{
        'Command' = [string]'git'
    }
    # 查看全部对象
    $obj | Get-Member
    # 仅查看属性
    $obj | Get-Member -MemberType NoteProperty
  8. 定义类并使用

    # 定义类 ClassDemo
    class ClassDemo
    {
        [int]$One
        [string]$Two
    
        ClassDemo() {}
    
        ClassDemo([int]$one, [string]$two) {
            $this.One = $one
            $this.Two = $two
        }
     
        [string]ToString(){
            return ("ClassDemo(One={0},Two={1})" -f $this.One, $this.Two)
        }
    }
    # 3种方式实例化 ClassDemo
    # 1. 使用 ::new()
    $object1 = [ClassDemo]::new(1,"2")
    # 2. 使用 New-Object
    $object2 = New-Object ClassDemo -Property @{ One = 1; Two = "2" }
    # 3. 使用类型转换
    $object3 = [ClassDemo]@{ One = 1; Two = "2" }

功能封装

  1. 判断命令行命令是否存在

    function IsCommandExists {
        <#
            .SYNOPSIS
            判断命令行命令是否存在
            
            .DESCRIPTION
            判断命令行命令是否存在
    
            .PARAMETER Command
            命令
    
            .EXAMPLE
            PS> IsCommandExists -Command git
    
            .EXAMPLE
            PS> 'git' | IsCommandExists
    
            .EXAMPLE
            PS> [PSCustomObject]@{
                    'Command' = [string]'git'
                } | IsCommandExists
    
            .LINK
            https://learn.microsoft.com/zh-cn/powershell/module/microsoft.powershell.core/about/about_automatic_variables
        #>
        [OutputType([bool])]
        param(
            [Parameter(Mandatory=$true, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True)]
            [string] $Command
        )
        Get-Command -ErrorAction SilentlyContinue "$Command"  | Out-Null
        if ($?) {
            return $True
        }
        return $False
    }

外部命令行调用

# 命令行调用 pwsh 执行 PowerShell 命令 Get-InstalledModule
pwsh -NoLogo -Command "& {Get-InstalledModule}"

参考

0

评论 (0)

取消