简体   繁体   English

如何导入新的PowerShell cmdlet?

[英]How to import a new powershell cmdlet?

I have just downloaded the Register-TemporaryEvent cmdlet from http://poshcode.org/2205 and placed it in my powershell profile directory near the $profile script. 我刚从http://poshcode.org/2205下载了Register-TemporaryEvent cmdlet,并将其放在$profile脚本附近的powershell配置文件目录中。

How do I create a new command Register-TemporaryEvent which would be bound to this script? 如何创建一个新命令Register-TemporaryEvent ,它将绑定到此脚本?

Thanks. 谢谢。

With PowerShell, you can execute scripts as commands if they are placed in directories contained in the 'PATH' environment variable. 使用PowerShell,如果将脚本放在“PATH”环境变量中包含的目录中,则可以将脚本作为命令执行。 To see what directories are in the Path, you can use: 要查看Path中的目录,您可以使用:

$env:Path -split ';'| sort

You could modify the path permanently from Windows' System Properties to include the location of your scripts, or you could temporarily modify the path from within your profile or script. 您可以从Windows的“系统属性”中永久修改路径以包含脚本的位置,也可以从配置文件或脚本中临时修改路径。 In your particular case, you could add the following to your profile to add the profile directory to the path: 在您的特定情况下,您可以将以下内容添加到配置文件中,以将配置文件目录添加到路径中:

$ScriptRoot = Split-Path $SCRIPT:MyInvocation.MyCommand.Path

if(($env:Path -split ';') -notcontains $ScriptRoot) {
    $env:Path += ';' + $ScriptRoot
}

You can then run the command as: 然后,您可以运行以下命令:

PS >$timer = New-Object Timers.Timer
PS >Register-TemporaryEvent $timer Disposed { [Console]::Beep(100,100) }

Note: When tab completing, it will complete as Register-TemporaryEvent.ps1 , but you can remove the '.ps1' and it will still work. 注意:当选项卡完成时,它将作为Register-TemporaryEvent.ps1完成,但您可以删除'.ps1',它仍然可以工作。

You can get the content of the script file, enclose it in a function and invoke the code to create the function. 您可以获取脚本文件的内容,将其包含在函数中并调用代码来创建函数。

$sb = Get-Content .\script.ps1 | Out-String
Invoke-Expression "function Register-TemporaryEvent {`n $sb `n} "

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

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