programing

현재 실행 중인 PowerShell 파일을 가져오려면 어떻게 해야 합니까?

golfzon 2023. 4. 9. 22:37
반응형

현재 실행 중인 PowerShell 파일을 가져오려면 어떻게 해야 합니까?

1.0 PowerShell 1.0
PowerShell을 사용합니다.요, 이렇게.

powershell.exe .\myfile.ps1

문자열 ".\myfile.ps1"(또는 그 비슷한 것)을 원합니다.편집: "myfile.ps1"이 좋습니다.
은은생 각각?

PowerShell 5용으로 업데이트된 다양한 답변을 여기에 요약했습니다.

  • 3 PowerShell 3을 하십시오.$PSCommandPath

  • 이전 버전과의 호환성을 원할 경우 다음과 같이 심을 삽입합니다.

    if ($PSCommandPath -eq $null) { function GetPSCommandPath() { return $MyInvocation.PSCommandPath; } $PSCommandPath = GetPSCommandPath }

    하면 더해져요.$PSCommandPath직직아면면면면 면

    는 임의의 장소 또는 )에서 할 수 , "상위 수준 또는 함수 내부에서 실행할 수 .$PSCommandPathvariable은 통상적인 범위 지정 규칙에 따릅니다(예를 들어, 함수에 심을 넣으면 변수는 해당 함수에 대해서만 범위가 지정됩니다).

세부 사항

이 을 쓴 을 보여주기 .$PSCommandPath

function PSCommandPath() { return $PSCommandPath }
function ScriptName() { return $MyInvocation.ScriptName }
function MyCommandName() { return $MyInvocation.MyCommand.Name }
function MyCommandDefinition() {
    # Begin of MyCommandDefinition()
    # Note: ouput of this script shows the contents of this function, not the execution result
    return $MyInvocation.MyCommand.Definition
    # End of MyCommandDefinition()
}
function MyInvocationPSCommandPath() { return $MyInvocation.PSCommandPath }

Write-Host ""
Write-Host "PSVersion: $($PSVersionTable.PSVersion)"
Write-Host ""
Write-Host "`$PSCommandPath:"
Write-Host " *   Direct: $PSCommandPath"
Write-Host " * Function: $(PSCommandPath)"
Write-Host ""
Write-Host "`$MyInvocation.ScriptName:"
Write-Host " *   Direct: $($MyInvocation.ScriptName)"
Write-Host " * Function: $(ScriptName)"
Write-Host ""
Write-Host "`$MyInvocation.MyCommand.Name:"
Write-Host " *   Direct: $($MyInvocation.MyCommand.Name)"
Write-Host " * Function: $(MyCommandName)"
Write-Host ""
Write-Host "`$MyInvocation.MyCommand.Definition:"
Write-Host " *   Direct: $($MyInvocation.MyCommand.Definition)"
Write-Host " * Function: $(MyCommandDefinition)"
Write-Host ""
Write-Host "`$MyInvocation.PSCommandPath:"
Write-Host " *   Direct: $($MyInvocation.PSCommandPath)"
Write-Host " * Function: $(MyInvocationPSCommandPath)"
Write-Host ""

출력:

PS C:\> .\Test\test.ps1

PSVersion: 5.1.19035.1

$PSCommandPath:
 *   Direct: C:\Test\test.ps1
 * Function: C:\Test\test.ps1

$MyInvocation.ScriptName:
 *   Direct:
 * Function: C:\Test\test.ps1

$MyInvocation.MyCommand.Name:
 *   Direct: test.ps1
 * Function: MyCommandName

$MyInvocation.MyCommand.Definition:
 *   Direct: C:\Test\test.ps1
 * Function:
    # Begin of MyCommandDefinition()
    # Note this is the contents of the MyCommandDefinition() function, not the execution results
    return $MyInvocation.MyCommand.Definition;
    # End of MyCommandDefinition()


$MyInvocation.PSCommandPath:
 *   Direct:
 * Function: C:\Test\test.ps1

