打开 Powershell 时运行 Powershell 脚本

打开 Powershell 时运行 Powershell 脚本

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

答案1

如果存在,则有一个在 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.

对您的个人资料进行一次签名 - 更不用说每次更改它时都进行签名 - 可能不太现实,因此您必须更改执行策略以允许它。

为此,您可以:

  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以启用未签名的下载脚本,但这不是推荐的安全做法。)

答案2

键入以下命令:

New-item –type file –force $profile

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

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

现在,当你运行你的 powershell 控制台时,Microsoft.PowerShell_profile.ps1就会被触发。

答案3

要在 PowerShell 会话启动时运行任意脚本,请使用以下命令:

PowerShell -NoExit -File PathToScript.ps1

答案4

更新默认的 $Profile 变量编辑默认的 .PS1 文件(如果不存在,则创建它)将脚本添加到 .PS1 文件

相关内容