如何配置Windows以更轻松地使用PowerShell脚本

Header

Windows and PowerShell have built-in security features and default configurations intended to prevent end-users from accidentally launching scripts in the course of their daily activities. However, if your daily activities routinely involve writing and running your own PowerShell scripts, this can be more of a nuisance than a benefit. Here, we’ll show you how to work around these features without completely compromising on security.

Windows和PowerShell具有内置的安全功能和默认配置,旨在防止最终用户在日常活动过程中意外启动脚本。 但是,如果您的日常活动通常涉及编写和运行自己的PowerShell脚本,那么这可能更多的是麻烦而不是好处。 在这里,我们将向您展示如何解决这些功能而又不完全损害安全性。

Windows和PowerShell如何以及为什么阻止脚本执行。 (How and why Windows & PowerShell prevent script execution.)

PowerShell is effectively the command shell and scripting language that’s intended to replace CMD and batch scripts on Windows systems. As such, a PowerShell script can pretty much be configured to do anything you could do manually from the command line. That equates to making practically any change possible on your system, up to the restrictions in place on your user account. So, if you could just double-click a PowerShell script and run it with full Administrator privileges, a simple one-liner like this could really wreck your day:

PowerShell有效地是命令外壳和脚本语言,旨在替换Windows系统上的CMD和批处理脚本。 因此,PowerShell脚本几乎可以配置为执行您可以从命令行手动执行的任何操作。 这实际上等于使您的系统上几乎可以进行任何更改,直到您的用户帐户受到限制为止。 因此,如果您只需双击一个PowerShell脚本并以完全的管理员权限运行它,那么像这样的简单单行便会破坏您的一天:

Get-ChildItem "$env:SystemDrive\" -Recurse -ErrorAction SilentlyContinue | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
Get-ChildItem "$env:SystemDrive\" -Recurse -ErrorAction SilentlyContinue | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue

DO NOT run the above command!

不要运行以上命令!

That simply goes through the file system and deletes whatever it can. Interestingly, this may not render the system inoperable as quickly as you might think – even when run from an elevated session. But if someone calls you after running this script, because they suddenly can’t find their files or run some programs, “turning it off and on again” will probably just lead them into Windows Startup Repair where they’re going to be told there’s nothing that can be done to fix the problem. What could be worse is, instead of getting a script that just trashes their file system, your friend might be tricked into running one that downloads and installs a keylogger or remote access service. Then, instead of asking you questions about Startup Repair, they may end up asking the police some questions about bank fraud!

这只是遍历文件系统并删除所有可能的内容。 有趣的是,即使在提升的会话中运行,这也可能不会使系统无法像您想象的那样快速运行。 但是,如果有人在运行此脚本后打电话给您,因为他们突然找不到文件或运行某些程序,“将其关闭并再次打开”可能只会导致他们进入Windows启动修复,并被告知存在无法解决此问题。 更糟糕的是,您的朋友可能会被骗去运行一个下载并安装键盘记录器或远程访问服务的脚本,而不是仅仅浪费他们的文件系统的脚本。 然后,他们可能没有向您询问有关启动修复的问题,而是最终向警察询问了有关银行欺诈的一些问题!

By now it should be obvious why certain things are needed to protect end-users from themselves, so to speak. But power users, system administrators, and other geeks are generally (though there are exceptions) a bit more wary of these threats, knowing how to spot and easily avoid them, and just want to get on with getting their work done. To do this, they’ll have to either disable or work around a few road blocks:

