programing

Powershell ISE 내의 다른 PS1 스크립트에서 PowerShell 스크립트 PS1 호출

telecom 2023. 5. 10. 20:16
반응형

Powershell ISE 내의 다른 PS1 스크립트에서 PowerShell 스크립트 PS1 호출

Powershell ISE 내의 두 번째 myScript2.ps1 스크립트 내의 myScript1.ps1 스크립트에 대한 호출 실행을 원합니다.

MyScript2.ps1 내부의 다음 코드는 Powershell Administration에서 정상적으로 작동하지만 PowerShell ISE 내부에서는 작동하지 않습니다.

#Call myScript1 from myScript2
invoke-expression -Command .\myScript1.ps1

PowerShell ISE에서 MyScript2.ps1을 실행하면 다음 오류가 발생합니다.

'.\myScript1.ps1'이라는 용어는 cmdlet, 함수, 스크립트 파일 또는 작동 가능한 프로그램의 이름으로 인식되지 않습니다.이름의 철자를 확인하거나 경로가 포함된 경우 경로가 올바른지 확인한 후 다시 시도하십시오.

동일한 디렉토리에서 스크립트를 실행합니다.

PowerShell 3.0 이상에서는 자동 변수를 사용할 수 있습니다.$PSScriptRoot:

$PSScriptRoot/myScript1.ps1

PowerShell 1.0 및 2.0에서는 다음과 같은 특정 속성을 사용해야 합니다.

& "$(Split-Path $MyInvocation.MyCommand.Path)/myScript1.ps1"

다른 어떤 것도 사용하지 않고 그것을 사용해야 하는 이유는 이 예제 스크립트를 통해 설명할 수 있습니다.

## ScriptTest.ps1
Write-Host "InvocationName:" $MyInvocation.InvocationName
Write-Host "Path:" $MyInvocation.MyCommand.Path

여기 몇 가지 결과가 있습니다.

PSC:\Users\JasonAr>.\ScriptTest.ps1호출 이름: .\ScriptTest.ps1경로: C:\Users\JasonAr\ScriptTest.ps1
PSC:\Users\JasonAr> .\ScriptTest.ps1호출 이름: .
경로: C:\Users\JasonAr\ScriptTest.ps1
PSC:\Users\JasonAr> & ".\ScriptTest.ps1"호출 이름: &경로: C:\Users\JasonAr\ScriptTest.ps1

PowerShell 3.0 이상에서는 자동 변수를 사용할 수 있습니다.$PSScriptRoot:

## ScriptTest.ps1
Write-Host "Script:" $PSCommandPath
Write-Host "Path:" $PSScriptRoot
PSC:\Users\jarcher>.\ScriptTest.ps1스크립트: C:\Users\jarcher\ScriptTest.ps1경로: C:\사용자\저커

저는 제 스크립트 2.ps1에서 제 스크립트 1.ps1을 부르고 있습니다.

두 스크립트가 모두 동일한 위치에 있다고 가정하면 먼저 다음 명령을 사용하여 스크립트의 위치를 가져옵니다.

$PSScriptRoot

그런 다음 다음 다음과 같이 호출할 스크립트 이름을 추가합니다.

& "$PSScriptRoot\myScript1.ps1"

이게 통할 겁니다.

MyScript1.ps1의 현재 경로가 myScript2.ps1과 다릅니다.당신은 MyScript2.ps1의 폴더 경로를 가져와서 MyScript1.ps1에 연결한 후 실행할 수 있습니다.두 스크립트는 동일한 위치에 있어야 합니다.

## MyScript2.ps1 ##
$ScriptPath = Split-Path $MyInvocation.InvocationName
& "$ScriptPath\MyScript1.ps1"

한 줄 솔루션:

& ((Split-Path $MyInvocation.InvocationName) + "\MyScript1.ps1")

이것은 다른 파일에 인수를 전달하기 위한 답변에 대한 추가 정보입니다.

논쟁이 예상되는 부분

PrintName.ps1

Param(
    [Parameter( Mandatory = $true)]
    $printName = "Joe"    
)


Write-Host $printName

파일 호출 방법

Param(
    [Parameter( Mandatory = $false)]
    $name = "Joe"    
)


& ((Split-Path $MyInvocation.InvocationName) + "\PrintName.ps1") -printName $name

입력을 제공하지 않으면 기본적으로 "Joe"로 설정되며, 이는 PrintName.ps1 파일의 printName 인수로 전달되어 "Joe" 문자열을 출력합니다.

호출자와 동일한 폴더(또는 하위 폴더)에서 스크립트 파일을 쉽게 실행하려면 다음을 사용합니다.

# Get full path to the script:
$ScriptRoute = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($PSScriptRoot, "Scriptname.ps1"))

# Execute script at location:
&"$ScriptRoute"

이미 답을 찾으셨겠지만, 제가 하는 일은 이렇습니다.

일반적으로 설치 스크립트의 시작 부분에 다음 행을 배치합니다.

if(!$PSScriptRoot){ $PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent } #In case if $PSScriptRoot is empty (version of powershell V.2).  

그러면 아래 예제와 같이 $PSScriptRoot 변수를 현재 스크립트(경로)의 위치로 사용할 수 있습니다.

if(!$PSScriptRoot){ $PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent } #In case if $PSScriptRoot is empty (version of powershell V.2).  

Try {
If (Test-Path 'C:\Program Files (x86)') {
    $ChromeInstallArgs= "/i", "$PSScriptRoot\googlechromestandaloneenterprise64_v.57.0.2987.110.msi", "/q", "/norestart", "/L*v `"C:\Windows\Logs\Google_Chrome_57.0.2987.110_Install_x64.log`""
    Start-Process -FilePath msiexec -ArgumentList $ChromeInstallArgs -Wait -ErrorAction Stop
    $Result= [System.Environment]::ExitCode
} Else {
    $ChromeInstallArgs= "/i", "$PSScriptRoot\googlechromestandaloneenterprise_v.57.0.2987.110.msi", "/q", "/norestart", "/L*v `"C:\Windows\Logs\Google_Chrome_57.0.2987.110_Install_x86.log`""
    Start-Process -FilePath msiexec -ArgumentList $ChromeInstallArgs -Wait -ErrorAction Stop
    $Result= [System.Environment]::ExitCode
    }

} ### End Try block


Catch  {
    $Result = [System.Environment]::Exitcode
    [System.Environment]::Exit($Result)
   }
[System.Environment]::Exit($Result)

당신의 경우, 당신은 대체할 수 있습니다.

프로세스 시작...와 일치하는.

호출-표현식 $PSScriptRoot\ScriptName.ps1

$MY INVOCATION 및 $PSScriptRoot 자동 변수에 대한 자세한 내용은 Microsoft 사이트 https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/about/about_automatic_variables 에서 확인할 수 있습니다.

저도 비슷한 문제가 있어서 이런 식으로 해결했습니다.

내 작업 디렉토리는 일반 스크립트 폴더와 서버 특정 스크립트 폴더가 동일한 루트에 있으므로 특정 스크립트 폴더(특정 문제의 매개 변수로 일반 스크립트를 호출)를 호출해야 합니다.그래서 작업 디렉토리는 다음과 같습니다.

\Nico\Scripts\Script1.ps1
             \Script2.ps1
      \Problem1\Solution1.ps1
               \ParameterForSolution1.config
      \Problem2\Solution2.ps1
               \ParameterForSolution2.config

Solutions1 및 Solutions2는 ParameterForSolution에 저장된 매개 변수를 로드하는 Scripts의 PS1 폴더를 호출합니다.그래서 파워셸 ISE에서 나는 이 명령을 실행합니다.

.\Nico\Problem1\Solution1.PS1

솔루션 1 내부의 코드입니다.PS1은 다음과 같습니다.

# This is the path where my script is running
$path = split-path -parent $MyInvocation.MyCommand.Definition

# Change to root dir
cd "$path\..\.."

$script = ".\Script\Script1.PS1"

$parametro = "Problem1\ParameterForSolution1.config"
# Another set of parameter Script1.PS1 can receive for debuggin porpuose
$parametro +=' -verbose'

Invoke-Expression "$script $parametro"

검토를 위해 예를 제출합니다.이것이 제가 만든 도구에 있는 컨트롤러 스크립트의 일부 코드를 부르는 방법입니다.작업을 수행하는 스크립트도 매개 변수를 수락해야 하므로 이 예제에서는 매개 변수를 전달하는 방법을 보여 줍니다.호출 중인 스크립트가 컨트롤러 스크립트(호출하는 스크립트)와 동일한 디렉토리에 있다고 가정합니다.

[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string[]]
$Computername,

[Parameter(Mandatory = $true)]
[DateTime]
$StartTime,

[Parameter(Mandatory = $true)]
[DateTime]
$EndTime
)

$ZAEventLogDataSplat = @{
    "Computername" = $Computername
    "StartTime"    = $StartTime
    "EndTime"      = $EndTime
}

& "$PSScriptRoot\Get-ZAEventLogData.ps1" @ZAEventLogDataSplat

위는 3개의 매개 변수를 허용하는 컨트롤러 스크립트입니다.이들은 매개변수 블록에 정의되어 있습니다.그런 다음 컨트롤러 스크립트가 Get-Z라는 스크립트를 호출합니다.AeventLogData.ps1.예를 들어, 이 스크립트는 동일한 3개의 매개 변수도 허용합니다.컨트롤러 스크립트가 작업을 수행하는 스크립트를 호출할 때 컨트롤러 스크립트를 호출하고 매개 변수를 전달해야 합니다.위의 내용은 제가 스플래팅을 하는 방법을 보여줍니다.

