我正在Powershell ISE中处理一些脚本,我需要PS脚本根目录才能在Powershell和Powershell ISE中执行相同的操作。我做了下面的例子来说明区别。
调用方.ps1
if ($psISE)
{
$directory = Split-Path -Path $psISE.CurrentFile.FullPath
Write-Host "psISE : " $directory
}
else
{
$directory=$PSScriptRoot
Write-Host "not psISE : " $directory
}
write-host "---------- in dir Scripts --------------"
try {& "$directoryScriptsCalled.ps1"}
catch {"FAILED"}
调用.ps1
if ($psISE)
{
$directory = Split-Path -Path $psISE.CurrentFile.FullPath
Write-Host "psISE : " $directory
}
else
{
$directory=$PSScriptRoot
Write-Host "not psISE : " $directory
}
Powershell 的结果
PS C:> .ExampleCaller.ps1
not psISE : C:Example
---------- in dir Scripts --------------
not psISE : C:ExampleScripts
Powershell ISE 的结果
PS C:> C:ExampleCaller.ps1
psISE : C:Example
---------- in dir Scripts --------------
psISE : C:Example
首次发布在中的示例和相关问题:PowerShell PSScriptRoot为空
$PSScriptRoot在PowerShell ISE中工作,只要文件保存到磁盘即可。该文件可以使用F5运行,但不能使用F8。
示例代码演示的问题是psISE.CurrentFile.FullPath没有从Called.ps1文件更新。