powershell 常用代码片段 snippets

powershell这个脚本语言,因为感觉用的人比较少,生态不是很丰富,而且也没有太好的教程。

我虽然看了一些教程,但是估计大多数是powershell早期版本就有的语法。官方文档的教程也只是基础而已。

新语法有一些是很实用的,比如foreach的多进程模式。。。

还有就是写脚本的一些实用技巧,比如参数校验之类的。

powershell的vscode插件,不支持F2重构代码,不要好用,不过它的snippets不错,提示我一些powershell好用的写法。

比如你输入cmdlet,就是函数的模板。。。然后你就了解到[cmdletbinding]这个实用的语法.

所以我们就从powershell插件的snippets里面找找有什么实用用法,同时也能提高自己写脚本的效率

01.ArgumentCompleter 参数tab补全

这个标签是提供命令行参数自动tab补全用的,还是比较实用的参数。

一般情况下,固定参数的补全我们可以用ValidateSet,这个ArgumentCompleter可以实现更复杂的补全,可以执行代码获取补全的参数,比如用Get-Process获取系统中的进程名用于补全。

[ArgumentCompleter({
    [OutputType([System.Management.Automation.CompletionResult])]
    param(
        [string] $CommandName,
        [string] $ParameterName,
        [string] $WordToComplete,
        [System.Management.Automation.Language.CommandAst] $CommandAst,
        [System.Collections.IDictionary] $FakeBoundParameters
    )
    
    $CompletionResults = [System.Collections.Generic.List[System.Management.Automation.CompletionResult]]::new()
    
    
    
    return $CompletionResults
})]

validateSet的例子

Param(
    [Parameter(Mandatory=$true)]
    [ValidateSet('Apple', 'Banana', 'Pear')]
    [string[]]
    $Fruit
)

补全类可以用IArgumentCompleter class 触发

class ArgumentCompleter : System.Management.Automation.IArgumentCompleter {
    [System.Collections.Generic.IEnumerable[System.Management.Automation.CompletionResult]] CompleteArgument(
        [string] $CommandName,
        [string] $ParameterName,
        [string] $WordToComplete,
        [System.Management.Automation.Language.CommandAst] $CommandAst,
        [System.Collections.IDictionary] $FakeBoundParameters
    ) {
        $CompletionResults = [System.Collections.Generic.List[System.Management.Automation.CompletionResult]]::new()
        
        
        
        return $CompletionResults
    }
}

02.Calculated Property 计算属性

这个主要是对一些命令结果对象进行修改替换,可以调整最后的对象展示的值