到现在为止,显而易见的是,为什么需要采取某些措施来保护最终用户免受自身侵害。 但是,高级用户,系统管理员和其他极客通常(尽管有例外)对这些威胁更加警惕,知道如何发现并轻松避免它们,并且只想继续完成工作。 为此,他们必须禁用或解决一些障碍:

  • PowerShell does not allow external script execution by default.The ExecutionPolicy setting in PowerShell prevents execution of external scripts by default in all versions of Windows. In some Windows versions, the default doesn’t allow script execution at all. We showed you how to change this setting in How to Allow the Execution of PowerShell Scripts on Windows 7, but we’ll cover it on a few levels here as well.

    默认情况下,PowerShell不允许外部脚本执行。 PowerShell中的ExecutionPolicy设置默认情况下在所有Windows版本中都阻止执行外部脚本。 在某些Windows版本中,默认设置根本不允许脚本执行。 我们在“ 如何在Windows 7上允许执行PowerShell脚本”中向您展示了如何更改此设置,但在这里还将在几个级别上进行介绍。

  • PowerShell is not associated to the .PS1 file extension by default.We brought this up initially in our PowerShell Geek School series. Windows sets the default action for .PS1 files to open them in Notepad, instead of sending them to the PowerShell command interpreter. This is to directly prevent accidental execution of malicious scripts when they’re simply double-clicked.

    默认情况下,PowerShell未与.PS1文件扩展名关联。 我们最初在PowerShell Geek School系列中提出了这一点。 Windows设置.PS1文件的默认操作,以在记事本中打开它们,而不是将其发送到PowerShell命令解释器。 这是为了直接防止恶意脚本在被双击时的意外执行。

  • Some PowerShell scripts won’t work without Administrator permissions.Even running with an Administrator-level account, you still need to get through User Account Control (UAC) to perform certain actions. For command-line tools, this can be a bit cumbersome to say the least. We don’t want to disable UAC, but it’s still nice when we can make it a bit easier to deal with.

    没有管理员权限,某些PowerShell脚本将无法工作。 即使使用管理员级别的帐户运行,您仍需要通过用户帐户控制(UAC)来执行某些操作。 至少对于命令行工具而言,这可能有点麻烦。 我们不想禁用UAC ,但是当我们可以使它更易于处理时,它仍然很不错。

These same issues are brought up in How to Use a Batch File to Make PowerShell Scripts Easier to Run, where we walk you through writing a batch file to temporarily get around them. Now, we’re going to show you how to set your system up with a more long-term solution. Bear in mind that you should not generally make these changes on systems that aren’t exclusively used by you – otherwise, you’re putting other users at higher risk of running into the same problems these features are intended to prevent.

如何使用批处理文件使PowerShell脚本更易于运行中也提出了同样的问题,在此我们将指导您编写批处理文件以暂时解决它们。 现在,我们将向您展示如何使用更长期的解决方案来设置系统。 请记住,通常不应该在非您独有的系统上进行这些更改–否则,您会使其他用户陷入这些功能旨在防止的相同问题的更高风险。

更改.PS1文件关联。 (Changing the .PS1 file association.)

The first, and perhaps foremost, annoyance to get around is the default association for .PS1 files. Associating these files to anything other than PowerShell.exe makes sense for preventing accidental execution of undesirable scripts. But, considering that PowerShell comes with an Integrated Scripting Environment (ISE) which is specifically designed for editing PowerShell scripts, why would we want to open .PS1 files in Notepad by default? Even if you’re not ready to fully switch to enabling double-click-to-run functionality, you’ll probably want to tweak these settings.

解决的第一个(也是最重要的)麻烦是.PS1文件的默认关联。 将这些文件与除PowerShell.exe以外的任何其他文件相关联,对于防止意外执行不需要的脚本很有意义。 但是,考虑到PowerShell带有专门用于编辑PowerShell脚本的集成脚本环境(ISE),为什么我们要默认在记事本中打开.PS1文件? 即使您还没有准备好完全切换为启用双击运行功能,也可能需要调整这些设置。

You could change the .PS1 file association to whatever program you want with the Default Programs control panel, but digging directly into the Registry will give you a bit more control over exactly how the files will be opened. This also lets you set or change additional options which are available in the context menu for .PS1 files. Don’t forget to make a backup of the registry before you do this!

您可以使用“ 默认程序”控制面板将.PS1文件关联更改为所需的任何程序,但是直接挖掘注册表将使您对文件的确切打开方式有了更多的控制。 这也使您可以设置或更改.PS1文件的上下文菜单中可用的其他选项。 在执行此操作之前,请不要忘记备份注册表

The registry settings controlling how PowerShell scripts are opened are stored in the following location:

控制如何打开PowerShell脚本的注册表设置存储在以下位置:

HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell

To explore these settings before we go about changing them, have a look at that key and its sub-keys with Regedit. The Shell key should just have one value, “(Default)”, which is set to “Open”. This is a pointer to the default action for double-clicking the file, which we’ll see in the sub-keys.

要在更改设置之前探索这些设置,请使用Regedit查看该键及其子键。 Shell键应该只有一个值“(默认)”,该值设置为“打开”。 这是指向双击文件的默认操作的指针,这将在子键中看到。

Expand the Shell key, and you’ll see three sub-keys. Each of these represents an action you can perform which is specific to PowerShell scripts.

展开Shell键,您将看到三个子键。 这些中的每一个都代表您可以执行的特定于PowerShell脚本的操作。

Shell-Key

You can expand each key to explore the values within, but they basically equate to the following defaults:

