PowerShell スクリプト モジュールを記述する方法

スクリプト モジュールは、拡張機能に保存されている任意の .psm1 有効な PowerShell スクリプトです。 この拡張機能を使用すると、PowerShell エンジンはファイルでルールとモジュール コマンドレットを使用できます。 これらの機能のほとんどは、コードを他のシステムにインストールし、スコープを管理するのに役立ちます。 さらに複雑なインストールとソリューションを記述するモジュール マニフェスト ファイルを使用することもできます。

PowerShell スクリプト モジュールの記述

スクリプト モジュールを作成するには、有効な PowerShell スクリプトをファイルに .psm1 保存します。 スクリプトとそのスクリプトが格納されているディレクトリは、同じ名前を使用する必要があります。 たとえば、名前の付いた MyPsScript.psm1 スクリプトは 、という名前 MyPsScriptのディレクトリに格納されます。

モジュールのディレクトリは、次で指定したパスに存在 $env:PSModulePathする必要があります。 モジュールのディレクトリには、スクリプトの実行に必要なリソースと、モジュールの動作を PowerShell に記述するモジュール マニフェスト ファイルを含めることができます。

基本的な PowerShell モジュールを作成する

次の手順では、PowerShell モジュールを作成する方法について説明します。

  1. 拡張機能を含む PowerShell スクリプトを .psm1 保存します。 スクリプトとスクリプトが保存されるディレクトリに同じ名前を使用します。

    拡張機能を使用してスクリプトを .psm1 保存すると、 Import-Module などのモジュール コマンドレットを使用できます。 モジュール コマンドレットは主に存在するため、コードを他のユーザーのシステムにインポートおよびエクスポートできます。 別の解決策は、コードを他のシステムに読み込み、それをアクティブメモリにドットソースすることです。これはスケーラブルなソリューションではありません。 詳細については、「Windows PowerShell モジュールについて」を参照してください。 既定では、ユーザーがファイルを .psm1 インポートすると、スクリプト内のすべての関数にアクセスできますが、変数にはアクセスできません。

    この記事の最後には、PowerShell スクリプトの例 (タイトル Show-Calendar付き) が用意されています。

    function Show-Calendar {
    param(
        [DateTime] $start = [DateTime]::Today,
        [DateTime] $end = $start,
        $firstDayOfWeek,
        [int[]] $highlightDay,
        [string[]] $highlightDate = [DateTime]::Today.ToString('yyyy-MM-dd')
        )
    
        #actual code for the function goes here see the end of the topic for the complete code sample
    }
    
  2. 特定の関数または変数へのユーザー アクセスを制御するには、スクリプトの最後に Export-ModuleMember を呼び出します。

    記事の下部にあるコード例には、既定で公開される関数が 1 つだけあります。 ただし、次のコードで説明するように、公開する関数を明示的に呼び出することをお勧めします。

    function Show-Calendar {
          }
    Export-ModuleMember -Function Show-Calendar
    

    モジュール マニフェストを使用して、インポートされる内容を制限できます。 詳細については、「 PowerShell モジュールのインポート」および「PowerShell モジュール マニフェストを記述する方法」を参照してください。

  3. 独自のモジュールを読み込む必要があるモジュールがある場合は、モジュールの上部で使用 Import-Moduleできます。

    コマンドレットは Import-Module ターゲット モジュールをシステムにインポートし、後の手順で独自のモジュールをインストールするために使用できます。 この記事の下部にあるサンプル コードでは、インポート モジュールは使用しません。 ただし、その場合は、次のコードに示すように、ファイルの先頭に一覧表示されます。

    Import-Module GenericModule
    
  4. モジュールを PowerShell ヘルプ システムに記述するには、ファイル内で標準のヘルプ コメントを使用するか、追加のヘルプ ファイルを作成します。

    この記事の下部にあるコード サンプルには、コメントにヘルプ情報が含まれています。 また、追加のヘルプ コンテンツを含む拡張 XML ファイルを記述することもできます。 詳細については、「Windows PowerShell モジュールのヘルプの記述」を参照してください。

  5. モジュール、XML ファイル、またはモジュールと共にパッケージ化するその他のコンテンツがある場合は、モジュール マニフェストを使用できます。

    モジュール マニフェストは、他のモジュールの名前、ディレクトリ レイアウト、バージョン番号、作成者データ、およびその他の情報を含むファイルです。 PowerShell では、モジュール マニフェスト ファイルを使用して、ソリューションを整理してデプロイします。 詳細については、「 PowerShell モジュール マニフェストを記述する方法」を参照してください。

  6. モジュールをインストールして実行するには、モジュールを適切な PowerShell パスのいずれかに保存して Import-Module使用します。

    モジュールをインストールできるパスは、グローバル変数にあります $env:PSModulePath 。 たとえば、システムにモジュールを保存するための共通パスは次のようになります %SystemRoot%/users/<user>/Documents/PowerShell/Modules/<moduleName>。 1 つの .psm1 ファイルであっても、スクリプト モジュールと同じ名前を使用するモジュール用のディレクトリを必ず作成してください。 これらのパスのいずれかにモジュールを保存しなかった場合は、コマンドでモジュールの場所を指定する Import-Module 必要があります。 それ以外の場合、PowerShell はモジュールを見つけることができません。

    注意

    PowerShell 3.0 以降では、モジュールをいずれかの PowerShell モジュール パスに配置した場合は、明示的にインポートする必要はありません。 ユーザーが関数を呼び出すと、モジュールが自動的に読み込まれます。 モジュール パスの詳細については、「 PowerShell モジュールのインポート 」と 「about_PSModulePath」を参照してください。

  7. 現在の PowerShell セッションでアクティブなサービスからモジュールを削除するには、 Remove-Module を使用します

    注意

    Remove-Module は現在の PowerShell セッションからモジュールを削除しますが、モジュールをアンインストールしたり、モジュールのファイルを削除したりすることはありません。

