本文介绍了如何为 Powershell 配置启动/配置脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在每次启动 PowerShell 时定义一组自定义别名/变量以供使用.我正在寻找 .bashrc 文件的 PowerShell 替代方案.

我曾尝试将名为 Profile.ps1 的文件放在主目录中,但它从未运行.我需要做什么才能运行此文件?

我使用的是 Windows 10.

解决方案

我会先阅读 Microsoft 的文档 about_Profiles.我已链接到文档的 5.1 版本,因为这可能是您在 Windows 10 上拥有的内容,但我怀疑它在不同版本之间发生了很大变化.它包括有关如何实际创建文件的说明以及有关何时运行的详细信息.

对于您的用例,您可能希望在会话中执行以下操作:

if (!(Test-Path -Path $PROFILE)) {New-Item -ItemType File -Path $PROFILE -Force}

这将生成配置文件.然后一旦生成,您可以直接使用记事本打开它,并使用相同的示例:

记事本 $PROFILE

你可以用你最喜欢的编辑器代替记事本.VSCode 例如:

code $PROFILE

您也可以通过在 shell 中输入 $PROFILE 来获取您的配置文件的路径,它会输出它,然后使用该信息从您喜欢的编辑器导航到它.

根据文档:

PowerShell 配置文件是在 PowerShell 启动时运行的脚本.

比这更复杂,因为文档解释了多个配置文件,但对于您的故事来说,它已经足够准确了.

您也可以随时'dotsource' 您的配置文件,通过执行以下操作使其手动运行:

.$个人资料

但是,您应该注意,之前由您的配置文件调用定义的对象可能不会被删除.因此,在开发您的个人资料(这是一项有用的技术)时,请务必仅通过打开一个全新的会话来信任它在运行时的行为.

I am looking to define a set of custom aliases/variables for use every time I launch PowerShell. I am looking for the PowerShell alternative to the .bashrc file.

I have tried putting a file named Profile.ps1 in the home directory, but it never runs. What do I need to do to get this file to run?

I am using Windows 10.

解决方案

I'd start by reading through Microsoft's documentation about_Profiles. I've linked to the 5.1 version of the documentation since that's likely what you have on Windows 10, though I doubt it has changed much from version to version. It includes instructions on how to actually create the file and details about when it runs.

For your use case, you probably want to do the following from your session:

if (!(Test-Path -Path $PROFILE)) {
  New-Item -ItemType File -Path $PROFILE -Force
}

which will generate the profile. Then once that is generated you can open it with notepad directly with the same example from there:

notepad $PROFILE

You can substitute your favorite editor for notepad. VSCode for instance would be:

code $PROFILE

You can also just get the path to the your profile by simply typing $PROFILE into the shell and it will output it, and then use that information to navigate to it from your favorite editor.

Per the documentation:

It's more complicated than that since there are multiple profile files as the documentation explains, but for your story it's accurate enough.

You can always also 'dotsource' your profile to make it run manually by executing:

. $Profile

However you should note that objects previously defined by prior invocations of your profile might not be removed. So while developing your profile that's a useful technique, be sure to only trust how it behaves when run by opening a completely new session.

这篇关于如何为 Powershell 配置启动/配置脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 00:59