about_Debuggers

업데이트 날짜: 2012년 8월

적용 대상: Windows PowerShell 2.0, Windows PowerShell 3.0

여기에 소개를 삽입합니다.

항목

about_Debuggers

간단한 설명

Windows PowerShell® 디버거에 대해 설명합니다.

자세한 설명

디버깅은 스크립트 지침의 오류를 식별하고 해결하기 위해 실행하는 동안 스크립트를 검사하는 과정입니다. Windows PowerShell 디버거는 스크립트, 함수, 명령, Windows PowerShell 워크플로 또는 식의 오류 및 비효율을 검사하고 식별하도록 도와 줍니다.

Windows PowerShell 4.0에서 Windows PowerShell 디버거는 스크립트, 함수, 워크플로, 명령 또는 원격 컴퓨터의 Windows PowerShell 콘솔(ISE가 아닌)에서 실행 중인 식을 디버깅하도록 업데이트되었습니다. Enter-PSSession을 실행하면 원격 컴퓨터에서 중단점을 설정하고 스크립트 파일 및 명령을 디버깅할 수 있는 대화형 원격 PowerShell 세션을 시작할 수 있습니다. Enter-PSSession 기능은 원격 컴퓨터에서 스크립트 또는 명령을 실행 중인 중단된 세션을 다시 연결하고 전환할 수 있도록 업데이트되었습니다. 실행 중인 스크립트가 중단점을 만나면 클라이언트 세션이 자동으로 디버거를 시작합니다. 스크립트를 실행 중인 중단된 세션이 이미 중단점을 만나고 중단점에서 중단된 경우, 세션에 다시 연결한 후 Enter-PSSession이 자동으로 명령줄 디버거를 시작합니다.

Windows PowerShell 4.0 디버거를 사용하여 Windows PowerShell 콘솔 또는 Windows PowerShell ISE에서 Windows PowerShell 워크플로를 디버깅할 수도 있습니다.

Windows PowerShell 디버거의 기능을 사용하여 Windows PowerShell 스크립트, 함수, 명령, 워크플로 또는 식을 실행하는 동안 검사할 수 있습니다. Windows PowerShell 디버거는 중단점 설정, 중단점 관리 및 호출 스택을 수행할 수 있는 cmdlet 집합을 포함하고 있습니다.

DEBUGGER CMDLET

Windows PowerShell 디버거는 다음과 같은 cmdlet 집합을 포함하고 있습니다

          Set-PsBreakpoint:     Sets breakpoints on lines, variables, and
                                commands. 

          Get-PsBreakpoint:     Gets breakpoints in the current session.

          Disable-PsBreakpoint: Turns off breakpoints in the current session.

          Enable-PsBreakpoint:  Re-enables breakpoints in the current session.

          Remove-PsBreakpoint:  Deletes breakpoints from the current session.

          Get-PsCallStack:      Displays the current call stack. 

디버거 시작 및 중단

디버거를 시작하려면 하나 이상의 중단점을 설정합니다. 그런 다음 디버깅할 스크립트, 명령 또는 함수를 실행합니다.

중단점에 도달하면 실행이 중단되고 제어권이 디버거로 넘어갑니다.

디버거를 중단하려면 스크립트, 명령 또는 함수를 완료될 때까지 실행합니다. 혹은 "stop" 또는 "t"를 누릅니다.

디버거 명령

Windows PowerShell 콘솔에서 디버거를 사용할 때 다음과 같은 명령을 사용하여 실행을 제어합니다. Windows PowerShell ISE의 경우, 디버그 메뉴의 명령을 사용합니다.

참고: 다른 호스트 응용 프로그램에서 디버거를 사용하는 방법은 호스트 응용 프로그램 설명서를 참조하세요.

s, Step-into        Executes the next statement and then stops.


 v, Step-over        Executes the next statement, but skips functions
                            and invocations. The skipped statements are
                            executed, but not stepped through.


 o, Step-out         Steps out of the current function; up one level
                            if nested. If in the main body, it continues to
                            the end or the next breakpoint. The skipped
                            statements are executed, but not stepped through.


 c, Continue         Continues to run until the script is complete or
                            until the next breakpoint is reached. The skipped
                            statements are executed, but not stepped through.


        l, List             Displays the part of the script that is executing.
                            By default, it displays the current line, five
                            previous lines, and 10 subsequent lines. To continue
                            listing the script, press ENTER.
                        

        l <m>, List         Displays 16 lines of the script beginning with the
                            line number specified by <m>.                           

        l <m> <n>, List     Displays <n> lines of the script, beginning with the
                            line number specified by <m>.                           

        q, Stop             Stops executing the script, and exits the debugger.


        k, Get-PsCallStack  Displays the current call stack.