Show-Calendarコード例

次の例は、という名前の 1 つの関数を含むスクリプト モジュールです Show-Calendar。 この関数は、予定表の視覚的な表現を表示します。 サンプルには、概要、説明、パラメーター値、およびコードの PowerShell ヘルプ文字列が含まれています。 モジュールがインポートされると、コマンドによって Export-ModuleMember 関数がモジュール メンバーとしてエクスポートされます Show-Calendar

<#
 .Synopsis
  Displays a visual representation of a calendar.

 .Description
  Displays a visual representation of a calendar. This function supports multiple months
  and lets you highlight specific date ranges or days.

 .Parameter Start
  The first month to display.

 .Parameter End
  The last month to display.

 .Parameter FirstDayOfWeek
  The day of the month on which the week begins.

 .Parameter HighlightDay
  Specific days (numbered) to highlight. Used for date ranges like (25..31).
  Date ranges are specified by the Windows PowerShell range syntax. These dates are
  enclosed in square brackets.

 .Parameter HighlightDate
  Specific days (named) to highlight. These dates are surrounded by asterisks.

 .Example
   # Show a default display of this month.
   Show-Calendar

 .Example
   # Display a date range.
   Show-Calendar -Start "March, 2010" -End "May, 2010"

 .Example
   # Highlight a range of days.
   Show-Calendar -HighlightDay (1..10 + 22) -HighlightDate "2008-12-25"
#>
function Show-Calendar {
param(
    [DateTime] $start = [DateTime]::Today,
    [DateTime] $end = $start,
    $firstDayOfWeek,
    [int[]] $highlightDay,
    [string[]] $highlightDate = [DateTime]::Today.ToString('yyyy-MM-dd')
    )

## Determine the first day of the start and end months.
$start = New-Object DateTime $start.Year,$start.Month,1
$end = New-Object DateTime $end.Year,$end.Month,1

## Convert the highlighted dates into real dates.
[DateTime[]] $highlightDate = [DateTime[]] $highlightDate

## Retrieve the DateTimeFormat information so that the
## calendar can be manipulated.
$dateTimeFormat  = (Get-Culture).DateTimeFormat
if($firstDayOfWeek)
{
    $dateTimeFormat.FirstDayOfWeek = $firstDayOfWeek
}

$currentDay = $start

## Process the requested months.
while($start -le $end)
{
    ## Return to an earlier point in the function if the first day of the month
    ## is in the middle of the week.
    while($currentDay.DayOfWeek -ne $dateTimeFormat.FirstDayOfWeek)
    {
        $currentDay = $currentDay.AddDays(-1)
    }

    ## Prepare to store information about this date range.
    $currentWeek = New-Object PsObject
    $dayNames = @()
    $weeks = @()

    ## Continue processing dates until the function reaches the end of the month.
    ## The function continues until the week is completed with
    ## days from the next month.
    while(($currentDay -lt $start.AddMonths(1)) -or
        ($currentDay.DayOfWeek -ne $dateTimeFormat.FirstDayOfWeek))
    {
        ## Determine the day names to use to label the columns.
        $dayName = "{0:ddd}" -f $currentDay
        if($dayNames -notcontains $dayName)
        {
            $dayNames += $dayName
        }

        ## Pad the day number for display, highlighting if necessary.
        $displayDay = " {0,2} " -f $currentDay.Day

        ## Determine whether to highlight a specific date.
        if($highlightDate)
        {
            $compareDate = New-Object DateTime $currentDay.Year,
                $currentDay.Month,$currentDay.Day
            if($highlightDate -contains $compareDate)
            {
                $displayDay = "*" + ("{0,2}" -f $currentDay.Day) + "*"
            }
        }

        ## Otherwise, highlight as part of a date range.
        if($highlightDay -and ($highlightDay[0] -eq $currentDay.Day))
        {
            $displayDay = "[" + ("{0,2}" -f $currentDay.Day) + "]"
            $null,$highlightDay = $highlightDay
        }

        ## Add the day of the week and the day of the month as note properties.
        $currentWeek | Add-Member NoteProperty $dayName $displayDay

        ## Move to the next day of the month.
        $currentDay = $currentDay.AddDays(1)

        ## If the function reaches the next week, store the current week
        ## in the week list and continue.
        if($currentDay.DayOfWeek -eq $dateTimeFormat.FirstDayOfWeek)
        {
            $weeks += $currentWeek
            $currentWeek = New-Object PsObject
        }
    }

    ## Format the weeks as a table.
    $calendar = $weeks | Format-Table $dayNames -AutoSize | Out-String

    ## Add a centered header.
    $width = ($calendar.Split("`n") | Measure-Object -Maximum Length).Maximum
    $header = "{0:MMMM yyyy}" -f $start
    $padding = " " * (($width - $header.Length) / 2)
    $displayCalendar = " `n" + $padding + $header + "`n " + $calendar
    $displayCalendar.TrimEnd()

    ## Move to the next month.
    $start = $start.AddMonths(1)

}
}
Export-ModuleMember -Function Show-Calendar