有没有办法通过双击.ps1文件使PowerShell脚本工作?

问题描述 投票:100回答:17

我正在向我的团队分发PowerShell脚本。该脚本用于从Vsphere客户端获取IP地址,建立mstsc连接,并将其记录在共享文件中。

他们使用脚本的那一刻他们就知道了机器的IP地址。之后,他们总是倾向于直接使用mstsc而不是运行PowerShell脚本。 (因为他们正在使用mstsc我无法知道他们是否经常使用VM。)

主要是他们告诉我运行PowerShell并不简单。

我因他们的懒惰而生病。

有没有办法通过双击.ps1文件使PowerShell脚本工作?

powershell powershell-v2.0
17个回答
106
投票

创建一个类似于“目标”的快捷方式:

powershell.exe -command "& 'C:\A path with spaces\MyScript.ps1' -MyArguments blah"

3
投票

将一个简单的.cmd文件放在我的子文件夹中,并使用相同名称的.ps1文件,因此,例如,名为“foobar”的脚本将具有“foobar.ps1”和“foobar.cmd”。因此,要运行.ps1,我所要做的就是从资源管理器中单击.cmd文件或从命令提示符运行.cmd。我使用相同的基本名称,因为.cmd文件将使用自己的名称自动查找.ps1。

::====================================================================
:: Powershell script launcher
::=====================================================================
:MAIN
    @echo off
    for /f "tokens=*" %%p in ("%~p0") do set SCRIPT_PATH=%%p
    pushd "%SCRIPT_PATH%"

    powershell.exe -sta -c "& {.\%~n0.ps1 %*}"

    popd
    set SCRIPT_PATH=
    pause

pushd / popd允许您从命令提示符启动.cmd文件,而无需更改为脚本所在的特定目录。它将更改为脚本目录,然后在完成后返回到原始目录。

如果希望命令窗口在脚本完成时消失,也可以暂停。

如果我的.ps1脚本有参数,我使用.NET Forms提示GUI提示,但是如果我想要传递它们,也可以使脚本足够灵活地接受参数。这样我就可以从资源管理器中双击它,而不必知道参数的细节,因为它会通过列表框或其他形式询问我需要什么。


2
投票

这是基于KoZm0kNoT的答案。我修改它以跨驱动器工作。

@echo off
pushd "%~d0"
pushd "%~dp0"
powershell.exe -sta -c "& {.\%~n0.ps1 %*}"
popd
popd

如果用户的cwd位于不同的驱动器上,则需要两个pushd / popds。如果没有外部设置,带有脚本的驱动器上的cwd将丢失。


2
投票

这是我用来使用scrips默认运行的管理员:

Powershell.exe -Command "& {Start-Process PowerShell.exe -Verb RunAs -ArgumentList '-File """%1"""'}"

您需要将其粘贴到regedit中作为默认值:

HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\Open\Command

或者这是一个可以为您完成的脚本:

$hive = [Microsoft.Win32.RegistryKey]::OpenBaseKey('ClassesRoot', 'Default')
$key = $hive.CreateSubKey('Microsoft.PowerShellScript.1\Shell\Open\Command')
$key.SetValue($null, 'Powershell.exe -Command "& {Start-Process PowerShell.exe -Verb RunAs -ArgumentList ''-File """%1"""''}"')

2
投票

您可以使用Windows的“SendTo”功能来简化正在运行的PS1脚本。使用此方法,您可以右键单击PS1脚本并执行。这并不完全回答OP问题,但它很接近。希望这对其他人有用。 BTW ..这对各种其他任务很有帮助。

  • 找到/搜索Powershell.exe
  • 右键单击Powershell.exe并选择“打开文件位置”
  • 右键单击Powershell.exe并选择Create Shortcut。暂时保存一些像桌面一样的地方
  • 默认情况下,您可能希望以管理员身份打开。选择快捷方式>属性>高级>打开管理员
  • 打开Sendto文件夹。开始>运行> Shell:Sendto
  • 将Powershell.exe快捷方式移动到Sendto文件夹
  • 您现在应该可以右键单击PS1脚本。
  • 右键单击PS1文件,选择SendTo上下文选项>选择Powershell快捷方式
  • 你的PS1脚本应该执行。

2
投票

如果您熟悉高级Windows管理,则可以使用this ADM package(该页面上包含说明)并允许在通过此模板和本地GPO双击后运行PowerShell脚本。在此之后,您只需将与.ps1文件类型相关联的默认程序更改为powershell.exe(使用搜索,它已经完全存储),您就可以通过双击运行PowerShell脚本了。

否则,我建议坚持使用其他建议,因为您可以使用这些管理工具搞乱整个系统。

我认为默认设置太严格了。如果有人设法在您的计算机上放置一些恶意代码,那么他/她也可以绕过这个限制(将其包装成.cmd文件或.exe,或者用快捷方式欺骗)并且它最终完成的所有操作只是为了防止你可以通过简单的方式运行你编写的脚本。


1
投票

您可以将ps1文件的默认文件关联设置为powershell.exe,这将允许您通过双击执行powershell脚本。

在Windows 10中,

  1. 右键单击ps1文件
  2. 点击Open with
  3. 点击Choose another app
  4. 在弹出窗口中,选择More apps
  5. 滚动到底部并选择Look for another app on this PC
  6. 浏览并选择C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
  7. 项目清单

这将改变文件关联,并通过双击它们来执行ps1文件。您可以通过将notepad.exe设置为默认应用程序将其更改回其默认行为。

Source


1
投票

我用过这个(需要只运行一次);还要确保您有权执行:

来自PowerShell的权利提升:

Set-ExecutionPolicy=RemoteSigned

然后从bat文件:

-----------------------------------------

 ftype Microsoft.PowerShellScript.1="C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe" -noexit ^&'%%1'

 assoc .ps1=Microsoft.PowerShellScript.1

-----------------------------------------
auto exit: remove -noexit 

瞧双击* .ps1将执行它。


1
投票

在Windows 10中,您可能还希望删除Windows资源管理器的文件扩展名关联覆盖:

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.ps1\UserChoice

除了在其他答案中提到的HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\open\command更改。

https://stackoverflow.com/a/2697804/1360907


-1
投票

来自http://www.howtogeek.com/204166/how-to-configure-windows-to-work-with-powershell-scripts-more-easily

HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell的默认值设置为0


67
投票

或者,如果您希望所有PS1文件都像VBS文件一样工作,您可以像这样编辑注册表:

HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\open\command

编辑默认值是这样的......

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

然后,您可以像您希望的那样双击所有.PS1文件。以我的拙见,能够开箱即用。

我打算称之为“Powershell De-castration Hack”。大声笑享受!


17
投票

请注意,PowerShell的安全功能之一是用户无法通过双击启动脚本。如果修改此设置,请务必小心。另一种方法是打包脚本。像PrimalScript这样的编辑可以做到这一点。用户仍然需要安装PowerShell,但他们可以双击exe。听起来你的团队需要一点教育。


15
投票

我几年前写过这个(用管理员权限运行):

<#
.SYNOPSIS
    Change the registry key in order that double-clicking on a file with .PS1 extension
    start its execution with PowerShell.
.DESCRIPTION
    This operation bring (partly) .PS1 files to the level of .VBS as far as execution
    through Explorer.exe is concern.
    This operation is not advised by Microsoft.
.NOTES
    File Name   : ModifyExplorer.ps1
    Author      : J.P. Blanc - [email protected]
    Prerequisite: PowerShell V2 on Vista and later versions.
    Copyright 2010 - Jean Paul Blanc/Silogix
.LINK
    Script posted on:
    http://www.silogix.fr
.EXAMPLE
    PS C:\silogix> Set-PowAsDefault -On
    Call Powershell for .PS1 files.
    Done!
.EXAMPLE
    PS C:\silogix> Set-PowAsDefault
    Tries to go back
    Done!
#>
function Set-PowAsDefault
{
  [CmdletBinding()]
  Param
  (
    [Parameter(mandatory=$false, ValueFromPipeline=$false)]
    [Alias("Active")]
    [switch]
    [bool]$On
  )

  begin
  {
    if ($On.IsPresent)
    {
      Write-Host "Call PowerShell for .PS1 files."
    }
    else
    {
      Write-Host "Try to go back."
    }
  }

  Process
  {
    # Text Menu
    [string]$TexteMenu = "Go inside PowerShell"

    # Text of the program to create
    [string] $TexteCommande = "%systemroot%\system32\WindowsPowerShell\v1.0\powershell.exe -Command ""&'%1'"""

    # Key to create
    [String] $clefAModifier = "HKLM:\SOFTWARE\Classes\Microsoft.PowerShellScript.1\Shell\Open\Command"

    try
    {
      $oldCmdKey = $null
      $oldCmdKey = Get-Item $clefAModifier -ErrorAction SilentlyContinue
      $oldCmdValue = $oldCmdKey.getvalue("")

      if ($oldCmdValue -ne $null)
      {
        if ($On.IsPresent)
        {
          $slxOldValue = $null
          $slxOldValue = Get-ItemProperty $clefAModifier -Name "slxOldValue" -ErrorAction SilentlyContinue
          if ($slxOldValue -eq $null)
          {
            New-ItemProperty $clefAModifier -Name "slxOldValue" -Value $oldCmdValue  -PropertyType "String" | Out-Null
            New-ItemProperty $clefAModifier -Name "(default)" -Value $TexteCommande  -PropertyType "ExpandString" | Out-Null
            Write-Host "Done !"
          }
          else
          {
            Write-Host "Already done!"
          }
        }
        else
        {
          $slxOldValue = $null
          $slxOldValue = Get-ItemProperty $clefAModifier -Name "slxOldValue" -ErrorAction SilentlyContinue
          if ($slxOldValue -ne $null)
          {
            New-ItemProperty $clefAModifier -Name "(default)" -Value $slxOldValue."slxOldValue"  -PropertyType "String" | Out-Null
            Remove-ItemProperty $clefAModifier -Name "slxOldValue"
            Write-Host "Done!"
          }
          else
          {
            Write-Host "No former value!"
          }
        }
      }
    }
    catch
    {
      $_.exception.message
    }
  }
  end {}
}