저는 이것에 문제가 있었습니다.나는 영리한 어떤 것도 사용하지 않았습니다.$MyInvocation하지만 그것을 고칠 물건. 오른쪽 스립트파를마오른버쪽튼로클으릭고하경다우음여택는선하여을크우일스을를▁the▁by를 선택하면 ISE가 열립니다.edit그런 다음 ISE 내에서 두 번째 스크립트를 엽니다. 일반 .\script.ps1 구문을 사용하여 다른 스크립트에서 하나를 호출할 수 있습니다.ISE는 현재 폴더의 개념을 가지고 있으며 이렇게 열면 현재 폴더가 스크립트가 포함된 폴더로 설정됩니다.일반적으로 사용하는 다른 스크립트에서 한 스크립트를 호출할 때 .\script.ps1을 사용합니다. IMO에서 스크립트를 수정하는 것은 ISE에서 제대로 작동하도록 하기 위해 잘못된 것입니다.

다음 명령도 사용할 수 있습니다.

$Patch = Join-Path -Path $PSScriptRoot -ChildPath "\patch.ps1"<br>
Invoke-Expression "& `"$Patch`""

스크립트 내부에서 PowerShell 내장 스크립트를 어떻게 실행합니까?

다음과 같은 기본 제공 스크립트를 사용하는 방법

Get-Location
pwd
ls
dir
split-path
::etc...

사용자의 컴퓨터에서 실행되어 스크립트의 경로를 자동으로 확인합니다.

마찬가지로 스크립트 블록에 스크립트 이름만 입력하면 사용자 지정 스크립트를 실행할 수 있습니다.

::sid.ps1 is a PS script I made to find the SID of any user
::it takes one argument, that argument would be the username
echo $(sid.ps1 jowers)


(returns something like)> S-X-X-XXXXXXXX-XXXXXXXXXX-XXX-XXXX


$(sid.ps1 jowers).Replace("S","X")

(returns same as above but with X instead of S)

powershell 명령줄로 이동하여 다음을 입력합니다.

> $profile

그러면 앱을 열 때마다 PowerShell 명령줄에서 실행할 파일의 경로가 반환됩니다.

이렇게 될 것입니다.

C:\Users\jowers\OneDrive\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1

문서로 이동하여 Windows PowerShell 디렉터리가 이미 있는지 확인합니다.안 했어요, 그래서.

> cd \Users\jowers\Documents
> mkdir WindowsPowerShell
> cd WindowsPowerShell
> type file > Microsoft.PowerShellISE_profile.ps1

이제 PowerShell 앱을 열 때마다 실행되는 스크립트를 만들었습니다.

이 작업을 수행한 이유는 모든 사용자 지정 스크립트가 들어 있는 고유한 폴더를 추가할 수 있기 때문입니다.이 폴더를 생성하면 Mac/Linux가 스크립트를 보관하는 디렉터리의 이름을 따서 "Bin"으로 이름을 지정합니다.

> mkdir \Users\jowers\Bin

이제 해당 디렉토리를 우리의 디렉토리에 추가하기를 원합니다.$env:path우리가 앱을 열 때마다 변수가 있으니 다시 돌아가세요.WindowsPowerShell디렉터리 및

> start Microsoft.PowerShellISE_profile.ps1

그러면 이것을 추가합니다.

$env:path += ";\Users\jowers\Bin"

이제 "Bin" 디렉터리에 스크립트를 저장하는 한 셸에서 명령을 자동으로 찾습니다.

전원 셸을 다시 시작하면 처음 실행되는 스크립트 중 하나가 됩니다.

경로 변수에서 새 디렉터리를 보려면 다시 로드한 후 명령줄에서 이를 실행합니다.

> $env:Path

이제 명령줄에서 또는 다른 스크립트 내에서 스크립트를 호출할 수 있습니다.

$(customScript.ps1 arg1 arg2 ...)

보시다시피, 우리는 그들에게 전화해야 합니다..ps1우리가 그들을 위해 가명을 만들 때까지 연장.우리가 멋을 부리고 싶다면요.

위의 변수가 null이면 PowerShell ISE를 사용하고 있을 수 있습니다.이 경우 다음을 시도합니다.

if ($psISE)
{
    Split-Path -Path $psISE.CurrentFile.FullPath        
}
else
{
    $global:PSScriptRoot
}

토론을 확인하십시오.

언급URL : https://stackoverflow.com/questions/6816450/call-powershell-script-ps1-from-another-ps1-script-inside-powershell-ise

반응형