<Enter>             Repeats the last command if it was Step (s), 
                            Step-over (v), or List (l). Otherwise, represents a
                            submit action.  
                           

?, h                Displays the debugger command Help.


      To exit the debugger, use Stop (q).

이 디버거 명령을 사용하면 스크립트를 실행하고, 원하는 지점에서 중단하고, 변수의 값 및 시스템의 상태를 검사하고, 문제를 식별할 때까지 스크립트 실행을 계속할 수 있습니다.

참고:

">" 같은 리디렉션 연산자로 문을 한 단계씩 실행하면 Windows PowerShell 디버거는 스크립트의 모든 남은 문을 끝까지 한 단계씩 실행합니다.

스크립트 변수의 값 표시

디버거 안에 있는 동안 명령을 입력하고, 변수의 값을 표시하고, cmdlet을 사용하고, 명령줄에서 스크립트 실행할 수도 있습니다.

다음과 같은 자동 변수를 제외하고 디버깅 중인 스크립트의 모든 변수의 현재 값을 표시할 수 있습니다.

          $_
          $Args
          $Input
          $MyInvocation
          $PSBoundParameters

이 변수의 값 중 하나 이상을 표시하려고 하면 스크립트의 변수의 값이 아닌 디버거가 사용하는 내부 파이프라인에 대한 해당 변수의 값을 얻습니다.

디버깅 중인 스크립트에 대한 이 변수의 값을 표시하려면 스크립트에서 새 변수에 자동 변수의 값을 할당합니다. 그런 다음 새 변수의 값을 표시할 수 있습니다.

예:

          $scriptArgs = $Args
          $scriptArgs

이 항목의 예제에서는 다음과 같이 $MyInvocation 변수의 값을 다시 할당합니다.

          $scriptname = $MyInvocation.MyCommand.Path

디버거 환경

중단점에 도달하면 디버거 환경으로 전환됩니다. 명령 프롬프트는 "[DBG]:"로 시작하도록 바뀝니다. 워크플로를 디버깅하는 경우 프롬프트는 "[WFDBG]"입니다. 프롬프트를 사용자 지정할 수 있습니다.

또한 Windows PowerShell 콘솔 같은 일부 호스트 응용 프로그램의 경우(단, Windows PowerShell 통합 스크립팅 환경[ISE] 제외) 디버깅을 위해 중첩 프롬프트가 열립니다. 명령 프롬프트에 나타나는 반복되는 보다 큰(>) 문자(ASCII 62)를 보고 중첩 프롬프트임을 알 수 있습니다.

예를 들어 다음은 Windows PowerShell 콘솔의 기본 디버깅 프롬프트입니다.

[DBG]: PS (get-location)>>>

$NestedPromptLevel 자동 변수를 사용하면 중첩 수준을 확인할 수 있습니다.

또한 로컬 범위에 자동 변수 $PSDebugContext가 정의됩니다. $PsDebugContext variable 변수의 유무를 보고 디버거 안에 있는지 여부를 판단할 수 있습니다.

예를 들면 다음과 같습니다.

          if ($psdebugcontext) {"Debugging"} else {"Not Debugging"}

디버깅 시 $PSDebugContext 변수의 값을 사용할 수 있습니다.

[DBG]: PS>>> $psdebugcontext.invocationinfo

        Name   CommandLineParameters  UnboundArguments  Location
        ----   ---------------------  ----------------  --------
        =      {}                     {}                C:\ps-test\vote.ps1 (1)

디버깅 및 범위

디버거로 분기해도 작동 중인 범위가 바뀌지 않지만 스크립트의 중단점에 도달하면 스크립트 범위로 이동합니다. 스크립트 범위는 디버거를 실행한 범위의 하위 범위입니다.