주의:

  • ★★★부터 실행C:\, 스크립트는 '''입니다C:\Test\test.ps1.
  • 전달된 호출 경로를 알려주는 메서드는 없습니다..\Test\test.ps1)
  • $PSCommandPath 있는이지만 PowerShell 3에서되었습니다.
  • 3 이전 버전에서는 함수 내부와 외부에서 모두 사용할 수 있는 단일 메서드는 없습니다.

대부분의 경우 현재 답변이 맞지만 정답을 제공하지 못할 수 있습니다.스크립트 함수 내에서 를 사용하는 경우:

$MyInvocation.MyCommand.Name 

스크립트 이름 대신 함수 이름을 반환합니다.

function test {
    $MyInvocation.MyCommand.Name
}

스크립트의 이름이 어떻게 지정되든 "테스트"가 표시됩니다.스크립트명을 취득하기 위한 올바른 명령어는 항상 다음과 같습니다.

$MyInvocation.ScriptName

실행 중인 스크립트의 전체 경로를 반환합니다.스크립트 파일 이름만 필요한 경우 이 코드보다 도움이 됩니다.

split-path $MyInvocation.PSCommandPath -Leaf

(풀 패스가 아닌) 파일명만을 사용하는 경우는, 다음과 같이 합니다.

$ScriptName = $MyInvocation.MyCommand.Name

다음을 시도합니다.

$path =  $MyInvocation.MyCommand.Definition 

이렇게 하면 입력한 실제 경로가 제공되지 않을 수 있지만 파일에 대한 올바른 경로가 제공됩니다.

주의: 다른 것과 달리$PSScriptRoot ★★★★★★★★★★★★★★★★★」$PSCommandPath '자동변수',PSScriptRoot ★★★★★★★★★★★★★★★★★」PSCommandPath$MyInvocation자동 변수에는 현재 스크립트가 아닌 호출자 또는 호출 스크립트에 대한 정보가 포함됩니다.

예.

PS C:\Users\S_ms\OneDrive\Documents> C:\Users\SP_ms\OneDrive\Documents\DPM ...
=!C:\Users\S_ms\OneDrive\Documents\DPM.ps1

서...어디에DPM.ps1

Write-Host ("="+($MyInvocation.PSCommandPath)+"!"+$PSCommandPath)

스크립트가 실행되고 있는 현재의 디렉토리를 찾고 있는 경우는, 다음과 같이 시험할 수 있습니다.

$fullPathIncFileName = $MyInvocation.MyCommand.Definition
$currentScriptName = $MyInvocation.MyCommand.Name
$currentExecutingPath = $fullPathIncFileName.Replace($currentScriptName, "")

Write-Host $currentExecutingPath

이전 응답에서 설명한 바와 같이 "$MyInvocation"을 사용하면 범위 지정 문제가 발생할 수 있으며 일관된 데이터(반환값과 직접 액세스 값)를 제공할 수 없습니다.범위(메인 또는 후속/내포함수 호출)에 관계없이 스크립트 경로, 이름, 팜, 명령줄 등의 스크립트 정보를 얻는 가장 일관된 방법은 "MyInvocation"에서 "Get-Variable"을 사용하는 것입니다.

# Get the MyInvocation variable at script level
# Can be done anywhere within a script
$ScriptInvocation = (Get-Variable MyInvocation -Scope Script).Value

# Get the full path to the script
$ScriptPath = $ScriptInvocation.MyCommand.Path

# Get the directory of the script
$ScriptDirectory = Split-Path $ScriptPath

# Get the script name
# Yes, could get via Split-Path, but this is "simpler" since this is the default return value
$ScriptName = $ScriptInvocation.MyCommand.Name

# Get the invocation path (relative to $PWD)
# @GregMac, this addresses your second point
$InvocationPath = ScriptInvocation.InvocationName

따라서 $PSCommandPath와 동일한 정보를 얻을 수 있지만, 이 거래에서는 훨씬 더 많은 정보를 얻을 수 있습니다.잘 모르겠습니다만, 「Get-Variable(Get-Variable)」은 PS3까지는 이용할 수 없었던 것 같기 때문에, 정말로 오래된(업데이트되지 않은) 시스템에는 그다지 도움이 되지 않습니다.

「-Scope」를 사용하면, 호출 함수의 이름등을 취득할 수 있기 때문에, 몇개의 흥미로운 측면도 있습니다.0=전류, 1=부모 등

이게 도움이 됐으면 좋겠네요.

레퍼런스, https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-variable

변수 $MyInvocation의 범위를 설정함으로써 더 나은 방법이 있다고 생각합니다.마이 커맨드경로:

ex> $script:MyInvocation.마이 커맨드이름.

이 메서드는 호출의 모든 상황에서 작동합니다.

Somescript.ps1

function printme () {
    "In function:"
    ( "MyInvocation.ScriptName: " + [string]($MyInvocation.ScriptName) )
    ( "script:MyInvocation.MyCommand.Name: " + [string]($script:MyInvocation.MyCommand.Name) )
    ( "MyInvocation.MyCommand.Name: " + [string]($MyInvocation.MyCommand.Name) )
}
"Main:"
( "MyInvocation.ScriptName: " + [string]($MyInvocation.ScriptName) )
( "script:MyInvocation.MyCommand.Name: " + [string]($script:MyInvocation.MyCommand.Name) )
( "MyInvocation.MyCommand.Name: " + [string]($MyInvocation.MyCommand.Name) )
" "
printme
exit

출력:

PS> powershell C:\temp\test.ps1
Main:
MyInvocation.ScriptName:
script:MyInvocation.MyCommand.Name: test.ps1
MyInvocation.MyCommand.Name: test.ps1

In function:
MyInvocation.ScriptName: C:\temp\test.ps1
script:MyInvocation.MyCommand.Name: test.ps1
MyInvocation.MyCommand.Name: printme

Main에서 호출해도 위에서 수락한 응답은 값을 반환하지 않습니다.또한, 상기 승인된 답변은 질문이 스크립트 이름만 요구했을 때 풀 경로를 반환하는 것에 주의해 주세요.범위 변수는 모든 위치에서 작동합니다.

또, 풀 패스가 필요한 경우는, 다음의 번호로 문의해 주세요.

$script:MyInvocation.MyCommand.Path

기본적으로 권장하는 @gregmac의 (뛰어난 상세) 답변에 대한 간단한 데모$PSCommandPath이 명령어는 Powershell 3.0 이후가 사용되는 현재 실행 중인 스크립트를 반환하는 유일한 신뢰성 있는 명령어입니다.

여기에서는 전체 경로 또는 파일 이름만 반환하는 것을 보여 줍니다.

Test.ps1:

'Direct:'
$PSCommandPath  # Full Path 
Split-Path -Path $PSCommandPath -Leaf  # File Name only

function main () {
  ''
  'Within a function:'
  $PSCommandPath
  Split-Path -Path $PSCommandPath -Leaf
}

main

출력:

PS> .\Test.ps1
Direct:
C:\Users\John\Documents\Sda\Code\Windows\PowerShell\Apps\xBankStatementRename\Test.ps1
Test.ps1

Within a function:
C:\Users\John\Documents\Sda\Code\Windows\PowerShell\Apps\xBankStatementRename\Test.ps1
Test.ps1

PS 2와 PS 4에서 다음 스크립트를 사용하여 테스트를 실시하여 같은 결과를 얻었다.이게 사람들에게 도움이 됐으면 좋겠어요.

$PSVersionTable.PSVersion
function PSscript {
  $PSscript = Get-Item $MyInvocation.ScriptName
  Return $PSscript
}
""
$PSscript = PSscript
$PSscript.FullName
$PSscript.Name
$PSscript.BaseName
$PSscript.Extension
$PSscript.DirectoryName

""
$PSscript = Get-Item $MyInvocation.InvocationName
$PSscript.FullName
$PSscript.Name
$PSscript.BaseName
$PSscript.Extension
$PSscript.DirectoryName

결과 -

Major  Minor  Build  Revision
-----  -----  -----  --------
4      0      -1     -1      

C:\PSscripts\Untitled1.ps1
Untitled1.ps1
Untitled1
.ps1
C:\PSscripts

C:\PSscripts\Untitled1.ps1
Untitled1.ps1
Untitled1
.ps1
C:\PSscripts

이는 대부분의 powershell 버전에서 작동합니다.

(& { $MyInvocation.ScriptName; })

이는 스케줄링된 작업에 대해 작동할 수 있습니다.

Get-ScheduledJob |? Name -Match 'JOBNAMETAG' |% Command

언급URL : https://stackoverflow.com/questions/817198/how-can-i-get-the-current-powershell-executing-file

반응형