您可以展开每个键以探索其中的值,但是它们基本上等同于以下默认值:

  • 0 – Run with PowerShell. “Run with PowerShell” is actually the name of an option already in the context menu for PowerShell scripts. The text is just pulled from another location instead of using the key name like the others. And it’s still not the default double-click action.

    0 –使用PowerShell运行。 实际上,“使用PowerShell运行”是PowerShell脚本的上下文菜单中已经存在的选项的名称。 文本只是从另一个位置拉出,而不是像其他名称一样使用键名。 而且它仍然不是默认的双击操作。
  • Edit – Open in PowerShell ISE. This makes much more sense than Notepad, but you still have to right-click the .PS1 file to do it by default.

    编辑–在PowerShell ISE中打开。 这比记事本更有意义,但是默认情况下,您仍然必须右键单击.PS1文件才能执行此操作。
  • Open – Open in Notepad. Note that this key name is also the string stored in the “(Default)” value of the Shell key. This means double-clicking the file will “Open” it, and that action is normally set to use Notepad.

    打开–在记事本中打开。 请注意,此密钥名称也是存储在Shell密钥的“(默认)”值中的字符串。 这意味着双击文件将“打开”它,并且该操作通常设置为使用记事本。

If you want to stick with the pre-built command strings already available, you can just change the “(Default)” value in the Shell key to match the name of the key that matches what you want a double-click to do. This can easily be done from within Regedit, or you could use lessons learned from our tutorial on exploring the registry with PowerShell (plus a small PSDrive tweak) to begin building a reusable script that can configure your systems for you. The below commands must be run from an elevated PowerShell session, similar to running CMD as Administrator.

如果要保留已经可用的预构建命令字符串,则只需更改Shell键中的“(默认)”值以匹配与您要双击的键名匹配的键名。 这可以在Regedit内轻松完成,或者您可以使用从我们的教程中学习的经验教训, 以使用PowerShell探索注册表 (加上一个小的PSDrive调整)来开始构建可以为您配置系统的可重用脚本。 以下命令必须从提升的PowerShell会话中运行 ,类似于以Administrator身份运行CMD

First, you’ll want to configure a PSDrive for HKEY_CLASSES_ROOT since this isn’t set up by default. The command for this is:

首先,您要为HKEY_CLASSES_ROOT配置PSDrive,因为默认情况下未设置。 该命令是:

New-PSDrive HKCR Registry HKEY_CLASSES_ROOT
New-PSDrive HKCR Registry HKEY_CLASSES_ROOT

Now you can navigate and edit registry keys and values in HKEY_CLASSES_ROOT just like you would in the regular HKCU and HKLM PSDrives.

现在,您可以像在常规HKCU和HKLM PSDrives中一样在HKEY_CLASSES_ROOT中导航和编辑注册表项和值。

To configure double-clicking to launch PowerShell scripts directly:

要配置双击以直接启动PowerShell脚本,请执行以下操作:

Set-ItemProperty HKCR:\Microsoft.PowerShellScript.1\Shell '(Default)' 0

To configure double-clicking to open PowerShell scripts in the PowerShell ISE:

要配置双击以在PowerShell ISE中打开PowerShell脚本,请执行以下操作:

Set-ItemProperty HKCR:\Microsoft.PowerShellScript.1\Shell '(Default)' 'Edit'
Set-ItemProperty HKCR:\Microsoft.PowerShellScript.1\Shell '(Default)' 'Edit'

To restore the default value (sets double-click to open PowerShell scripts in Notepad):

恢复默认值(设置双击以在记事本中打开PowerShell脚本):

Set-ItemProperty HKCR:\Microsoft.PowerShellScript.1\Shell '(Default)' 'Open'

That’s just the basics of changing the default double-click action. We’ll go into more detail on customizing how PowerShell scripts are handled when they’re opened in PowerShell from Explorer in the next section. Keep in mind that scoping prevents PSDrives from persisting across sessions. So, you’ll probably want to include the New-PSDrive line at the start of any configuration script you build for this purpose, or add it to your PowerShell profile. Otherwise, you’ll need to run that bit manually before trying to make changes this way.

这只是更改默认双击动作的基础。 在下一部分中,我们将详细介绍如何自定义从PowerShell中打开PowerShell脚本时如何处理PowerShell脚本。 请记住, 范围界定可防止PSDrives在各个会话之间持续存在 。 因此,您可能需要在为此目的构建的任何配置脚本的开头都包含New-PSDrive行, 或将其添加到PowerShell配置文件中 。 否则,在尝试以这种方式进行更改之前,您需要手动运行该位。

