简体   繁体   English

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

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

I am new to powershell so this may just be me not understanding something.我是powershell的新手,所以这可能只是我不理解某些东西。

I am writing a tool in powershell and have the tool working in c:\Users\Documents\WindowsPowerShell\Modules.我正在 powershell 中编写一个工具,并且该工具在 c:\Users\Documents\WindowsPowerShell\Modules 中工作。

What I would like is the ability to copy the tool to a USB stick and run it from the USB stick.我想要的是能够将该工具复制到 U 盘并从 U 盘运行它。

How can I get the tool to run if its not in the PSModulePath environment variable path?如果该工具不在 PSModulePath 环境变量路径中,如何让该工具运行?

Or how can I add the USB stick added to the PSModulePath path?或者如何添加添加到 PSModulePath 路径的 U 盘?

If you want your script to be portable, you will have to carry around the dependent module with you as well.如果您希望您的脚本是可移植的,您还必须随身携带相关模块。 However, in your script, you can make sure to add the full path to the module's parent directory on your USB to the PSModulePath as a process-level environment variable:但是,在您的脚本中,您可以确保将 USB 上模块父目录的完整路径添加到PSModulePath作为进程级环境变量:

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

However, this is cumbersome to have to do.然而,这很麻烦。 The best solution here would be to host your own internal nuget feed to push your package to, so you can install the module on any machine you need it on from your network, if you can't upload it to the public PowerShell Gallery (which you should host your own feed/squid proxy for business needs).这里最好的解决方案是托管您自己的内部 nuget 提要以将您的包推送到,因此如果您无法将模块上传到公共PowerShell 库(其中您应该托管自己的 feed/squid 代理以满足业务需求)。

Thanks for the help.谢谢您的帮助。 I have a solution that works by placing the following in a .ps1 script and using that to import the dependent modules and call the first function.我有一个解决方案,它通过将以下内容放在 .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

I could not get $PSScriptRoot to work but the Split-Path $MyInvocation.MyCommand.Path –Parent code has the advantage in that it also works in ISE.我无法让$PSScriptRoot工作,但Split-Path $MyInvocation.MyCommand.Path –Parent代码的优势在于它也适用于 ISE。 I then placed the dependent modules in directories below the .ps1 script.然后我将依赖模块放在 .ps1 脚本下面的目录中。

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

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