스크립트 범위에서 정의된 변수와 별칭을 찾으려면 Get-Alias 또는 Get-Variable cmdlet의 Scope 매개 변수를 사용합니다.

예를 들어 다음 명령은 로컬 (스크립트) 범위의 변수를 가져옵니다.

  get-variable -scope 0

이 명령을 다음과 같이 약어로 표기할 수 있습니다.

gv -s 0

이는 스크립트에 정의한 변수와 디버깅 중에 정의한 변수만 보려는 경우에 유용한 방법입니다.

명령줄에서 디버깅

변수 중단점 또는 명령 중단점을 설정할 때 중단점을 스크립트에서만 설정할 수 있습니다. 그러나 기본적으로 중단점은 현재 세션에서 실행하는 어느 대상에 대해서도 설정할 수 있습니다.

예를 들어 $name 변수에 중단점을 설정하면 디버거는 해당 중단점을 사용하지 않도록 설정하거나 제거할 때까지 실행하는 어떤 스크립트, 명령, 함수, 스크립트 cmdlet 또는 식의 어떤 $name 변수에서도 중단합니다.

이를 통해 세션 및 사용자 프로필의 함수, 변수, 기타 스크립트의 영향을 받을 수 있는 더 현실적인 컨텍스트에서 스크립트를 디버깅할 수 있습니다.

줄 중단점은 스크립트 파일 전용이므로 스크립트 파일에서만 설정됩니다.

워크플로 디버깅

Windows PowerShell 4.0 디버거를 사용하여 Windows PowerShell 콘솔 또는 Windows PowerShell ISE에서 Windows PowerShell 워크플로를 디버깅할 수 있습니다. Windows PowerShell 디버거를 사용하여 워크플로를 디버깅하는 데에는 몇 가지 제한이 있습니다.

-- You can view workflow variables while you are in the debugger, but
         setting workflow variables from within the debugger is not supported.
      -- Tab completion when stopped in the workflow debugger is not
         available.
      -- Workflow debugging works only with synchronous running of workflows from
         a Windows PowerShell script. You cannot debug workflows if they are
         running as a job (with the –AsJob parameter).
      -- Other nested debugging scenarios--such as a workflow calling another
         workflow, or a workflow calling a script--are not implemented.

다음 예제에서는 워크플로 디버깅을 보여 줍니다. 참고로 디버거가 워크플로 함수를 한 단계씩 실행할 때 디버거 프롬프트는 [WFDBG]로 바뀝니다.

          PS C:\> Set-PSBreakpoint -Script C:\TestWFDemo1.ps1 -Line 8

          ID Script           Line Command    Variable     Action
          -- ------           ---- -------    --------     ------
          0 TestWFDemo1.ps1   8

          PS C:\> C:\TestWFDemo1.ps1
          Entering debug mode. Use h or ? for help.

          Hit Line breakpoint on 'C:\TestWFDemo1.ps1:8'

          At C:\TestWFDemo1.ps1:8 char:5
          +     Write-Output -InputObject "Now writing output:"
          +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          [WFDBG:localhost]: PS C:\>> list

              3:
              4:  workflow SampleWorkflowTest
              5:  {
              6:      param ($MyOutput)
              7:
              8:*     Write-Output -InputObject "Now writing output:"
              9:      Write-Output -Input $MyOutput
             10:
             11:      Write-Output -InputObject "Get PowerShell process:"
             12:      Get-Process -Name powershell
             13:
             14:      Write-Output -InputObject "Workflow function complete."
             15:  }
             16:
             17:  # Call workflow function
             18:  SampleWorkflowTest -MyOutput "Hello"

          [WFDBG:localhost]: PS C:\>> $MyOutput
          Hello
          [WFDBG:localhost]: PS C:\>> stepOver
          Now writing output:
          At C:\TestWFDemo1.ps1:9 char:5
          +     Write-Output -Input $MyOutput
          +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          [WFDBG:localhost]: PS C:\>> list

              4:  workflow SampleWorkflowTest
              5:  {
              6:      param ($MyOutput)
              7:
              8:      Write-Output -InputObject "Now writing output:"
              9:*     Write-Output -Input $MyOutput
             10:
             11:      Write-Output -InputObject "Get PowerShell process:"
             12:      Get-Process -Name powershell
             13:
             14:      Write-Output -InputObject "Workflow function complete."
             15:  }
             16:
             17:  # Call workflow function
             18:  SampleWorkflowTest -MyOutput "Hello"
             19:

          [WFDBG:localhost]: PS C:\>> stepOver
          Hello
          At C:\TestWFDemo1.ps1:11 char:5
          +     Write-Output -InputObject "Get PowerShell process:"
          +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          [WFDBG:localhost]: PS C:\>> stepOut
          Get PowerShell process:

          Handles  NPM(K)    PM(K)   WS(K) VM(M)   CPU(s)     Id ProcessName    PSComputerName
          -------  ------    -----   ----- -----   ------     -- -----------    --------------
              433      35   106688   128392   726     2.67   7124 powershell    localhost
              499      44   134244   172096   787     2.79   7452 powershell    localhost
          Workflow function complete.