更改PowerShell ExecutionPolicy设置。 (Changing the PowerShell ExecutionPolicy setting.)

PowerShell’s ExecutionPolicy is another layer of protection against execution of malicious scripts. There are multiple options for this, and a couple different ways it can be set. From most to least secure, the available options are:

PowerShell的ExecutionPolicy是防止执行恶意脚本的另一层保护。 有多个选项,可以通过几种不同的方式进行设置。 从最不安全到最不安全,可用的选项有:

  • Restricted – No scripts are allowed to run. (Default setting for most systems.) This will even prevent your profile script from running.

    受限–不允许运行脚本。 (大多数系统的默认设置。)这甚至会阻止您的配置文件脚本运行。
  • AllSigned – All scripts must be digitally signed by a trusted publisher to run without prompting the user. Scripts signed by publishers explicitly defined as untrusted, or scripts not digitally signed at all, will not run. PowerShell will prompt the user for confirmation if a script is signed by a publisher not yet defined as trusted or untrusted. If you haven’t digitally signed your profile script, and established trust in that signature, it won’t be able to run. Be careful which publishers you trust, as you can still end up running malicious scripts if you trust the wrong one.

    AllSigned –所有脚本必须由受信任的发布者进行数字签名才能运行,而不提示用户。 由明确定义为不受信任的发布者签名的脚本,或者根本没有经过数字签名的脚本将无法运行。 如果脚本是由尚未定义为受信任或不受信任的发布者签名的,PowerShell将提示用户进行确认。 如果您尚未对配置文件脚本进行数字签名,并且尚未对该签名建立信任关系,则它将无法运行。 请注意您信任的发布者,因为如果您信任错误的脚本,仍然可能最终运行恶意脚本。
  • RemoteSigned – For scripts downloaded from the Internet, this is effectively the same as “AllSigned”. However, scripts created locally or imported from sources other than the Internet are allowed to run without any confirmation prompt. Here, you’ll need to also be careful which digital signatures you trust but even be more careful of the non-signed scripts you choose to run. This is the highest security level under which you can have a working profile script without having to digitally sign it.

    RemoteSigned –对于从Internet下载的脚本,这实际上与“ AllSigned”相同。 但是,允许在本地创建或从Internet以外的其他源导入的脚本运行,而无需任何确认提示。 在这里,您还需要注意信任的数字签名,甚至要更加小心选择运行的非签名脚本。 这是最高的安全级别,在此级别下,您无需数字签名即可拥有有效的配置文件脚本。

  • Unrestricted – All scripts are allowed to run, but a confirmation prompt will be required for scripts from the Internet. From this point on, it’s entirely up to you to avoid running untrustworthy scripts.

    不受限制–允许运行所有脚本,但是来自Internet的脚本将需要确认提示。 从现在开始,完全由您决定避免运行不可信的脚本。
  • Bypass – Everything runs without a warning. Be careful with this one.

    绕过–一切运行都没有警告。 小心这一点。
  • Undefined – No policy is defined in the current scope. This is used to allow fall-back to policies defined in lower scopes (more details below) or to the OS defaults.

    未定义–当前范围内未定义任何策略。 这用于允许回退到在较低范围内定义的策略(在下面有更多详细信息)或操作系统默认设置。

As suggested by the description of Undefined, the above policies can be set in one or more of several scopes. You can use Get-ExecutionPolicy, with the -List parameter, to see all of the scopes and their current configuration.

如未定义的描述所建议,可以在多个范围中的一个或多个范围内设置以上策略。 您可以将Get-ExecutionPolicy与-List参数一起使用,以查看所有作用域及其当前配置。

ExecutionPolicy-List

The scopes are listed in precedence order, with the topmost defined scope overriding all others. If no policies are defined, the system falls back to its default setting (in most cases, this is Restricted).

