파워쉘 배치파일 만들기 - pawoswel baechipail mandeulgi

1.로컬 컴퓨터에 저장된 .ps1 파일 실행하기
– PowerShell console에서 파일 경로를 입력하면 된다
c:\lab\script.ps1

– 로컬 컴퓨터에 저장된 .ps1을 원격 서버(server1)에서 실행하도록 하기
Invoke-Command -ComputerName server1 -FilePath c:\lab\script.ps1

2.원격 컴퓨터에 저장된 .ps1 파일 실행하기(Invoke-Expression)
– File Server에 저장된 .ps1 파일 실행하기
Invoke-Expression -Command \\instructor\lab\script.ps1

– Web Server에 저장된 .ps1 파일 실행하기
Invoke-Expression -Command (wget http://instructor/script.ps1).content
(** wget은 Invoke-WebRequest의 Alias이다)

– Domain Controller에 저장된 .ps1 파일 실행하기
Group Policy 설정을 통하여 .ps1 파일을 다운로드하여 자동으로 실행한다

– 원격 컴퓨터(Server1)에 저장된 .ps1 파일을 로컬에서 실행하기
Invoke-Command -ComputerName Server1  -ScriptBlock {c:\Lab\CopyAll.ps1}

3. 예약 작업(Scheduled Tasks)으로 실행한다.
제어판에 있는 예약 작업에서 PowerShell의 실행 파일의 전체 경로를 사용해야 한다.
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -Command c:\lab\script.ps1

4.로컬 컴퓨터에 저장된 .bat 파일 실행하기
batch 파일을 사용하여 사용자가 해당 파일을 더블 클릭으로 실행할 수 있는 장점이 있다. 보안성보다는 편의성을 강조한 것이다(script.bat 파일은 아래와 같이 만든다)
@echo off
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -Command c:\lab\script.ps1

여기서 로컬 컴퓨터에 저장된 파일 뿐 아니라 원격에 있는 파일 서버에 저장된 파일도 실행할 수 있다는것을 기억해둔다. (-Command \\FileServer\myjob\script.ps1 으로 경로를 잡아도 된다)

Post navigation

  • 수 백대의 PC를 도메인에 가입시키는 것은 시간이 많이 걸린다. 이것을 해결하는 것이 확장자 .bat 파일을 이용하여 그 파일을 더블클릭하여 설치하면 된다.
  • 중요한 것은 그 배치 파일안에 어떤 내용은 넣느냐는 것이다. 그 파일에는 Powershell script를 실행하는 내용을 넣으면 된다. 그런데 Script는 어떻게 만들어야지 알아야 한다. 다음과 같이 순서대로 작업을 하면 된다.

    • 먼저 도메인에 가입하게 하는 Powershell script를 작성해야 한다. 이 스크립트의 내용은 도메인에 가입하고 컴퓨터를 재시작하도록 하는 것이다.
      Add-Computer -DomainName Powershell -Credential Powershell\administrator ; Restart-Computer

      (참고로 도메인에서 제거하려면 Remove-Computer ; Restart-Computer)

    • 이 내용을 C:\JoiningDomain.ps1 파일로 저장한다.
      (참고로 이 배치파일을 PC에 실행하면 ExecutionPolicy 때문에 실행이 되지 않는다. 그래서 배치 파일을 이용하는 것이다.)
    • 이제는 이 스크립트를 실행하는 배치 파일(TakingPartInDomain.bat)을 생성한다.
      Powershell.exe -ExecutionPolicy UnRestricted -File c:\joiningDomain.ps1
      (이렇게 하여 더블 클릭으로 이 파일을 실행하면 이 작업을 할 동안 만 ExecutionPolicy가 Unrestricted로 된 후 .ps1 파일을 실행한다. 그리고 다시 원래 모드인 Restricted로 돌아간다.)
    • 여기서 도메인에 가입시키는 사용자는 이 배치 파일을 USB 플래시 메모리에 저장하여 가지고 다니면서 이 배치 파일을 더블클릭하여 실행하면 도메인에 가입할 수 있다. 문제는 USB 드라이브가 어떤 볼륨인지 알 수가 없다. 그래서 Powershell.exe -ExecutionPolicy UnRestricted -File c:\joiningDomain.ps1에서 -File \\fileserver\JoiningDomain.ps1으로 바꿔서 실행하면 된다. 즉, ps1 파일을 File Server에 저장해 놓고 사용하면 된다는 것이다.

출처 : http://cloudsns.wordpress.com/category/microsoft/powershell/page/10/

주요 콘텐츠로 건너뛰기

이 브라우저는 더 이상 지원되지 않습니다.

최신 기능, 보안 업데이트, 기술 지원을 이용하려면 Microsoft Edge로 업그레이드하세요.

PowerShell 스크립트 모듈을 작성하는 방법

  • 아티클
  • 06/13/2022
  • 읽는 데 11분 걸림

이 문서의 내용

스크립트 모듈은 확장에 저장된 유효한 PowerShell 스크립트입니다 .psm1 . 이 확장을 사용하면 PowerShell 엔진에서 파일의 규칙 및 모듈 cmdlet을 사용할 수 있습니다. 이러한 기능의 대부분은 다른 시스템에 코드를 설치하고 범위 지정을 관리하는 데 도움이 됩니다. 더 복잡한 설치 및 솔루션을 설명하는 모듈 매니페스트 파일을 사용할 수도 있습니다.

PowerShell 스크립트 모듈 작성

스크립트 모듈을 만들려면 유효한 PowerShell 스크립트를 .psm1 파일에 저장합니다. 스크립트와 스크립트가 저장된 디렉터리가 동일한 이름을 사용해야 합니다. 예를 들어 이름이 지정된 MyPsScript.psm1 스크립트는 이름이 지정된 MyPsScript디렉터리에 저장됩니다.

모듈의 디렉터리가 에 지정된 $env:PSModulePath경로에 있어야 합니다. 모듈의 디렉터리에는 스크립트를 실행하는 데 필요한 리소스와 모듈의 작동 방식을 PowerShell에 설명하는 모듈 매니페스트 파일이 포함될 수 있습니다.

기본 PowerShell 모듈 만들기

다음 단계에서는 PowerShell 모듈을 만드는 방법을 설명합니다.

  1. 확장이 있는 PowerShell 스크립트를 저장합니다 .psm1 . 스크립트와 스크립트가 저장된 디렉터리에 동일한 이름을 사용합니다.

    확장을 사용하여 스크립트를 .psm1 저장하면 Import-Module과 같은 모듈 cmdlet을 사용할 수 있습니다. 모듈 cmdlet은 주로 존재하므로 코드를 가져와서 다른 사용자의 시스템으로 내보낼 수 있습니다. 다른 솔루션은 코드를 다른 시스템에 로드한 다음 확장 가능한 솔루션이 아닌 활성 메모리로 도트 소스로 가져오는 것입니다. 자세한 내용은 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 를 호출합니다.

    문서의 맨 아래에 있는 예제 코드에는 기본적으로 노출되는 함수가 하나만 있습니다. 그러나 다음 코드에 설명된 대로 노출하려는 함수를 명시적으로 호출하는 것이 좋습니다.

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

    모듈 매니페스트를 사용하여 가져온 항목을 제한할 수 있습니다. 자세한 내용은 PowerShell 모듈 가져오기 및 PowerShell 모듈 매니페스트 작성 방법을 참조하세요.

  3. 모듈을 로드해야 하는 모듈이 있는 경우 모듈 맨 위에 있는 모듈을 사용할 Import-Module수 있습니다.

    cmdlet은 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>. 단일 .psm1 파일인 경우에도 스크립트 모듈과 동일한 이름을 사용하는 모듈에 대한 디렉터리를 만들어야 합니다. 이러한 경로 중 하나에 모듈을 저장하지 않은 경우 명령에서 Import-Module 모듈의 위치를 지정해야 합니다. 그렇지 않으면 PowerShell에서 모듈을 찾을 수 없습니다.

    참고

    PowerShell 3.0부터 PowerShell 모듈 경로 중 하나에 모듈을 배치한 경우 명시적으로 가져올 필요가 없습니다. 사용자가 함수를 호출하면 모듈이 자동으로 로드됩니다. 모듈 경로에 대한 자세한 내용은 PowerShell 모듈 가져오기 및 about_PSModulePath 참조하세요.

  7. 현재 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

피드백