打开 Powershell 时运行 Powershell 脚本

use*_*993 19 powershell

运行 Powershell 时是否可以运行 Powershell 脚本?如在,双击 Powershell 图标并打开窗口。某处是否有某种类型的“自动运行”设置?

小智 28

有一个在 ps 启动时运行的 PowerShell 脚本(如果存在)。此脚本的文件规范位于变量中$profile

您可以使用 PowerShell 命令检查此脚本文件是否存在,如果不存在则创建它,并使用记事本编辑它。这是操作指南

请注意,在最近的(~2020 及更高版本)中,PowerShell 将不再$profile默认运行未签名的脚本(甚至不会!)。如果您只是按照操作指南中的旧说明进行操作,则当您打开新的 PowerShell 时,您将看到如下错误消息:

. : File C:\[..]\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 cannot be loaded
because running scripts is disabled on this system. For more information,
see about_Execution_Policies at
https:/go.microsoft.com/fwlink/?LinkID=135170.
Run Code Online (Sandbox Code Playgroud)

签署一次您的个人资料——更不用说每次更改它时——可能是不现实的,因此您必须更改执行策略以允许它。

为此,您可以:

  1. 以管理员身份运行以下命令:

    Set-ExecutionPolicy RemoteSigned -Scope LocalMachine

  2. 或者,使用 RegEdit 进行修改Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell,添加具有名称ExecutionPolicy和值的新 REG_SZ RemoteSigned

两者具有完全相同的效果,并且会在会话中持续存在。

RemoteSigned策略要求对从其他地方下载的脚本进行签名,但您在机器上本地创建的脚本(例如$profile)无需签名即可运行。(您也可以将策略设置Unrestricted为启用未签名的下载脚本,但这不是推荐的安全做法。)

  • 这是[另一个答案](/sf/answers/4515788441/),它解释了为什么“RemoteSigned”通常可以安全使用。另外,我必须使用“CurrentUser”而不是“LocalMachine”才能使其正常工作。 (2认同)

小智 13

输入以下命令:

New-item –type file –force $profile
Run Code Online (Sandbox Code Playgroud)

Microsoft.PowerShell_profile.ps1将为C:\Users\<username>\Documents\WindowsPowerShell\PowerShell 5 及更早版本或C:\Users\<username>\Documents\PowerShell\PowerShell 6 Core创建一个文件(将自动创建此文件夹)。

然后编辑此文件,您可以添加个性化的 PowerShell 功能或加载模块或管理单元...

现在,当您运行 powershell 控制台时,Microsoft.PowerShell_profile.ps1将被触发。