这些作用域按优先级顺序列出,最上面定义的作用域将覆盖所有其他作用域。 如果未定义任何策略,则系统将退回到其默认设置(在大多数情况下,这是“受限”)。

  • MachinePolicy represents a Group Policy in effect at the Computer level. This is generally applied only in a domain, but can be done locally as well.

    MachinePolicy表示在计算机级别有效的组策略 。 这通常仅在域中应用 ,但也可以在本地完成。

  • UserPolicy represents a Group Policy in effect on the user. This is also typically only used in enterprise environments.

    UserPolicy表示对用户有效的组策略。 这通常也仅在企业环境中使用。
  • Process is a scope specific to this instance of PowerShell. Changes to the policy in this scope will not affect other running PowerShell processes, and will be ineffective after this session is terminated. This can be configured by the -ExecutionPolicy parameter when PowerShell is launched, or it can be set with the proper Set-ExecutionPolicy syntax from within the session.

    进程是特定于此PowerShell实例的作用域。 在此范围内对该策略的更改不会影响其他正在运行的PowerShell进程,并且在终止该会话后将无效。 可以在启动PowerShell时通过-ExecutionPolicy参数进行配置,也可以在会话中使用适当的Set-ExecutionPolicy语法进行设置。
  • CurrentUser is a scope that is configured in the local registry and applies to the user account used to launch PowerShell. This scope can be modified with Set-ExecutionPolicy.

    CurrentUser是在本地注册表中配置的范围,适用于用于启动PowerShell的用户帐户。 可以使用Set-ExecutionPolicy修改此范围。
  • LocalMachine is a scope configured in the local registry and applying to all users on the system. This is the default scope that is changed if Set-ExecutionPolicy is run without the -Scope parameter. As it applies to all users on the system, it can only be changed from an elevated session.

    LocalMachine是在本地注册表中配置的范围,适用于系统上的所有用户。 如果运行不带-Scope参数的Set-ExecutionPolicy,则这是默认范围。 由于它适用于系统上的所有用户,因此只能在提升的会话中进行更改。

Since this article is mainly about getting around security to facilitate usability, we’re just concerned about the lower three scopes. The MachinePolicy and UserPolicy settings are really useful only if you want to enforce a restrictive policy that isn’t so simply bypassed. By keeping our changes to the Process level or below, we can easily use whatever policy setting we deem appropriate for a given situation at any time.

由于本文主要是关于绕过安全性以促进可用性的,因此我们只关心下面的三个范围。 仅当您要强制执行并非如此简单绕过的限制性策略时,MachinePolicy和UserPolicy设置才真正有用。 通过将更改保持在“流程”级别或以下,我们可以随时轻松地使用我们认为适合给定情况的任何策略设置。

To retain some balance between security and usability, the policy shown in the screenshot is probably best. Setting the LocalMachine policy to Restricted generally prevents running scripts by anyone other than you. Of course, this can be bypassed by users who know what they’re doing without much effort. But it should keep any non-tech-savvy users from accidentally triggering something catastrophic in PowerShell. Having the CurrentUser (i.e.: you) set as Unrestricted allows you to manually execute scripts from the command line however you like, but does retain a reminder of caution for scripts downloaded from the Internet. The RemoteSigned setting at the Process level would need to be done in a shortcut to PowerShell.exe or (as we’ll do below) in the Registry values that control the behavior of PowerShell scripts. This will allow easy double-click-to-run functionality for any scripts you write, while putting up a stronger barrier against unintentional execution of (potentially malicious) scripts from external sources. We want to do this here since it’s much easier to accidentally double-click a script than it generally is to call it manually from an interactive session.

为了在安全性和可用性之间保持某种平衡,屏幕快照中显示的策略可能是最好的。 将LocalMachine策略设置为“受限”通常会阻止您以外的任何人运行脚本。 当然,知道自己正在做什么的用户可以绕开它,而无需付出太多努力。 但是,它应该防止任何不懂技术的用户意外触发PowerShell中的灾难性事件。 将CurrentUser(即:您)设置为Unrestricted(允许)可以使您根据自己的喜好从命令行手动执行脚本,但是确实提醒您从Internet下载的脚本。 进程级别的RemoteSigned设置需要在PowerShell.exe的快捷方式中完成,或在控制PowerShell脚本行为的注册表值中完成(如下所述)。 这将为您编写的任何脚本提供简单的双击运行功能,同时为防止意外地从外部源执行(可能是恶意的)脚本提供了更大的障碍。 我们要在此处执行此操作,因为意外地双击脚本要比从交互式会话中手动调用脚本容易得多。

To set the CurrentUser and LocalMachine policies as in the screenshot above, run the following commands from an elevated PowerShell session:

要像上面的屏幕快照中那样设置CurrentUser和LocalMachine策略,请从提升的PowerShell会话中运行以下命令:

Set-ExecutionPolicy Restricted
Set-ExecutionPolicy Unrestricted -Scope CurrentUser
Set-ExecutionPolicy Restricted
Set-ExecutionPolicy Unrestricted -Scope CurrentUser

To enforce the RemoteSigned policy on scripts run from Explorer, we’ll have to change a value inside of one of the registry keys we were looking at earlier. This is particularly important because, depending on your PowerShell or Windows version, the default configuration may be to bypass all ExecutionPolicy settings except AllSigned. To see what the current configuration is for your computer, you can run this command (making sure the HKCR PSDrive is mapped first):

