繁体   English   中英

如果您不知道要运行的位置,如何运行 powershell 脚本?

[英]How can you run a powershell script if you do not know the location is will be run from?

我是powershell的新手,所以这可能只是我不理解某些东西。

我正在 powershell 中编写一个工具,并且该工具在 c:\Users\Documents\WindowsPowerShell\Modules 中工作。

我想要的是能够将该工具复制到 U 盘并从 U 盘运行它。

如果该工具不在 PSModulePath 环境变量路径中,如何让该工具运行?

或者如何添加添加到 PSModulePath 路径的 U 盘?

如果您希望您的脚本是可移植的,您还必须随身携带相关模块。 但是,在您的脚本中,您可以确保将 USB 上模块父目录的完整路径添加到PSModulePath作为进程级环境变量:

$portableModuleDirectory = [System.IO.DirectoryInfo]'./relative/path/to/dependent/module'
$env:PSModulePath += ";$(Split-Path -Parent $portableModuleDirectory.FullName)"
Import-Module ModuleName

然而,这很麻烦。 这里最好的解决方案是托管您自己的内部 nuget 提要以将您的包推送到,因此如果您无法将模块上传到公共PowerShell 库(其中您应该托管自己的 feed/squid 代理以满足业务需求)。

谢谢您的帮助。 我有一个解决方案,它通过将以下内容放在 .ps1 脚本中并使用它来导入依赖模块并调用第一个函数。

#find local directory 
$LocalDir = Split-Path $MyInvocation.MyCommand.Path -Parent

#prove correct directory found.
Write-Host "Starting module load: $($MyInvocation.MyCommand) in directory = $LocalDir"
#load modules
Import-Module $LocalDir/Module –Force

#call first function
firstfunction

我无法让$PSScriptRoot工作,但Split-Path $MyInvocation.MyCommand.Path –Parent代码的优势在于它也适用于 ISE。 然后我将依赖模块放在 .ps1 脚本下面的目录中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM