programing

명령줄을 통해 변수를 파워셸 스크립트로 전달

telecom 2023. 9. 7. 21:30
반응형

명령줄을 통해 변수를 파워셸 스크립트로 전달

저는 파워쉘을 처음 접했고, 기본적인 것들을 독학하려고 노력하고 있습니다.파일을 파싱하기 위해 ps 스크립트를 작성해야 하는데, 큰 어려움은 없었습니다.

이제 스크립트에 변수를 전달하도록 변경합니다.그 변수는 구문 분석 문자열이 될 것입니다.이제 변수는 단어 집합이나 여러 단어가 아니라 항상 1개의 단어가 될 것입니다.

이것은 매우 간단해 보이지만 나에게 문제가 되고 있습니다.제 간단한 코드는 다음과 같습니다.

$a = Read-Host
Write-Host $a

명령줄에서 스크립트를 실행하면 변수 전달이 작동하지 않습니다.

.\test.ps1 hello
.\test.ps1 "hello"
.\test.ps1 -a "hello"
.\test.ps1 -a hello
.\test.ps1 -File "hello"

보시다시피, 저는 대본이 가치를 가지고 그것을 출력하는 많은 방법들을 시도했지만 성공하지 못했습니다.

스크립트는 실행되고 값을 입력할 때까지 기다립니다. 그러면 해당 값이 선택됩니다.

그냥 제가 전달한 값을 출력해줬으면 좋겠는데, 제가 놓치고 있는 게 뭐가 있나요?

감사해요.

테스트.ps1에서 첫번째 줄에 이것을 만듭니다.

param(
[string]$a
)

Write-Host $a

그럼 전화해 보세요.

./Test.ps1 "Here is your text"

여기서 찾을 수 있음(영어)

다음은 파워셸 파라미터에 대한 좋은 튜토리얼입니다.

PowerShell ABC - Pis for 모수

기본적으로, 당신은 A를 사용해야 합니다.param대본의 첫줄에 있는 문장

param([type]$p1 = , [type]$p2 = , ...)

또는 $args built-in 변수를 사용합니다. 이 변수는 모든 args와 자동으로 연결됩니다.

test.ps1의 파라미터를 선언합니다.

 Param(
                [Parameter(Mandatory=$True,Position=1)]
                [string]$input_dir,
                [Parameter(Mandatory=$True)]
                [string]$output_dir,
                [switch]$force = $false
                )

Run OR Windows Task Scheduler에서 스크립트 실행:

powershell.exe -command "& C:\FTP_DATA\test.ps1 -input_dir C:\FTP_DATA\IN -output_dir C:\FTP_DATA\OUT"

아니면,

 powershell.exe -command "& 'C:\FTP DATA\test.ps1' -input_dir 'C:\FTP DATA\IN' -output_dir 'C:\FTP DATA\OUT'"

아래와 같이 매개변수 전달,

Param([parameter(Mandatory=$true,
   HelpMessage="Enter name and key values")]
   $Name,
   $Key)

.\script_name.ps1 - 이름 -

파라미터 이름을 사용하여 파라미터의 순서를 무시할 수 있습니다.

ParamEx.ps1

# Show how to handle command line parameters in Windows PowerShell
param(
  [string]$FileName,
  [string]$Bogus
)
write-output 'This is param FileName:'+$FileName
write-output 'This is param Bogus:'+$Bogus

파라엑스배트

rem Notice that named params mean the order of params can be ignored
powershell -File .\ParamEx.ps1 -Bogus FooBar -FileName "c:\windows\notepad.exe"

언급URL : https://stackoverflow.com/questions/16426688/passing-a-variable-to-a-powershell-script-via-command-line

반응형