스크립트 모듈은 .psm1
확장에 저장된 유효한 PowerShell 스크립트입니다. 이 확장을 사용하면 PowerShell 엔진에서 파일의 규칙 및 모듈 cmdlet을 사용할 수 있습니다. 이러한 기능의 대부분은 다른 시스템에 코드를 설치하고 범위 지정을 관리하는 데 도움이 됩니다. 더 복잡한 설치 및 솔루션을 설명하는 모듈 매니페스트 파일을 사용할 수도 있습니다.
PowerShell 스크립트 모듈 작성
스크립트 모듈을 만들려면 유효한 PowerShell 스크립트를 .psm1
파일에 저장합니다. 스크립트와 스크립트가 저장된 디렉터리에서 동일한 이름을 사용해야 합니다. 예를 들어 MyPsScript.psm1
스크립트는 MyPsScript
디렉터리에 저장됩니다.
모듈의 디렉터리가 $Env:PSModulePath
지정된 경로에 있어야 합니다. 모듈의 디렉터리에는 스크립트를 실행하는 데 필요한 리소스와 모듈의 작동 방식을 PowerShell에 설명하는 모듈 매니페스트 파일이 포함될 수 있습니다.
기본 PowerShell 모듈 만들기
다음 단계에서는 PowerShell 모듈을 만드는 방법을 설명합니다.
.psm1
확장으로 PowerShell 스크립트를 저장합니다. 스크립트와 스크립트가 저장된 디렉터리에 대해 동일한 이름을 사용합니다..psm1
확장으로 스크립트를 저장하면 import-Module 같은 모듈 cmdlet을 사용할 수. 모듈 cmdlet은 주로 존재하므로 코드를 가져와서 다른 사용자의 시스템으로 내보낼 수 있습니다. 다른 솔루션은 코드를 다른 시스템에 로드한 다음, 확장 가능한 솔루션이 아닌 활성 메모리로 도트 소스로 가져오는 것입니다. 자세한 내용은 Windows PowerShell 모듈이해하세요. 기본적으로 사용자가.psm1
파일을 가져올 때 스크립트의 모든 함수에 액세스할 수 있지만 변수는 액세스할 수 없습니다.Show-Calendar
이라는 PowerShell 스크립트 예제는 이 문서의 끝부분에 제공됩니다.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 }
특정 함수 또는 변수에 대한 사용자 액세스를 제어하려면 스크립트 끝에 Export-ModuleMember 호출합니다.
문서의 맨 아래에 있는 예제 코드에는 기본적으로 노출되는 함수가 하나만 있습니다. 그러나 다음 코드에 설명된 대로 노출하려는 함수를 명시적으로 호출하는 것이 좋습니다.
function Show-Calendar { } Export-ModuleMember -Function Show-Calendar
모듈 매니페스트를 사용하여 가져온 항목을 제한할 수 있습니다. 자세한 내용은 PowerShell 모듈 가져오기 및 PowerShell 모듈 매니페스트 작성하는 방법참조하세요.
모듈을 로드해야 하는 모듈이 있는 경우 모듈 맨 위에 있는
Import-Module
사용할 수 있습니다.Import-Module
cmdlet은 대상 모듈을 시스템으로 가져오며, 이후 절차에서 사용자 고유의 모듈을 설치하는 데 사용할 수 있습니다. 이 문서의 맨 아래에 있는 샘플 코드는 가져오기 모듈을 사용하지 않습니다. 그러나 이 경우 다음 코드와 같이 파일 맨 위에 나열됩니다.Import-Module GenericModule
PowerShell 도움말 시스템에 모듈을 설명하려면 파일 내에서 표준 도움말 메모를 사용하거나 추가 도움말 파일을 만들 수 있습니다.
이 문서의 맨 아래에 있는 코드 샘플에는 주석에 도움말 정보가 포함되어 있습니다. 추가 도움말 콘텐츠가 포함된 확장된 XML 파일을 작성할 수도 있습니다. 자세한 내용은 Windows PowerShell 모듈대한 도움말 작성을 참조하세요.
모듈을 사용하여 패키지하려는 추가 모듈, XML 파일 또는 기타 콘텐츠가 있는 경우 모듈 매니페스트를 사용할 수 있습니다.
모듈 매니페스트는 다른 모듈, 디렉터리 레이아웃, 버전 관리 번호, 작성자 데이터 및 기타 정보의 이름을 포함하는 파일입니다. PowerShell은 모듈 매니페스트 파일을 사용하여 솔루션을 구성하고 배포합니다. 자세한 내용은 PowerShell 모듈 매니페스트작성하는 방법을 참조하세요.
모듈을 설치하고 실행하려면 해당 PowerShell 경로 중 하나에 모듈을 저장하고
Import-Module
사용합니다.모듈을 설치할 수 있는 경로는
$Env:PSModulePath
전역 변수에 있습니다. 예를 들어 시스템에 모듈을 저장하는 일반적인 경로는%SystemRoot%/users/<user>/Documents/PowerShell/Modules/<moduleName>
. 단일.psm1
파일인 경우에도 스크립트 모듈과 동일한 이름을 사용하는 모듈에 대한 디렉터리를 만들어야 합니다. 이러한 경로 중 하나에 모듈을 저장하지 않은 경우Import-Module
명령에서 모듈의 위치를 지정해야 합니다. 그렇지 않으면 PowerShell에서 모듈을 찾을 수 없습니다.비고
PowerShell 3.0부터 PowerShell 모듈 경로 중 하나에 모듈을 배치한 경우 명시적으로 가져올 필요가 없습니다. 사용자가 함수를 호출하면 모듈이 자동으로 로드됩니다. 모듈 경로에 대한 자세한 내용은 PowerShell 모듈 가져오기 및 about_PSModulePath 참조하세요.
현재 PowerShell 세션의 활성 서비스에서 모듈을 제거하려면 Remove-Module사용합니다.
비고
Remove-Module
현재 PowerShell 세션에서 모듈을 제거하지만 모듈을 제거하거나 모듈의 파일을 삭제하지는 않습니다.
Show-Calendar 코드 예제
다음 예제는 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
PowerShell