从CMD或批处理文件调用时,是否可以在PowerShell脚本中获取调用者的目录?

时间:2017-09-01 16:39:21

标签: powershell

假设我在C:\source中的CMD中输入此内容:

powershell.exe Set-ExecutionPolicy RemoteSigned -File C:\test\test.ps1

test.ps1我尝试将C:\source作为目录而没有成功。

$script_folder = $PSScriptRoot
$myDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$myDir
$PSScriptRoot

$myDir$PSScriptRoot都会返回C:\test\而不是C:\source

3 个答案:

答案 0 :(得分:2)

您可以使用$PWD这是当前工作目录的自动变量。当您打开PowerShell时,它应该继续使用相同的工作目录。

来自about_automatic_variables

  

$ PWD

     

包含表示当前目录的完整路径的路径对象。

此外,MS-DOS是一个无法运行PowerShell的操作系统。这与cmd.exe /命令提示符不同。

答案 1 :(得分:1)

您使用的自动变量是有关脚本调用的信息。启动脚本启动命令的位置是环境的一部分。

$PWD包含有关当前工作目录的信息(对posix pwd命令的点头)。具体而言,$PWD.Path

根据about_automatic_variables page(或Get-Help about_automatic_variables)$PSScriptRoot$PSCommandPath,属于$MyInvocation

有关使用Split-Path -Path $($Global:$MyInvocation.MyCommand.Path)获取当前路径的示例,请参阅here

推荐测试脚本:

# TestInvocationAndPWDPaths.ps1
function Test-MyInvocation {
    $MyInvocation  
}
function Test-PWD {
    $PWD
}
'$MyInvocation from script:'
$MyInvocation
'$MyInvocation from function:'
Test-MyInvocation

'$PWD from script:'
$PWD
'$PWD from function'
Test-PWD

有趣的结果。从powershell控制台,ISE和命令提示符运行此命令将显示$ MyInvocation中的差异。

答案 2 :(得分:1)

$MyInvocation.PSScriptRoot 为您提供调用者脚本文件夹。 当调用者是命令行时,这将返回 $null。

您应该能够使用这两个事实。

只想补充一点,在 psm1 函数中使用 $pwd/get-location 是 powershell 中的一个普遍陷阱。 而是将完整路径作为参数注入。