13
投票

我同意设置系统设置可能有点多,但需要硬编码路径的快捷方式并不理想。 bat文件实际上很好地解决了这个问题

RunMyPowershellScript.bat

 start powershell -command "& '.\MyPowershellScript.ps1' -MyArguments blah"

现在可以双击此批处理文件,可以轻松地为批处理文件创建快捷方式,并且可以将脚本部署到任何文件夹。


12
投票

你需要调整注册表。首先,为HKEY_CLASSES_ROOT配置一个PSDrive,因为默认情况下没有设置它。对此的命令是:

New-PSDrive HKCR Registry HKEY_CLASSES_ROOT

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

要配置双击以直接启动PowerShell脚本:

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

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

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

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

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

10
投票

这适用于Windows 10和PowerShell 5.1:

  • 右键单击.ps1文件
  • 打开用...
  • 选择其他应用
  • 将powershell.exe的位置复制到地址栏(默认情况下不会显示Windows文件夹),即C:\ Windows \ System32 \ WindowsPowerShell \ v1.0
  • 选择powershell.exe
  • 选择“始终使用此应用程序打开.ps1文件”
  • 单击确定

8
投票

简单的PowerShell命令在注册表中设置它;

New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT
Set-ItemProperty -Path "HKCR:\Microsoft.PowerShellScript.1\Shell\open\command" -name '(Default)' -Value '"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -noLogo -ExecutionPolicy unrestricted -file "%1"'

6
投票
  1. 将REGEDIT导航到HKEY_LOCAL_MACHINE \ SOFTWARE \ Classes \ Microsoft.PowerShellScript.1 \ Shell
  2. 在右侧窗格中,双击“(默认)”
  3. 删除“Open”(启动记事本)的现有值并键入“0”(为零,直接启动Powershell)。

如果您希望再次使用记事本作为默认值,请还原该值。

© www.soinside.com 2019 - 2024. All rights reserved.