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

2024-03-29 14:33:30 发布

您现在位置:Python中文网/ 问答频道 /正文

D:\NoName\testfolder1\test1.ps1

function restapi {
    Write-Host "Initiating Rest Call"
    $test_value = "1"
}

D:\NoName\Testfolder1\testfolder2\test2.ps1

Invoke-Expression -Command D:\NoName\testfolder1\test1.ps1
function Invoke-Rest {
    restapi
    Write-Host "Invoking rest call and value of test is $test_value"    
}

如何调用/导入test1.ps1文件而不给出完整路径,就像我们在Python中所做的那样:

import testfolder1
from .testfolder1 import test1

Tags: testimportrestrestapihostvaluefunctioncall
1条回答
网友
1楼 · 发布于 2024-03-29 14:33:30

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

  1. Module import(通过^{})使用模块名(如果模块位于$env:PSModulePath):

    Import-Module BitsTransfer
    

    或使用完整/相对路径:

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

    . '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"    
}

请注意,automatic variable$PSScriptRoot在PowerShell v3之前不可用。在早期版本中,您需要自己确定目录,如下所示:

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

相关问题 更多 >