윈도우 파워셸에서 명령줄 인수 가져오는 방법
- PowerShell 스크립트에서 매개변수 정의하기
- PowerShell 스크립트에서 명명된 매개변수
- PowerShell 스크립트에서 매개변수에 기본값 할당하기
- PowerShell 스크립트에서 스위치 매개변수
- PowerShell 스크립트에서 필수 매개변수

우리는 param()
이라는 Windows PowerShell 매개변수 함수를 사용하여 인수를 처리합니다. Windows PowerShell 매개변수 함수는 모든 스크립트의 기본 요소입니다. 매개변수는 개발자가 스크립트 사용자에게 실행 시간에 입력을 제공할 수 있도록 하는 방법입니다.
이 기사에서는 매개변수 함수로 스크립트를 생성하고 이를 사용하는 방법 및 매개변수를 구축하기 위한 몇 가지 모범 사례를 배웁니다.
PowerShell 스크립트에서 매개변수 정의하기
관리자는 매개변수 함수 param()
을 사용하여 스크립트와 함수에 대한 매개변수를 생성할 수 있습니다. 함수는 변수로 정의된 하나 이상의 매개변수를 포함합니다.
Hello_World.ps1
:
param(
$message
)
그러나 매개변수가 필요한 입력 유형만 수락하는지 확인하기 위해 모범 사례에서는 매개변수 블록 [Parameter()]
를 사용하여 매개변수에 데이터 유형을 할당하고 변수를 정의하기 전에 데이터 유형을 대괄호 []
로 묶는 것을 권장합니다.
Hello_World.ps1
:
param(
[Parameter()]
[String]$message
)
위의 예제 Hello_World.ps1
에서 변수 message
는 주어진 값의 데이터 유형이 String
일 때만 전달된 값을 수락합니다.
PowerShell 스크립트에서 명명된 매개변수
스크립트에서 매개변수 함수를 사용하는 한 가지 방법은 매개변수 이름을 사용하는 것입니다. 이 방법을 명명된 매개변수라고 합니다. 명명된 매개변수를 통해 스크립트나 함수를 호출할 때 변수 이름을 매개변수의 전체 이름으로 사용합니다.
우리는 Hello_World.ps1
을 만들었고 이 예제에서 매개변수 함수 내부에 변수를 정의했습니다. 매개변수 함수 내부에 하나 이상의 변수를 넣을 수 있다는 점을 기억하세요.
Hello_World.ps1
:
param(
[Parameter()]
[String]$message,
[String]$emotion
)
Write-Output $message
Write-Output "I am $emotion"
이제 .ps1
파일을 실행할 때 인수로 명명된 매개변수를 사용할 수 있습니다.
.\Hello_World.ps1 -message 'Hello World!' -emotion 'happy'
출력:
Hello World!
I am happy
PowerShell 스크립트에서 매개변수에 기본값 할당하기
스크립트 내부에서 매개변수에 값을 할당하여 미리 기본값을 지정할 수 있습니다. 그런 다음 실행 라인에서 값을 전달하지 않고 스크립트를 실행하면 스크립트 내부에 정의된 변수의 기본값을 가져옵니다.
param(
[Parameter()]
[String]$message = "Hello World",
[String]$emotion = "happy"
)
Write-Output $message
Write-Output "I am $emotion"
.\Hello_World.ps1
출력:
Hello World!
I am happy
PowerShell 스크립트에서 스위치 매개변수
우리가 사용할 수 있는 또 다른 매개변수는 [switch]
데이터 유형으로 정의된 스위치 매개변수입니다. 스위치 매개변수는 true
또는 false
를 나타내기 위해 이진 또는 부울 값에 사용됩니다.
Hello_World.ps1
:
param(
[Parameter()]
[String]$message,
[String]$emotion,
[Switch]$display
)
if ($display) {
Write-Output $message
Write-Output "I am $emotion"
}
else {
Write-Output "User denied confirmation."
}
아래의 구문을 사용하여 스크립트 매개변수로 스크립트를 호출할 수 있습니다.
.\Hello_World.ps1 -message 'Hello World!' -emotion 'happy' -display:$false
출력:
User denied confirmation.
PowerShell 스크립트에서 필수 매개변수
스크립트 실행 시 사용해야 하는 하나 이상의 매개변수가 있는 경우가 일반적입니다. 매개변수 블록 [Parameter()]
내에 Mandatory
속성을 추가하여 매개변수를 필수로 만들 수 있습니다.
Hello_World.ps1:
param(
[Parameter(Mandatory)]
[String]$message,
[String]$emotion,
[Switch]$display
)
if ($display) {
Write-Output $message
Write-Output "I am $emotion"
}
else {
Write-Output "User denied confirmation."
}
Hello_World.ps1
을 실행할 때 Windows PowerShell은 스크립트 실행을 허용하지 않으며 값 입력을 요청합니다.
.\Hello_World.ps1
출력:
cmdlet hello_world.ps1 at command pipeline position 1
Supply values for the following parameters:
message:
Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.
LinkedIn