2016/04/23

Japan PowerShell User Group (JPPOSH) 主催の第 6 回 PowerShell 勉強会(4/9)には多数の方にお越しいただき、ありがとうございました。

PowerShell勉強会は今後も年2回くらいのペースで続けて行きたいと思っていますので、どうぞよろしくお願い致します。

さて、私のセッション「PowerShell 5.0 新機能と関連OSSのご紹介」のスライドを公開します。前半は以前のものとだいたい同じですが、正式版対応版にアップデートしています。

今回は去年から今年にかけて、PowerShell関連ソフトウェアとしてOSS化したものを、まとめて紹介しました。以下は今回紹介したもののリストです。

またデモで用いたサンプルファイルも公開します。

このzipにも同梱してますが、PSScriptAnalyzerのカスタムルールはこんな感じで作ります。作り方は、ASTを受け取って、中身をチェックして、ルールに該当するならDiagnosticRecordを返すというのが基本になります。

using namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic
using namespace System.Management.Automation.Language

Import-Module PSScriptAnalyzer

function Test-UsingVarsWithNonAsciiCharacter
{
    # 変数に半角英数字以外の文字種が含まれていると警告するカスタムルール。
    [CmdletBinding()]
    [OutputType([DiagnosticRecord[]])]
    Param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [ScriptBlockAst]
        $ScriptBlockAst
    )

    Process
    {
        [Ast[]]$variableAsts = $ScriptBlockAst.FindAll({
            param([Ast]$ast)
            $ast -is [VariableExpressionAst]
        }, $true)

        $variableAsts | 
        where {
            $_.VariablePath.UserPath -notmatch '^[a-zA-z0-9_]+$'
        }|
        foreach {
            $result = [DiagnosticRecord[]]@{
                "Message"  = "変数 `$$($_.VariablePath.UserPath) に半角英数字以外の文字種が使われています。"
                "Extent"   = $_.Extent
                "RuleName" = "AvoidUsingVarsWithNonAsciiCharacter"
                "Severity" = "Warning"
            }
            $result
        }
    }
}
Export-ModuleMember Test-UsingVarsWithNonAsciiCharacter

ついでにPesterのサンプルコードも。2つのパラメータを足し算する関数、Invoke-Additionに対するテストコードの例となります。

$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
. "$here\$sut"

Describe "Invoke-Addition" {   # テストの定義
    Context "足し算の実行" {   # テストのグループ化
        It "整数値を2個指定すると、足し算された結果が返る" {  # テストケース
            Invoke-Addition 3 5 | Should Be 8 # アサーション
        }

        It "小数値を2個指定すると、足し算された結果が返る" {
            Invoke-Addition 3.4 5.8 | Should Be 9.2
        }
    }

    Context "エラーの発生" {
        It "足し算できないものを指定するとエラー" {
            {Invoke-Addition 10 "x"} | Should Throw 
        }
    }
}

古い記事へ | 新しい記事へ


プライバシーポリシー

Twitter

Books