@{Name='PropertyName';Expression={<# Desired result. You can reference this object via $_ and $PSItem #>}}

比如下面这个例子

Get-ChildItem *.json -File |
  Format-List Fullname,
              @{
                 name='Modified'
                 expression={$_.LastWriteTime}
                 formatstring='O'
              },
              @{
                 name='Size'
                 expression={$_.Length/1KB}
                 formatstring='N2'
              }
FullName : C:\Git\PS-Docs\PowerShell-Docs\.markdownlint.json
Modified : 2020-07-23T10:26:28.4092457-07:00
Size     : 2.40

FullName : C:\Git\PS-Docs\PowerShell-Docs\.openpublishing.publish.config.json
Modified : 2020-07-23T10:26:28.4092457-07:00
Size     : 2.25

FullName : C:\Git\PS-Docs\PowerShell-Docs\.openpublishing.redirection.json
Modified : 2020-07-27T13:05:24.3887629-07:00
Size     : 324.60

03.Comment Block

多行注释,比较实用

<#
 # {:Enter a comment or description}
#>

04.Command Helper 帮助文档

帮助文档的代码片段太实用了。

<#
.SYNOPSIS
    A short one-line action-based description, e.g. 'Tests if a function is valid'
.DESCRIPTION
    A longer description of the function, its purpose, common use cases, etc.
.NOTES
    Information or caveats about the function e.g. 'This function is not supported in Linux'
.LINK
    Specify a URI to a help page, this will show when Get-Help -Online is used.
.EXAMPLE
    Test-MyTestFunction -Verbose
    Explanation of the function or its result. You can include multiple examples with additional .EXAMPLE lines
#>

还有一个触发词是function help

05.for

for循环也是比较实用的,虽然简单,加入snippets后用起来更丝滑

for ($i = 0; $i -lt $array.Count; $i++) {
    <# Action that will repeat until the condition is met #>
}

forr

反向for循环,

for ($i = 0; $i -lt $array.Count; $i++) {
    <# Action that will repeat until the condition is met #>
}

还有foreach foreach-item,ForEach-Object -Parallel 等

06.Here-String

是一种支持多行的字符串语法。

@"
TM_SELECTED_TEXT
"@

还有一种是单引号包围的,内部的变量不会被执行,而是作为字面量,hsl

07.shouldProcess

这个相关的都是模板代码,要记的话是根本很难记住的,所以用snippet比较合适

# 比如 IfShouldProcess
if ($PSCmdlet.ShouldProcess("Target", "Operation")) {
    
}

08.模块清单 manifest

这个也是模板。。。

09.parameter 函数参数

比如parameter-literalpath

# Specifies a path to one or more locations. Unlike the Path parameter, the value of the LiteralPath parameter is
# used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters,
# enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any
# characters as escape sequences.
[Parameter(Mandatory=$true,
           Position=0,
           ParameterSetName="LiteralPath",
           ValueFromPipelineByPropertyName=$true,
           HelpMessage="Literal path to one or more locations.")]
[Alias("PSPath")]
[ValidateNotNullOrEmpty()]
[string[]]
$LiteralPath

支持宽字符 Parameter-Path-Wildcards

# Specifies a path to one or more locations. Wildcards are permitted.
[Parameter(Mandatory=$true,
           Position=Position,
           ParameterSetName="ParameterSetName",
           ValueFromPipeline=$true,
           ValueFromPipelineByPropertyName=$true,
           HelpMessage="Path to one or more locations.")]
[ValidateNotNullOrEmpty()]
[SupportsWildcards()]
[string[]]
$ParameterName

10.PSCustomObject

这个是通过hashtable创建ps对象的功能

[PSCustomObject]@{
    Name = Value
}

11.Region Block

是一种组织代码用的注释,包裹的内容可以折叠

#region 

#endregion

12.splat

很实用,就是把hashtable展开作为命令行参数。

附 snippet json文件

{
  "ArgumentCompleterAttribute": {
    "prefix": "argument-completer",
    "description": "Allows you to add tab completion values to a specific parameter by writing a script block that generates zero or more CompletionResult objects. More: Get-Help about_Functions_Argument_Completion",
    "body": [
      "[ArgumentCompleter({",
      "\t[OutputType([System.Management.Automation.CompletionResult])]",
      "\tparam(",
      "\t\t[string] \\$CommandName,",
      "\t\t[string] \\$ParameterName,",
      "\t\t[string] \\$WordToComplete,",
      "\t\t[System.Management.Automation.Language.CommandAst] \\$CommandAst,",
      "\t\t[System.Collections.IDictionary] \\$FakeBoundParameters",
      "\t)",
      "\t",
      "\t\\$CompletionResults = [System.Collections.Generic.List[System.Management.Automation.CompletionResult]]::new()",
      "\t",
      "\t${0:$TM_SELECTED_TEXT}",
      "\t",
      "\treturn \\$CompletionResults",
      "})]"
    ]
  },
  "Calculated Property": {
    "prefix": "calculated-property",
    "description": "Typically used with Select-Object or Sort-Object. More: Get-Help about_Calculated_Properties",
    "body": [
      "@{Name='${1:PropertyName}';Expression={${2:${TM_SELECTED_TEXT:<# Desired result. You can reference this object via \\$_ and \\$PSItem #>}}}}$0"
    ]
  },
  "Class": {
    "prefix": "class",
    "description": "A blueprint used to create instances of objects at run time. More: Get-Help about_Classes",
    "body": [
      "class ${1:ClassName} {",
      "\t${0:${TM_SELECTED_TEXT:<# Define the class. Try constructors, properties, or methods. #>}}",
      "}"
    ]
  },
  "Class Constructor": {
    "prefix": [
      "ctor-class",
      "class-constructor"
    ],
    "description": "Set default values and validate object logic at the moment of creating the instance of the class. Constructors have the same name as the class. Constructors might have arguments, to initialize the data members of the new object. More: Get-Help about_Classes",
    "body": [
      "${1:ClassName}(${2:<#OptionalParameters#>}) {",
      "\t${0:${TM_SELECTED_TEXT:<# Initialize the class. Use \\$this to reference the properties of the instance you are creating #>}}",
      "}"
    ]
  },
  "Class Method": {
    "prefix": "class-method",
    "description": "Defines the actions that a class can perform. Methods may take parameters that provide input data. Methods can return output. Data returned by a method can be any defined data type. More: Get-Help about_Classes",
    "body": [
      "[${1:void}] ${2:MethodName}($${3:OptionalParameters}) {",
      "\t${0:${TM_SELECTED_TEXT:<# Action to perform. You can use $$this to reference the current instance of this class #>}}",
      "}"
    ]
  },
  "Class Property": {
    "prefix": "class-property",
    "description": "Properties are variables declared at class scope. A property may be of any built-in type or an instance of another class. Classes have no restriction in the number of properties they have. More: Get-Help about_Classes",
    "body": [
      "[${1:propertyType}] $${0:PropertyName}"
    ]
  },
  "Comment Block": {
    "prefix": [
      "block-comment"
    ],
    "description": "A multi-line comment.",
    "body": [
      "$BLOCK_COMMENT_START",
      " # ${0:{$TM_SELECTED_TEXT:Enter a comment or description}}",
      "$BLOCK_COMMENT_END"
    ]
  },
  "do-until": {
    "prefix": "do-until",
    "description": "Runs a statement list repeatedly until a condition is met More: Get-Help about_Do",
    "body": [
      "do {",
      "\t${0:$TM_SELECTED_TEXT}",
      "} until (",
      "\t${1:<# Condition that stops the loop if it returns true #>}",
      ")"
    ]
  },
  "do-while": {
    "prefix": "do-while",
    "description": "Runs a statement list repeatedly as long as a condition is met. More: Get-Help about_Do",
    "body": [
      "do {",
      "\t${0:$TM_SELECTED_TEXT}",
      "} while (",
      "\t${1:<# Condition that stops the loop if it returns false #>}",
      ")"
    ]
  },
  "else": {
    "prefix": "else",
    "description": "else defines what is done when all if and elseif conditions are false. More: Get-Help about_If",
    "body": [
      "else {",
      "\t${0:${TM_SELECTED_TEXT:<# Action when all if and elseif conditions are false #>}}",
      "}"
    ]
  },
  "elseif": {
    "prefix": "elseif",
    "description": "elseif provides an alternative path when an if condition is false. More: Get-Help about_If",
    "body": [
      "elseif (${1:<#condition#>}) {",
      "\t${0:${TM_SELECTED_TEXT:<# Action when this condition is true #>}}",
      "}"
    ]
  },
  "Enum": {
    "prefix": "enum",
    "description": "An enumeration is a distinct type that consists of a set of named labels called the enumerator list. More: Get-Help about_Enum",
    "body": [
      "enum ${1:<#EnumName#>} {",
      "\t${0:${TM_SELECTED_TEXT:<# Specify a list of distinct values #>}}",
      "}"
    ]
  },
  "for": {
    "prefix": "for",
    "description": "Creates a loop that runs commands in a command block while a specified condition evaluates to $true. A typical use of the for loop is to iterate an array of values and to operate on a subset of these values. More: Get-Help about_For",
    "body": [
      "for ($${1:i} = 0; $${1:i} -lt $${2:array}.Count; $${1:i}++) {",
      "\t${0:${TM_SELECTED_TEXT:<# Action that will repeat until the condition is met #>}}",
      "}"
    ]
  },
  "for-reversed": {
    "prefix": "forr",
    "description": "reversed for loop snippet",
    "body": [
      "for ($${1:i} = $${2:array}.Count - 1; $${1:i} -ge 0 ; $${1:i}--) {",
      "\t${0:${$TM_SELECTED_TEXT}}",
      "}"
    ]
  },
  "foreach": {
    "prefix": "foreach",
    "description": "Iterate through a collection, assigning a variable to the current item on each loop rather than using the automatic variable $PSItem. More: Get-Help about_Foreach",
    "body": [
      "foreach ($${1:currentItemName} in $${2:collection}) {",
      "\t${0:${TM_SELECTED_TEXT:<# $${1} is the current item #>}}",
      "}"
    ]
  },
  "foreach-item": {
    "prefix": "foreach-item",
    "description": "Quicker definition of foreach, just highlight the variable name of the collection you want to use and type 'item' then enter then tab. More: Get-Help about_Foreach",
    "body": [
      "foreach (${1/(.*)/$1Item/} in ${1:${TM_SELECTED_TEXT:collection}}) {",
      "\t${0:${1/(.*)/$1Item/}}",
      "}"
    ]
  },
  "ForEach-Object -Parallel": {
    "prefix": "foreach-parallel",
    "description": "[PS 7+] Process multiple objects in parallel using runspaces. This has some limitations compared to a regular ForEach-Object. More: Get-Help ForEach-Object",
    "body": [
      "${1:\\$collection} | Foreach-Object -ThrottleLimit ${2:5} -Parallel {",
      "  ${0:${TM_SELECTED_TEXT:#Action that will run in Parallel. Reference the current object via \\$PSItem and bring in outside variables with \\$USING:varname}}",
      "}"
    ]
  },
  "function": {
    "prefix": "function",
    "description": "A simple function with a parameter block to specify function arguments. More: Get-Help about_Functions",
    "body": [
      "function ${1:FunctionName} {",
      "\tparam (",
      "\t\t${2:OptionalParameters}",
      "\t)",
      "\t${0:$TM_SELECTED_TEXT}",
      "}"
    ]
  },
  "Function Help": {
    "prefix": [
      "help-function",
      "comment-help"
    ],
    "description": "Comment-based help for an advanced function. More: Get-Help about_Comment_Based_Help",
    "body": [
      "<#",
      ".SYNOPSIS",
      "\t${1:A short one-line action-based description, e.g. 'Tests if a function is valid'}",
      ".DESCRIPTION",
      "\t${2:A longer description of the function, its purpose, common use cases, etc.}",
      ".NOTES",
      "\t${3:Information or caveats about the function e.g. 'This function is not supported in Linux'}",
      ".LINK",
      "\t${4:Specify a URI to a help page, this will show when Get-Help -Online is used.}",
      ".EXAMPLE",
      "\t${5:Test-MyTestFunction -Verbose}",
      "\t${6:Explanation of the function or its result. You can include multiple examples with additional .EXAMPLE lines}",
      "#>",
      "",
      "${0:$TM_SELECTED_TEXT}"
    ]
  },
  "Function-Advanced": {
    "prefix": [
      "function-advanced",
      "cmdlet"
    ],
    "description": "Script advanced function definition snippet. More: Get-Help about_Functions_Advanced",
    "body": [
      "function ${1:Verb-Noun} {",
      "\t[CmdletBinding()]",
      "\tparam (",
      "\t\t$0",
      "\t)",
      "\t",
      "\tbegin {",
      "\t\t",
      "\t}",
      "\t",
      "\tprocess {",
      "\t\t$TM_SELECTED_TEXT",
      "\t}",
      "\t",
      "\tend {",
      "\t\t",
      "\t}",
      "}"
    ]
  },
  "Function-Inline": {
    "prefix": "function-inline",
    "description": "Function definition snippet that does not contain a param block, but defines parameters inline. This syntax is commonly used in other languages. More: Get-Help about_Functions",
    "body": [
      "function ${1:FunctionName} (${2:OptionalParameters}) {",
      "\t${0:$TM_SELECTED_TEXT}",
      "}"
    ]
  },
  "Function: Suppress PSScriptAnalyzer Rule": {
    "prefix": [
      "suppress-message-rule-function",
      "[SuppressMessageAttribute]"
    ],
    "description": "Suppress a PSScriptAnalyzer rule for a function. More: https://docs.microsoft.com/en-us/powershell/utility-modules/psscriptanalyzer/overview?view=ps-modules#suppressing-rules",
    "body": [
      "[Diagnostics.CodeAnalysis.SuppressMessageAttribute(",
      "\t<#Category#>'${1:PSProvideDefaultParameterValue}', <#CheckId>\\$null, Scope='Function',",
      "\tJustification = '${0:${TM_SELECTED_TEXT:Reason for suppressing}}'",
      ")]"
    ]
  },
  "Hashtable": {
    "prefix": "hashtable",
    "description": "A key/value store that are very efficient for finding and retrieving data. More: Get-Help about_Hash_Tables",
    "body": [
      "\\$${1:Var} = @{",
      "\t${2:Name} = ${3:Value}",
      "}"
    ]
  },
  "Here-String": {
    "prefix": [
      "hs",
      "here-string"
    ],
    "description": "Escape all text but evaluate variables. More: Get-Help about_Quoting_Rules",
    "body": [
      "@\"",
      "${0:TM_SELECTED_TEXT}",
      "\"@",
      ""
    ]
  },
  "Here-String (Literal)": {
    "prefix": [
      "hsl",
      "literal-here-string"
    ],
    "description": "Escape all text literally. More: Get-Help about_Quoting_Rules",
    "body": [
      "@'",
      "${0:TM_SELECTED_TEXT}",
      "'@",
      ""
    ]
  },
  "Hidden Property": {
    "prefix": "class-proph-hidden",
    "description": "Useful for creating internal properties and methods within a class that are hidden from users. More: Get-Help about_Hidden",
    "body": [
      "hidden [${1:string}] $${0:PropertyName}"
    ]
  },
  "IArgumentCompleter Class": {
    "prefix": "iargument-completer",
    "description": "Implementation of the IArgumentCompleter interface that can be directly attached to parameters (e.g. [MyCustomArgumentCompleter]). More: Get-Help about_Functions_Argument_Completion",
    "body": [
      "class ${1:ArgumentCompleter} : System.Management.Automation.IArgumentCompleter {",
      "\t[System.Collections.Generic.IEnumerable[System.Management.Automation.CompletionResult]] CompleteArgument(",
      "\t\t[string] \\$CommandName,",
      "\t\t[string] \\$ParameterName,",
      "\t\t[string] \\$WordToComplete,",
      "\t\t[System.Management.Automation.Language.CommandAst] \\$CommandAst,",
      "\t\t[System.Collections.IDictionary] \\$FakeBoundParameters",
      "\t) {",
      "\t\t\\$CompletionResults = [System.Collections.Generic.List[System.Management.Automation.CompletionResult]]::new()",
      "\t\t",
      "\t\t${0:$TM_SELECTED_TEXT}",
      "\t\t",
      "\t\treturn \\$CompletionResults",
      "\t}",
      "}"
    ]
  },
  "if": {
    "prefix": "if",
    "description": "Run code blocks if a specified conditional test evaluates to true. More: Get-Help about_If",
    "body": [
      "if (${1:condition}) {",
      "\t${0:${TM_SELECTED_TEXT:<# Action to perform if the condition is true #>}}",
      "}"
    ]
  },
  "IfShouldProcess": {
    "prefix": "if-should-process",
    "description": "Defines a condition that only executes if -WhatIf is not set, and returns a message otherwise. More: https://docs.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-shouldprocess",
    "body": [
      "if (\\$PSCmdlet.ShouldProcess(\"${1:Target}\", \"${2:Operation}\")) {",
      "\t${0:$TM_SELECTED_TEXT}",
      "}"
    ]
  },
  "ModuleManifest": {
    "prefix": "manifest",
    "description": "Basic skeleton for a PowerShell module manifest, complete with PowerShell Gallery metadata. More: https://docs.microsoft.com/en-us/powershell/scripting/developer/module/how-to-write-a-powershell-module-manifest",
    "body": [
      "@{",
      "\t# If authoring a script module, the RootModule is the name of your .psm1 file",
      "\tRootModule = '${module:MyModule}.psm1'",
      "",
      "\tAuthor = '${author:Cool Person <coolperson@email.local>}'",
      "",
      "\tCompanyName = '${company:Contoso Inc.}'",
      "",
      "\tModuleVersion = '${ModuleVersion:0.1}'",
      "",
      "\t# Use the New-Guid command to generate a GUID, and copy/paste into the next line",
      "\tGUID = '<pasteNewGUIDhere>'",
      "",
      "\tCopyright = '2017 ${company:Copyright Holder}'",
      "",
      "\tDescription = '${Description:What does this module do?}'",
      "",
      "\t# Minimum PowerShell version supported by this module (optional, recommended)",
      "\t# PowerShellVersion = ''",
      "",
      "\t# Which PowerShell Editions does this module work with? (Core, Desktop)",
      "\tCompatiblePSEditions = @('Desktop', 'Core')",
      "",
      "\t# Which PowerShell functions are exported from your module? (eg. Get-CoolObject)",
      "\tFunctionsToExport = @('')",
      "",
      "\t# Which PowerShell aliases are exported from your module? (eg. gco)",
      "\tAliasesToExport = @('')",
      "",
      "\t# Which PowerShell variables are exported from your module? (eg. Fruits, Vegetables)",
      "\tVariablesToExport = @('')",
      "",
      "\t# PowerShell Gallery: Define your module's metadata",
      "\tPrivateData = @{",
      "\t\tPSData = @{",
      "\t\t\t# What keywords represent your PowerShell module? (eg. cloud, tools, framework, vendor)",
      "\t\t\tTags = @('${tag1:cooltag1}', '${tag2:cooltag2}')",
      "",
      "\t\t\t# What software license is your code being released under? (see https://opensource.org/licenses)",
      "\t\t\tLicenseUri = ''",
      "",
      "\t\t\t# What is the URL to your project's website?",
      "\t\t\tProjectUri = ''",
      "",
      "\t\t\t# What is the URI to a custom icon file for your project? (optional)",
      "\t\t\tIconUri = ''",
      "",
      "\t\t\t# What new features, bug fixes, or deprecated features, are part of this release?",
      "\t\t\tReleaseNotes = @'",
      "'@",
      "\t\t}",
      "\t}",
      "",
      "\t# If your module supports updatable help, what is the URI to the help archive? (optional)",
      "\t# HelpInfoURI = ''",
      "}"
    ]
  },
  "Parallel Pipeline Function": {
    "prefix": "function-parallel-pipeline",
    "description": "Collects everything in the process block and does work in the end block. Useful when making a 'fan out' function that acts on multiple items simultaneously because the pipeline only does one item at a time in the process block. More: Get-Help about_Functions_Advanced",
    "body": [
      "function $1 {",
      "  [CmdletBinding()]",
      "  param(",
      "    [parameter(ValueFromPipeline)]$$2",
      "  )",
      "",
      "  begin {",
      "    [Collections.ArrayList]\\$inputObjects = @()",
      "  }",
      "  process {",
      "    [void]\\$inputObjects.Add($$2)",
      "  }",
      "  end {",
      "    \\$inputObjects | Foreach -Parallel {",
      "      $0",
      "    }",
      "  }",
      "}"
    ]
  },
  "Parameter": {
    "prefix": "parameter",
    "description": "A parameter definition for a method or function. More: Get-Help about_Functions",
    "body": [
      "# ${1:Parameter help description}",
      "[Parameter(${2:AttributeValues})]",
      "[${3:ParameterType}]",
      "$${0:ParameterName}"
    ]
  },
  "Parameter_Block": {
    "prefix": "param-block-advanced-function",
    "description": "A parameter block for an advanced function. More: Get-Help about_Functions_Advanced",
    "body": [
      "[CmdletBinding()]",
      "param (",
      "    [Parameter()]",
      "    [${1:TypeName}]",
      "    $${2:ParameterName}$0",
      ")"
    ]
  },
  "Parameter-LiteralPath": {
    "prefix": "parameter-literalpath",
    "description": "Parameter declaration snippet for a LiteralPath parameter",
    "body": [
      "# Specifies a path to one or more locations. Unlike the Path parameter, the value of the LiteralPath parameter is",
      "# used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters,",
      "# enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any",
      "# characters as escape sequences.",
      "[Parameter(Mandatory=\\$true,",
      "           Position=${1:0},",
      "           ParameterSetName=\"${2:LiteralPath}\",",
      "           ValueFromPipelineByPropertyName=\\$true,",
      "           HelpMessage=\"Literal path to one or more locations.\")]",
      "[Alias(\"PSPath\")]",
      "[ValidateNotNullOrEmpty()]",
      "[string[]]",
      "$${2:LiteralPath}$0"
    ]
  },
  "Parameter-Path": {
    "prefix": "parameter-path",
    "description": "Parameter declaration snippet for Path parameter that does not accept wildcards. Do not use with parameter-literalpath.",
    "body": [
      "# Specifies a path to one or more locations.",
      "[Parameter(Mandatory=\\$true,",
      "           Position=${1:0},",
      "           ParameterSetName=\"${2:ParameterSetName}\",",
      "           ValueFromPipeline=\\$true,",
      "           ValueFromPipelineByPropertyName=\\$true,",
      "           HelpMessage=\"Path to one or more locations.\")]",
      "[Alias(\"PSPath\")]",
      "[ValidateNotNullOrEmpty()]",
      "[string[]]",
      "$${3:ParameterName}$0"
    ]
  },
  "Parameter-Path-Wildcards": {
    "prefix": "parameter-path-wildcards",
    "description": "Parameter declaration snippet for Path parameter that accepts wildcards. Add parameter-literalpath to handle paths with embedded wildcard chars.",
    "body": [
      "# Specifies a path to one or more locations. Wildcards are permitted.",
      "[Parameter(Mandatory=\\$true,",
      "           Position=${1:Position},",
      "           ParameterSetName=\"${2:ParameterSetName}\",",
      "           ValueFromPipeline=\\$true,",
      "           ValueFromPipelineByPropertyName=\\$true,",
      "           HelpMessage=\"Path to one or more locations.\")]",
      "[ValidateNotNullOrEmpty()]",
      "[SupportsWildcards()]",
      "[string[]]",
      "$${3:ParameterName}$0"
    ]
  },
  "Parameter: Suppress PSScriptAnalyzer Rule": {
    "prefix": [
      "suppress-message-rule-parameter",
      "[SuppressMessageAttribute]"
    ],
    "description": "Suppress a PSScriptAnalyzer rule on a parameter. More: https://docs.microsoft.com/en-us/powershell/utility-modules/psscriptanalyzer/overview?view=ps-modules#suppressing-rules",
    "body": [
      "[Diagnostics.CodeAnalysis.SuppressMessageAttribute(<#Category#>'${1:PSUseDeclaredVarsMoreThanAssignments}',",
      "\t<#ParameterName#>'${0:${TM_SELECTED_TEXT:ParamName}}",
      "\tJustification = '${0:${TM_SELECTED_TEXT:Reason for suppressing}}'",
      ")]"
    ]
  },
  "Pipeline Function": {
    "prefix": "function-pipeline",
    "description": "Basic function that accepts pipeline input. More: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_pipelines",
    "body": [
      "function $1 {",
      "  [CmdletBinding()]",
      "  param(",
      "    [parameter(ValueFromPipeline)]$2",
      "  )",
      "",
      "  process {",
      "    $0",
      "  }",
      "}"
    ]
  },
  "PSCustomObject": {
    "prefix": [
      "pscustomobject",
      "[PSCustomObject]"
    ],
    "description": "Create a custom object from a hashtable of properties. More: Get-Help about_PSCustomObject",
    "body": [
      "[PSCustomObject]@{",
      "\t${1:Name} = ${2:Value}",
      "}"
    ]
  },
  "Region Block": {
    "prefix": "region",
    "description": "Region block for organizing and folding of your code",
    "body": [
      "#region ${1}",
      "${0:$TM_SELECTED_TEXT}",
      "#endregion"
    ]
  },
  "Scope: Suppress PSScriptAnalyzer Rule": {
    "prefix": "suppress-message-rule-scope",
    "description": "Suppress a PSScriptAnalyzer rule based on a function/parameter/class/variable/object's name by setting the SuppressMessageAttribute's Target property to a regular expression or a glob pattern. More: https://docs.microsoft.com/en-us/powershell/utility-modules/psscriptanalyzer/overview?view=ps-modules#suppressing-rules",
    "body": [
      "[Diagnostics.CodeAnalysis.SuppressMessageAttribute(",
      "\t<#Category#>'${1:PSUseDeclaredVarsMoreThanAssignments}', <#CheckId#>\\$null, Scope='Function',",
      "\tTarget='${1:${TM_SELECTED_TEXT:RegexOrGlobPatternToMatchName}}'",
      "\tJustification = '${0:Reason for suppressing}}'",
      ")]"
    ]
  },
  "splat": {
    "prefix": "splat",
    "description": "Use a hashtable to capture the parameters of a function and then pass them to a function in a concise way. More: Get-Help about_Splatting",
    "body": [
      "$${1/[^\\w]/_/}Params = @{",
      "\t${2:Parameter} = ${0:Value}",
      "}",
      "${1:${TM_SELECTED_TEXT}} @${1/[^\\w]/_/}Params"
    ]
  },
  "Suppress PSScriptAnalyzer Rule": {
    "prefix": [
      "suppress-message-rule",
      "[SuppressMessageAttribute]"
    ],
    "description": "Suppress a PSScriptAnalyzer rule. More: https://docs.microsoft.com/en-us/powershell/utility-modules/psscriptanalyzer/overview?view=ps-modules#suppressing-rules",
    "body": [
      "[Diagnostics.CodeAnalysis.SuppressMessageAttribute(",
      "\t<#Category#>'${1:PSUseDeclaredVarsMoreThanAssignments}',<#CheckId#>\\$null,",
      "\tJustification = '${0:${TM_SELECTED_TEXT:Reason for suppressing}}'",
      ")]"
    ]
  },
  "switch": {
    "prefix": "switch",
    "description": "Equivalent to a series of if statements, but it is simpler. The switch statement lists each condition and an optional action. If a condition obtains, the action is performed. More: Get-Help about_Switch",
    "body": [
      "switch (${1:\\$x}) {",
      "\t${2:condition} { ${0:$TM_SELECTED_TEXT} }",
      "\tDefault {}",
      "}"
    ]
  },
  "Ternary Operator": {
    "prefix": "ternary",
    "description": "[PS 7+] Simplified version of if-else popular in other languages that works in Powershell. More: Get-Help about_If",
    "body": [
      "(${1:${TM_SELECTED_TEXT:condition}}) ? $(${2:<#Action if True#>}) : $(${0:<#Action If False#>})"
    ]
  },
  "try-catch": {
    "prefix": "try-catch",
    "description": "Attempt a block of code and if a terminating exception occurs, perform another block of code rather than terminate the program More: Get-Help about_Try_Catch_Finally",
    "body": [
      "try {",
      "\t${0:$TM_SELECTED_TEXT}",
      "}",
      "catch {",
      "\t${1:<#Do this if a terminating exception happens#>}",
      "}"
    ]
  },
  "try-catch-finally": {
    "prefix": "try-catch-finally",
    "description": "Attempt a block of code and if a terminating exception occurs, perform another block of code, finally performing a final block of code regardless of the outcome. More: Get-Help about_Try_Catch_Finally",
    "body": [
      "try {",
      "\t${0:$TM_SELECTED_TEXT}",
      "}",
      "catch {",
      "\t${1:<#Do this if a terminating exception happens#>}",
      "}",
      "finally {",
      "\t${2:<#Do this after the try block regardless of whether an exception occurred or not#>}",
      "}"
    ]
  },
  "try-finally": {
    "prefix": "try-finally",
    "description": "Attempt a block of code and perform an action regardless of the outcome. Useful for cleanup or gracefully disconnecting active sessions even if there was a terminating error. More: Get-Help about_Try_Catch_Finally",
    "body": [
      "try {",
      "\t${0:$TM_SELECTED_TEXT}",
      "}",
      "finally {",
      "\t${2:<#Do this after the try block regardless of whether an exception occurred or not#>}",
      "}"
    ]
  },
  "while": {
    "prefix": "while",
    "description": "Repeatedly perform an action after verifying a condition is true first. More: Get-Help about_While",
    "body": [
      "while (${1:condition}) {",
      "\t${0:$TM_SELECTED_TEXT}",
      "}"
    ]
  }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容