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

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

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

我对他们的懒惰感到厌恶。

是否有一种方法可以通过双击.ps1文件来使PowerShell脚本工作?


当前回答

导航REGEDIT到 HKEY_LOCAL_MACHINE \ SOFTWARE \ \ Microsoft.PowerShellScript.1 \壳类 在右侧窗格中双击“(默认)” 删除现有的“Open”值(启动Notepad),输入“0”(为零,直接启动Powershell)。

如果希望再次使用“记事本”作为默认值,则恢复该值。

其他回答

我的解决方案是2022年 安装“PowerShell-7.2.2-win-x64.msi” 右键单击文件。Ps1,用“pwsh”更改为exec

Powershell注册表黑客和策略绕过从未对我起作用。

这是基于KoZm0kNoT的答案。我修改了它,让它能跨驱动器工作。

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

如果用户的cwd在不同的驱动器上,这两个pushd/popd是必要的。如果没有外部设置,带有脚本的驱动器上的cwd将会丢失。

您需要调整注册表。 首先,为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'

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

RunMyPowershellScript.bat

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

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

与UNIX shar (shell存档)具有相同精神的解决方案。

你可以把你的powershell脚本放在一个扩展名为.cmd的文件中(而不是.ps1),并把它放在开头:

@echo off
Rem Make powershell read this file, skip a number of lines, and execute it.
Rem This works around .ps1 bad file association as non executables.
PowerShell -Command "Get-Content '%~dpnx0' | Select-Object -Skip 5 | Out-String | Invoke-Expression"
goto :eof
# Start of PowerShell script here