함수 디버깅

Begin, Process 및 End 섹션이 있는 함수에 중단점을 설정하면 디버거는 각 섹션의 첫 번째 줄에서 중단합니다.

예를 들면 다음과 같습니다.

              function test-cmdlet
              {
                  begin
                  {
                      write-output "Begin"
                  }
                  process
                  {
                      write-output "Process"
                  }
                  end
                  {
                      write-output "End"
                  }
              }
        
          C:\PS> set-psbreakpoint -command test-cmdlet

          C:\PS> test-cmdlet
    
          Begin
          Entering debug mode. Use h or ? for help.

          Hit Command breakpoint on 'prompt:test-cmdlet'

          test-cmdlet

          [DBG]: C:\PS> c
          Process
          Entering debug mode. Use h or ? for help.

          Hit Command breakpoint on 'prompt:test-cmdlet'

          test-cmdlet

          [DBG]: C:\PS> c
          End
          Entering debug mode. Use h or ? for help.

          Hit Command breakpoint on 'prompt:test-cmdlet'

          test-cmdlet

          [DBG]: C:\PS> 

원격 스크립트 디버깅

Windows PowerShell 4.0의 경우 Windows PowerShell 4.0 콘솔의 원격 세션에서 Windows PowerShell 디버거를 실행할 수 있습니다. Enter-PSSession 기능은 원격 컴퓨터에서 현재 스크립트를 실행 중인 중단된 세션을 다시 연결하고 전환할 수 있도록 업데이트되었습니다. 실행 중인 스크립트가 중단점을 만나면 클라이언트 세션이 자동으로 디버거를 시작합니다. 다음은 스크립트의 줄 6, 11, 22 및 25에 중단점이 설정되었을 때 이 기능이 작동하는 방법을 보여 주는 예제입니다. 참고로 이 예제에서는 디버거가 시작할 때 식별 프롬프트 두 개가 있습니다. 하나는 세션이 실행 중인 컴퓨터의 이름이며, 다른 하나는 디버깅 모드에 있음을 알려 줄 수 있는 DBG 프롬프트입니다.

          Enter-Pssession -Cn localhost
          [localhost]: PS C:\psscripts> Set-PSBreakpoint .\ttest19.ps1 6,11,22,25

          ID Script          Line     Command          Variable          Action
          -- ------          ----     -------          --------          ------
          0 ttest19.ps1          6
          1 ttest19.ps1          11
          2 ttest19.ps1          22
          3 ttest19.ps1          25

           [localhost]: PS C:\psscripts> .\ttest19.ps1
          Hit Line breakpoint on 'C:\psscripts\ttest19.ps1:11'

          At C:\psscripts\ttest19.ps1:11 char:1
          + $winRMName = "WinRM"
          + ~
           [localhost]: [DBG]: PS C:\psscripts>> list


          6:      1..5 | foreach { sleep 1; Write-Output "hello2day $_" }
          7:  }
          8:
          9:  $count = 10
          10:  $psName = "PowerShell"
          11:* $winRMName = "WinRM"
          12:  $myVar = 102
          13:
          14:  for ($i=0; $i -lt $count; $i++)
          15:  {
          16:      sleep 1
          17:      Write-Output "Loop iteration is: $i"
          18:      Write-Output "MyVar is $myVar"
          19:
          20:      hello2day
          21:

           [localhost]: [DBG]: PS C:\psscripts>> stepover
          At C:\psscripts\ttest19.ps1:12 char:1
          + $myVar = 102
          + ~
           [localhost]: [DBG]: PS C:\psscripts>> quit
           [localhost]: PS C:\psscripts> Exit-PSSession
          PS C:\psscripts>

예제

이 테스트 스크립트는 운영 체제의 버전을 검색하고 시스템에 적절한 메시지를 표시하며, 그리고 함수, 함수 호출 및 변수를 포함하고 있습니다.

다음 명령은 테스트 스크립트 파일의 내용을 표시합니다.

  c:>\PS-test>  get-content test.ps1


  function psversion {
             "Windows PowerShell " + $psversiontable.psversion
              if ($psversiontable.psversion.major -lt 2) {
                  "Upgrade to Windows PowerShell 2.0!"
              }
              else {
                  "Have you run a background job today (start-job)?"
              }
          }

  $scriptname = $MyInvocation.MyCommand.Path
  psversion
  "Done $scriptname."

시작하려면 줄, 명령, 변수 또는 함수 등 스크립트에서 관심이 있는 지점에 중단점을 설정합니다.

먼저 현재 디렉터리에 있는 Test.ps1 스크립트의 첫 줄에 줄 중단점을 만듭니다.

PS C:\ps-test> set-psbreakpoint -line 1 -script test.ps1 

이 명령을

PS C:\ps-test> spb 1 -s test.ps1

명령은 줄 중단점 개체(System.Management.Automation.LineBreakpoint)를 반환합니다.

      Column     : 0
            Line       : 1
            Action     :
            Enabled    : True
            HitCount   : 0
            Id         : 0
            Script     : C:\ps-test\test.ps1
            ScriptName : C:\ps-test\test.ps1

이제 스크립트를 시작합니다.

PS C:\ps-test> .\test.ps1

스크립트가 첫 번째 중단점에 도달하면 중단점 메시지에 디버거가 활성 상태임을 나타냅니다. 중단점을 설명하고 스크립트의 첫 줄(함수 선언)을 미리 봅니다. 또한 명령 프롬프트는 디버거에 제어권이 있음을 나타내도록 바뀝니다.

미리 보기 줄에는 스크립트 이름과 미리 본 명령 줄 수가 포함되어 있습니다.

          Entering debug mode. Use h or ? for help.

          Hit Line breakpoint on 'C:\ps-test\test.ps1:1'

          test.ps1:1   function psversion {
          DBG>

Step 명령을 사용하여 스크립트의 첫 번째 문을 실행하고 다음 문을 미리 봅니다. 다음 문은 $MyInvocation 자동 변수를 사용하여 $ScriptName 변수의 값을 스크립트 파일의 경로와 파일 이름으로 설정합니다.

          DBG> s
          test.ps1:11  $scriptname = $MyInvocation.MyCommand.Path

이 시점에서 $ScriptName 변수는 채워지지 않지만 해당 값을 표시하여 변수의 값을 확인할 수 있습니다. 이 경우 값은 $null입니다.

          DBG> $scriptname
          DBG>

또 다른 Step 명령을 사용하여 현재 문을 실행하고 스크립트의 다음 문을 미리 봅니다. 다음 문은 PsVersion 함수를 호출합니다.

  DBG> s
  test.ps1:12  psversion

이 시점에서 $ScriptName 변수가 채워지지만 해당 값을 표시하여 변수의 값을 확인합니다. 이 경우 값은 스크립트 경로로 설정됩니다.

          DBG> $scriptname
          C:\ps-test\test.ps1

또 다른 Step 명령을 사용하여 함수 호출을 실행합니다. ENTER를 누르거나 "s"(Step을 의미)를 입력합니다.

  DBG> s
  test.ps1:2       "Windows PowerShell " + $psversiontable.psversion

디버그 메시지에 함수의 문에 대한 미리 보기가 포함되어 있습니다. 이 문을 실행하고 함수의 다음 문을 미리 보려면 Step 명령을 사용할 수 있습니다. 단, 이 경우 Step-Out 명령(o)을 사용합니다. 이는 함수의 실행을 완료하고(중단점에 도달하지 않은 한) 스크립트의 다음 문까지 한 단계씩 실행합니다.

  DBG> o
  Windows PowerShell 2.0
  Have you run a background job today (start-job)?
  test.ps1:13  "Done $scriptname"

스크립트의 마지막 문에 있으므로 Step, Step-Out 및 Continue 명령은 동일한 효과를 갖습니다. 이 경우 Step-Out(o)을 사용합니다.

  Done C:\ps-test\test.ps1
  PS C:\ps-test>

Step-Out 명령은 마지막 명령을 실행합니다. 표준 명령 프롬프트는 디버거가 종료했고 제어권을 명령 프로세서로 반환했음을 나타냅니다.

이제 디버거를 다시 실행합니다. 먼저, 현재 중단점을 삭제하기 위해 Get-PsBreakpoint 및 Remove-PsBreakpoint cmdlet을 사용합니다. (중단점을 다시 사용할 수도 있다고 생각하면 Remove-PsBreakpoint 대신에 Disable-PsBreakpoint cmdlet을 사용합니다.)

  PS C:\ps-test> Get-PsBreakpoint | Remove-PSBreakpoint

이 명령을

  PS C:\ps-test> gbp | rbp

또는 다음 함수 같은 함수를 작성하여 명령을 실행합니다.

  function delbr { gbp | rbp }

이번에는 $scriptname 변수에 중단점을 만듭니다.

  PS C:\ps-test> set-psbreakpoint -variable scriptname -script test.ps1

이 명령을 다음과 같이 약어로 표기할 수 있습니다.

  PS C:\ps-test> sbp -v scriptname -s test.ps1

이제 스크립트를 시작합니다. 스크립트는 변수 중단점에 도달합니다. 기본 모드는 쓰기이므로 실행은 변수의 값을 변경하는 문의 바로 앞에서 중단합니다.

  PS C:\ps-test> .\test.ps1
  Hit Variable breakpoint on 'C:\ps-test\test.ps1:$scriptname'
          (Write access)

  test.ps1:11  $scriptname = $MyInvocation.mycommand.path
  DBG>

$scriptname 변수의 현재 값($null)을 표시합니다.

          DBG> $scriptname
          DBG>

Step 명령을 사용하여 변수를 채우는 문을 실행합니다. 그런 다음 $scriptname 변수의 새 값을 표시합니다.

  DBG> $scriptname
  C:\ps-test\test.ps1

Step 명령을 사용하여 스크립트의 다음 문을 미리 봅니다.

  DBG> s
  test.ps1:12  psversion

다음 문은 PsVersion 함수 호출입니다. 함수를 건너뛰지만 여전히 실행하려면 Step-Over 명령(v)을 사용합니다. Step-Over를 사용할 때 이미 함수 안에 있는 경우 이는 효과가 없습니다. 함수 호출이 표시되지만 실행되지 않습니다.

  DBG> v
  Windows PowerShell 2.0
  Have you run a background job today (start-job)?
  test.ps1:13  "Done $scriptname"   

Step-Over 명령은 함수를 실행하고 스크립트의 다음 문(마지막 줄을 인쇄함)을 미리 봅니다.

Stop 명령(t)을 사용하여 디버거를 종료합니다. 명령 프롬프트는 표준 명령 프롬프트로 돌아갑니다.

  C:\ps-test>

중단점을 삭제하려면 Get-PsBreakpoint 및 Remove-PsBreakpoint cmdlet을 사용합니다.

  PS C:\ps-test> Get-PsBreakpoint | Remove-PSBreakpoint

PsVersion 함수에 새 명령 중단점을 만듭니다.

          PS C:\ps-test> Set-PsBreakpoint -command psversion -script test.ps1 

이 명령을 다음과 같이 약어로 표기할 수 있습니다.

          PS C:\ps-test> sbp -c psversion -s test.ps1 

이제 스크립트를 실행합니다.

          PS C:\ps-test> .\test.ps1
          Hit Command breakpoint on 'C:\ps-test\test.ps1:psversion'

          test.ps1:12  psversion
          DBG>

스크립트는 함수 호출에서 중단점에 도달합니다. 이 지점에서 함수는 아직 호출되지 않았습니다. 따라서 이때 Set-PsBreakpoint의 Action 매개 변수를 사용하여 중단점 실행의 조건을 설정하거나 로그 시작 또는 진단이나 보안 스크립트 호출 같은 예비 작업이나 진단 작업을 수행할 수 있습니다.

작업을 설정하려면 Continue 명령(c)을 사용하여 스크립트를 중단하고 Remove-PsBreakpoint 명령을 사용하여 현재 중단점을 삭제합니다. (중단점은 읽기 전용이므로 현재 중단점에 작업을 추가할 수 없습니다.)

  DBG> c
  Windows PowerShell 2.0
  Have you run a background job today (start-job)?
  Done C:\ps-test\test.ps1

  PS C:\ps-test> get-psbreakpoint | remove-psbreakpoint
  PS C:\ps-test>

이번에는 작업이 포함된 새 명령 중단점을 만듭니다. 다음 명령은 함수가 호출될 때 $scriptname 변수의 값을 기록하는 작업이 포함된 명령 중단점을 설정합니다. 작업에 Break 키워드를 사용하지 않으므로 실행이 중단되지 않습니다. (역따옴표[']는 줄 계속 문자입니다.)

         PS C:\ps-test> set-psbreakpoint -command psversion -script test.ps1  `
         -action { add-content "The value of `$scriptname is $scriptname." `
         -path action.log}

또한 중단점에 대한 조건을 설정하는 작업을 추가할 수 있습니다. 다음 명령에서 명령 중단점은 실행 정책이 스크립트 실행을 여전히 허용하는 가장 엄격한 정책인 RemoteSigned로 설정된 경우에만 실행됩니다. (역따옴표[']는 계속 문자입니다.)

          PS C:\ps-test> set-psbreakpoint -script test.ps1 -command psversion `
          -action { if ((get-executionpolicy) -eq "RemoteSigned") { break }}

작업의 Break 키워드는 디버거가 중단점을 실행하도록 지시합니다. 또한 Continue 키워드를 사용하여 디버거가 중단 없이 실행하도록 지시할 수 있습니다. 기본 키워드는 Continue이므로 Break를 지정하여 실행을 중단해야 합니다.

이제 스크립트를 실행합니다.

  PS C:\ps-test> .\test.ps1
  Hit Command breakpoint on 'C:\ps-test\test.ps1:psversion'

  test.ps1:12  psversion

실행 정책이 RemoteSigned로 설정되었으므로 실행은 함수 호출에서 중단됩니다.

이 지점에서 호출 스택을 확인하는 것이 좋습니다. Get-PsCallStack cmdlet 또는 Get-PsCallStack 디버거 명령(k)을 사용합니다. 다음 명령은 현재 호출 스택을 가져옵니다.

  DBG> k
  2: prompt
  1: .\test.ps1: $args=[]
  0: prompt: $args=[]

이 예제에서는 Windows PowerShell 디버거를 사용하는 많은 방법 중 몇 가지만 보여 줍니다.

디버거 cmdlet에 대한 자세한 내용을 보려면 다음 명령을 입력하십시오.

          help <cmdlet-name> -full

예를 들어 다음을 입력합니다.

          help set-psbreakpoint -full

Windows PowerShell의 다른 디버깅 기능

Windows PowerShell 디버거 외에도 Windows PowerShell에는 스크립트와 함수를 디버깅하는 데 사용할 수 있는 여러 다른 기능이 포함되어 있습니다.

    -- Windows PowerShell Integrated Scripting Environment (ISE) includes
       an interactive graphical debugger. For more information, start Windows
       PowerShell ISE and press F1.

    -- The Set-PSDebug cmdlet offers very basic script debugging features,
       including stepping and tracing. 

    -- Use the Set-StrictMode cmdlet to detect references to 
       uninitialized variables, to references to non-existent properties
       of an object, and to function syntax that is not valid. 

    -- Add diagnostic statements to a script, such as statements that
       display the value of variables, statements that read input from
       the command line, or statements that report the current 
       instruction. Use the cmdlets that contain the Write verb for 
       this task, such as Write-Host, Write-Debug, Write-Warning, and
       Write-Verbose.          

참고 항목

Disable-PsBreakpoint

Enable-PsBreakpoint

Get-PsBreakpoint

Get-PsCallStack

Remove-PsBreakpoint

Set-PsBreakpoint

Set-PsDebug

Set-Strictmode

Write-Debug

Write-Verbose