Python 如何在不使用psm1和完整目录路径的情况下,将一个ps.1脚本函数、变量和类调用/使用到另一个ps.1文件?

Python 如何在不使用psm1和完整目录路径的情况下,将一个ps.1脚本函数、变量和类调用/使用到另一个ps.1文件?,python,powershell,Python,Powershell,D:\NoName\testfolder1\test1.ps1: 函数restapi{ 写入主机“启动Rest调用” $test\u value=“1” } D:\NoName\Testfolder1\testfolder2\test2.ps1: 调用表达式-命令D:\NoName\testfolder1\test1.ps1 函数调用Rest{ 雷斯塔皮 写入主机“调用rest调用,测试值为$test\u value” } 如何调用/导入test1.ps1文件而不提供完整路径,就像我们在Py

D:\NoName\testfolder1\test1.ps1

函数restapi{
写入主机“启动Rest调用”
$test\u value=“1”
}
D:\NoName\Testfolder1\testfolder2\test2.ps1

调用表达式-命令D:\NoName\testfolder1\test1.ps1 函数调用Rest{ 雷斯塔皮 写入主机“调用rest调用,测试值为$test\u value” } 如何调用/导入
test1.ps1
文件而不提供完整路径,就像我们在Python中所做的那样:

导入testfolder1
从.testfolder1导入test1

PowerShell基本上有两种导入机制:

  • (via)带有模块名称(如果模块位于
    $env:PSModulePath
    ):

    或使用完整/相对路径:

    Import-Module 'C:\some\folder\foo.psm1'
    Import-Module '.\subfolder\bar.psm1'
    
    . 'C:\some\folder\foo.ps1'
    . '.\subfolder\bar.ps1'
    
  • 常规PowerShell脚本,也包括完整或相对路径:

    Import-Module 'C:\some\folder\foo.psm1'
    Import-Module '.\subfolder\bar.psm1'
    
    . 'C:\some\folder\foo.ps1'
    . '.\subfolder\bar.ps1'
    
  • 在您的情况下,您可能需要后者:

    . "$PSScriptRoot\..\testfolder1\test1.ps1"
    function Invoke-Rest {
        restapi
        Write-Host "Invoking rest call and value of test is $test_value"    
    }
    
    请注意,
    $PSScriptRoot
    在PowerShell v3之前不可用。在早期版本中,您需要自己确定目录,如下所示:

    $scriptdir = Split-Path $MyInvocation.MyCommand.Path -Parent
    . "$scriptdir\..\testfolder1\test1.ps1"
    

    首先,您应该在第二个powershell中使用点源来调用第一个PS1的函数。其次,如果所有都是函数,那么您应该使用psm1(模块)。第三,在python中,如果您想这样做,那么将工作目录更改为ps1所在的目录。我不会说不好的问题,但研究得很差。欢迎来到SO。经过非常简洁的解释。我喜欢它