要对从资源管理器运行的脚本实施RemoteSigned策略,我们必须更改我们之前查看的注册表项之一内的值。 这尤其重要,因为根据您的PowerShell或Windows版本,默认配置可能是绕过除AllSigned之外的所有ExecutionPolicy设置。 要查看计算机的当前配置,可以运行以下命令(确保先映射HKCR PSDrive):

Get-ItemProperty HKCR:\Microsoft.PowerShellScript.1\Shell\Command | Select-Object '(Default)'

Your default configuration will probably be one of the following two strings, or something fairly similar:

您的默认配置可能是以下两个字符串之一或相当类似的东西:

(Seen on Windows 7 SP1 x64, with PowerShell 2.0)

(在Windows 7 SP1 x64和PowerShell 2.0上看到)

"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-file" "%1"
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-file" "%1"

(Seen on Windows 8.1 x64, with PowerShell 4.0)

(在Windows 8.1 x64和PowerShell 4.0上看到)

"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & '%1'"

The first one isn’t too bad, as all it does is execute the script under the existing ExecutionPolicy settings. It could be made better, by enforcing tighter restrictions for a more accident-prone action, but this wasn’t originally intended to be triggered on a double-click anyway, and the default policy is usually Restricted after all. The second option, however, is a full bypass of whatever ExecutionPolicy you’re likely to have in place – even Restricted. Since the bypass will be applied in the Process scope, it only affects the sessions that are launched when scripts are run from Explorer. However, this means that you could end up launching scripts that you might otherwise expect (and want) your policy to forbid.

第一个还不错,因为它所做的只是在现有ExecutionPolicy设置下执行脚本。 通过对更容易发生事故的行为实施更严格的限制,可以使它变得更好,但这并不是最初旨在通过双击触发的,并且默认策略通常毕竟是“受限制的”。 但是,第二种选择是完全绕开您可能已经使用的任何ExecutionPolicy-甚至是Restricted。 由于绕过将应用于“流程”范围,因此它仅影响从资源管理器运行脚本时启动的会话。 但是,这意味着您可能最终启动了原本希望(并且希望)策略禁止的脚本。

To set the Process-level ExecutionPolicy for scripts launched from Explorer, in line with the screenshot above, you’ll need to modify the same registry value we just queried. You can do it manually in Regedit, by changing it to this:

要根据资源管理器启动的脚本设置进程级别的ExecutionPolicy,与上面的屏幕截图一致,您需要修改我们刚刚查询的相同注册表值。 您可以通过将其更改为以下内容,在Regedit中手动进行操作:

"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-ExecutionPolicy" "RemoteSigned" "-file" "%1"
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-ExecutionPolicy" "RemoteSigned" "-file" "%1"
Regedit-RemoteSigned

You can also change the setting from within PowerShell if you prefer. Remember to do this from an elevated session, with the HKCR PSDrive mapped.

如果愿意,还可以在PowerShell中更改设置。 切记在高级别的会议中使用HKCR PSDrive进行映射。

Set-ItemProperty HKCR:\Microsoft.PowerShellScript.1\Shell\Command '(Default)' '"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-ExecutionPolicy" "RemoteSigned" "-file" "%1"'

以管理员身份运行PowerShell脚本。 (Run PowerShell scripts as Administrator.)

Just as it is a bad idea to disable UAC entirely, it’s also bad security practice to run scripts or programs with elevated privileges unless you actually need them to perform operations which require Administrator access. So, building the UAC prompt into the default action for PowerShell scripts is not recommended. However, we can add a new context menu option to allow us to easily run scripts in elevated sessions when we need to. This is similar to the method used to add “Open with Notepad” to the context menu of all files – but here we’re only going to target PowerShell scripts. We’re also going to carry over some techniques used in the previous article, where we used a batch file instead of registry hacks to launch our PowerShell script.

就像完全禁用UAC是一个坏主意一样,以高特权运行脚本或程序也是安全的做法,除非您实际上需要它们执行需要管理员访问权限的操作。 因此,不建议将UAC提示符构建为PowerShell脚本的默认操作。 但是,我们可以添加一个新的上下文菜单选项,以使我们可以在需要时轻松地在提升的会话中运行脚本。 这类似于用于将“使用记事本打开”添加到所有文件的上下文菜单中的方法,但是这里我们仅针对PowerShell脚本。 我们还将继续使用上一篇文章中使用的一些技术,其中我们使用批处理文件而不是注册表黑客来启动PowerShell脚本。

