且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从某个目录将所有函数加载到 PowerShell 中

更新时间:2023-11-10 22:29:28

将它们包含在您的 PowerShell 配置文件中,以便在您每次启动 PS 时自动加载它们.

查看 Windows PowerShell 配置文件详细了解在哪里可以找到您的配置文件脚本.

PS 将您的个人资料默认为您的我的文档"文件夹.我的是在网络驱动器上,所以无论我登录到哪里,PowerShell 都指向同一个配置文件文件夹.

Suppose you're a system administrator who uses PowerShell to manage a lot of things on his/her system(s).

You've probably written a lot of functions which do things you regularly need to check. However, if you have to move around a lot, use different machines a lot and so on, you'd have to re-enter all your functions again and again to be able to use them. I even have to do it every time I exit and restart PowerShell for some reason, as it won't remember the functions...

I've written a function that does this for me. I'm posting it here because I want to be certain it's foolproof. The function itself is stored in allFunctions.ps1, which is why I have it excluded in the code.

The basic idea is that you have one folder in which you store all your ps1 files which each include a function. In PowerShell, you go to that directory and then you enter:

. .\allFunctions.ps1

The contents of that script is this:

[string]$items = Get-ChildItem -Path . -Exclude allFunctions.ps1
$itemlist = $items.split(" ")
foreach($item in $itemlist)
{
    . $item
}

This script will first collect every file in your directory, meaning all non-ps1 files you might have in there too. allFunctions.ps1 will be excluded.

Then I split the long string based on the space, which is the common separator here. And then I run through it with a Foreach-loop, each time initializing the function into PowerShell.

Suppose you have over 100 functions and you never know which ones you'll need and which you won't? Why not enter them all instead of nitpicking?

So I'm wondering, what can go wrong here? I want this to be really safe, since I'm probably going to be using it a lot.

Include them in your PowerShell profile so they will load automatically every time you start PS.

Look at Windows PowerShell Profiles for more info about where to find your profile script.

PS defaults your profile to your "My Documents" folder. Mine is on a network drive, so anywhere I login, PowerShell points to the same profile folder.