To do this in Regedit, go back into the Shell key, at:

要在Regedit中执行此操作,请返回Shell键,位于:

HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell
HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell

In there, create a new sub-key. Call it “Run with PowerShell (Admin)”. Underneath that, create another sub-key called “Command”. Then, set the “(Default)” value under Command to this:

在其中创建一个新的子项。 将其称为“使用PowerShell运行(管理员)”。 在其下,创建另一个名为“ Command”的子项。 然后,在“命令”下将“(默认)”值设置为此:

"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" ""& {Start-Process PowerShell.exe -ArgumentList '-ExecutionPolicy RemoteSigned -File \"%1\"' -Verb RunAs}"
Regedit-RunAsAdmin

Doing the same in PowerShell will actually need three lines this time. One for each new key, and one to set the “(Default)” value for Command. Don’t forget elevation and the HKCR mapping.

这次实际上需要在PowerShell中进行三行操作。 每个新键一个,另一个为Command设置“(默认)”值。 不要忘记海拔和HKCR映射。

New-Item 'HKCR:\Microsoft.PowerShellScript.1\Shell\Run with PowerShell (Admin)'
New-Item 'HKCR:\Microsoft.PowerShellScript.1\Shell\Run with PowerShell (Admin)\Command'
Set-ItemProperty 'HKCR:\Microsoft.PowerShellScript.1\Shell\Run with PowerShell (Admin)\Command' '(Default)' '"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" ""& {Start-Process PowerShell.exe -ArgumentList ''-ExecutionPolicy RemoteSigned -File \"%1\"'' -Verb RunAs}"'
New-Item 'HKCR:\Microsoft.PowerShellScript.1\Shell\Run with PowerShell (Admin)'
New-Item 'HKCR:\Microsoft.PowerShellScript.1\Shell\Run with PowerShell (Admin)\Command'
Set-ItemProperty 'HKCR:\Microsoft.PowerShellScript.1\Shell\Run with PowerShell (Admin)\Command' '(Default)' '"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" ""& {Start-Process PowerShell.exe -ArgumentList ''-ExecutionPolicy RemoteSigned -File \"%1\"'' -Verb RunAs}"'

Also, pay careful attention to the differences between the string that’s being put in through PowerShell and the actual value that’s going into the Registry. Particularly, we’ve got to wrap the whole thing in single-quotes, and double-up on the internal single-quotes, in order to avoid errors in command parsing.

另外,请特别注意通过PowerShell放入的字符串与进入注册表的实际值之间的区别。 特别是,我们必须将整个内容包装在单引号中,并在内部单引号上加倍,以避免命令解析中的错误。

Now you should have a new context-menu entry for PowerShell scripts, called “Run with PowerShell (Admin)”.

现在,您应该为PowerShell脚本创建一个新的上下文菜单条目,称为“使用PowerShell运行(Admin)”。

右键点击

The new option will spawn two consecutive PowerShell instances. The first is just a launcher for the second, which uses Start-Process with the “-Verb RunAs” parameter to request elevation for the new session. From there, your script should be able to run with Administrator privileges after you click through the UAC prompt.

新选项将产生两个连续的PowerShell实例。 第一个只是第二个的启动器,它使用带有“ -Verb RunAs”参数的Start-Process来请求新会话的提升。 从那里,单击UAC提示符后,您的脚本应能够以管理员权限运行。

画龙点睛。 (Finishing touches.)

There’s just a couple more tweaks to this that can help make life a bit easier still. For one, how about getting rid of the Notepad function entirely? Simply copy the “(Default)” value from the Command key under Edit (below), into the same location under Open.

还有一些其他的调整可以使生活变得更轻松。 首先,如何完全摆脱记事本功能? 只需从“编辑”(如下)的Command键中将“(默认)”值复制到“打开”下的相同位置。

"C:\Windows\System32\WindowsPowerShell\v1.0\powershell_ise.exe" "%1"

Or, you can use this bit of PowerShell (with Admin & HKCR of course):

或者,您可以使用以下PowerShell(当然还有Admin和HKCR):

Set-ItemProperty HKCR:\Microsoft.PowerShellScript.1\Shell\Open\Command '(Default)' '"C:\Windows\System32\WindowsPowerShell\v1.0\powershell_ise.exe" "%1"'
Set-ItemProperty HKCR:\Microsoft.PowerShellScript.1\Shell\Open\Command '(Default)' '"C:\Windows\System32\WindowsPowerShell\v1.0\powershell_ise.exe" "%1"'

One more minor annoyance is the console’s habit of disappearing once a script is complete. When that happens, we don’t have any chance to review the script output for errors or other useful information. This can be taken care of by putting a pause at the end of each of your scripts, of course. Alternately, we can modify the “(Default)” values for our Command keys to include the “-NoExit” parameter. Below are the modified values.

另一个烦恼是控制台一旦脚本完成就消失的习惯。 发生这种情况时,我们没有任何机会查看脚本输出中的错误或其他有用信息。 当然,可以通过在每个脚本的末尾放置一个暂停来解决此问题。 或者,我们可以修改Command键的“(默认)”值以包括“ -NoExit”参数。 以下是修改后的值。

(Without Admin access)

(无管理员权限)

"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-NoExit" "-ExecutionPolicy" "RemoteSigned" "-file" "%1"

(With Admin access)

(具有管理员访问权限)

"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" ""& {Start-Process PowerShell.exe -ArgumentList '-NoExit -ExecutionPolicy RemoteSigned -File \"%1\"' -Verb RunAs}"
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" ""& {Start-Process PowerShell.exe -ArgumentList '-NoExit -ExecutionPolicy RemoteSigned -File \"%1\"' -Verb RunAs}"

And of course, we’ll give you those in PowerShell commands too. Last reminder: Elevation & HKCR!

当然,我们也会在PowerShell命令中为您提供这些功能。 最后提醒:高程和HKCR!

(Non-Admin)

(非管理员)

Set-ItemProperty HKCR:\Microsoft.PowerShellScript.1\Shell\Command '(Default)' '"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-NoExit" "-ExecutionPolicy" "RemoteSigned" "-file" "%1"'

(Admin)

(管理员)

Set-ItemProperty 'HKCR:\Microsoft.PowerShellScript.1\Shell\Run with PowerShell (Admin)\Command' '(Default)' '"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" ""& {Start-Process PowerShell.exe -ArgumentList ''-NoExit -ExecutionPolicy RemoteSigned -File \"%1\"'' -Verb RunAs}"'
Set-ItemProperty 'HKCR:\Microsoft.PowerShellScript.1\Shell\Run with PowerShell (Admin)\Command' '(Default)' '"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" ""& {Start-Process PowerShell.exe -ArgumentList ''-NoExit -ExecutionPolicy RemoteSigned -File \"%1\"'' -Verb RunAs}"'

兜风。 (Taking it for a spin.)

To test this out, we’re going to use a script that can show us the ExecutionPolicy settings in place and whether or not the script was launched with Administrator permissions. The script will be called “MyScript.ps1” and be stored in “D:\Script Lab” on our sample system. The code is below, for reference.

为了测试这一点,我们将使用一个脚本,该脚本可以向我们显示ExecutionPolicy设置,以及该脚本是否使用管理员权限启动。 该脚本将被称为“ MyScript.ps1”,并存储在示例系统的“ D:\ Script Lab”中。 该代码如下,以供参考。

if(([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{Write-Output 'Running as Administrator!'}
else
{Write-Output 'Running Limited!'}
Get-ExecutionPolicy -List

Using the “Run with PowerShell” action:

使用“使用PowerShell运行”操作:

Limited-ExecutionPolicy

Using the “Run with PowerShell (Admin)” action, after clicking through UAC:

在通过UAC单击之后,使用“使用PowerShell运行(管理员)”操作:

Admin-ExecutionPolicy

To demonstrate the ExecutionPolicy in action at the Process scope, we can make Windows think the file came from the Internet with this bit of PowerShell code:

为了演示Process作用域中的ExecutionPolicy,我们可以使用以下PowerShell代码使Windows认为该文件来自Internet:

Add-Content -Path 'D:\Script Lab\MyScript.ps1' -Value "[ZoneTransfer]`nZoneId=3" -Stream 'Zone.Identifier'
Add-Content -Path 'D:\Script Lab\MyScript.ps1' -Value "[ZoneTransfer]`nZoneId=3" -Stream 'Zone.Identifier'
远程签名错误

Fortunately, we had -NoExit enabled. Otherwise, that error would have just blinked on by, and we wouldn’t have known!

幸运的是,我们启用了-NoExit。 否则,该错误将一直闪烁,而我们将不知道!

The Zone.Identifier can be removed with this:

可以使用以下方法删除Zone.Identifier:

Clear-Content -Path 'D:\Script Lab\MyScript.ps1' -Stream 'Zone.Identifier'


Useful References:

有用的参考资料:

翻译自: https://www.howtogeek.com/204166/how-to-configure-windows-to-work-with-powershell-scripts-more-easily/

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值