How to open multiple power shell automatically in power shell?

China☆狼群 提交于 2021-02-07 18:14:07

问题


I have my_project.ps1 file from which I am activating virtual environment & starting my project.

currently I need to open my powershell then after I need to go to directory where I have saved my .ps1 file & have to open it from powershell only.

Is there any way so that I can double click on .ps1 file & it will open automatically in power shell ?


回答1:


By design, double-clicking (opening) *.ps1 files from the Windows shell (Desktop, File Explorer, taskbar, Start Menu) does not execute them - instead they're opened for editing in Notepad or the PowerShell ISE, depending on the Windows / PowerShell version

However, since at least Windows 7, the shortcut menu for *.ps1 files contains a Run with PowerShell command, which does invoke the script at hand; this may be enough for your purposes, but this invocation method has limitations - see the bottom section for details.

If you do want to redefine double-clicking / opening so that it executes *.ps1 scripts, you have two options:


GUI method:

Use File Explorer to make PowerShell execute .ps1 files by default:

  • Right-click on a .ps1 file and select Properties.
  • Click on Change... next to the Opens with: label.
  • Click on More apps on the bottom of the list and scroll down to Look for another app on this PC
  • Browse to or paste file path C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe and submit.

This method gives you no control over the specifics of the PowerShell invocation; in effect you'll end up with the following behavior:

  • The redefinition is only in effect for the current user - which is probably a good thing, as other users may not expect this change, which can result in unwanted execution of script.

  • Whatever execution policy is in effect will be honored; e.g., if Restricted is in effect, invocation will fail altogether.

  • As with the default Run in PowerShell command, the window in which the script run will automatically close unless the script explicitly prompts the user before exiting.

To exercise more control over how PowerShell invokes the script, use the programmatic method shown next.


Programmatic method:

Modify the registry to redefine the Open shortcut-menu command for *.ps1 files at HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\shell\Open\Command, as shown below.

Important: If you've previously used the GUI method above, you must manually remove the underlying registry definition, otherwise the programmatic redefinition won't take effect:

  • Open regedit.exe (requires admin rights)

  • Navigate to HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.ps1 and delete that key.

  • Note: At least on Windows 10, trying to remove this key programmatically - e.g. with reg delete HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.ps1\UserChoice /f fails due to permission issues, even when running as admin.

Note:

  • The code redefines the command only for the current user, which is probably the better approach, because other users may not expect this change, which can result in unwanted execution of script.

    • If you still want the make the change to all users, set $forAllUsers to $true, below, but note that you'll then have to run the code elevated (as admin).
  • Unlike the standard Run in PowerShell command, the code below keeps the window in which the script executes open and the session alive.

  • Whatever execution policy is in effect will be honored; e.g., if Restricted is in effect, invocation will fail altogether.

    • In the code below, you can precede -File with something like -ExecutionPolicy RemoteSigned to override the effective policy, but I suggest not choosing a less restrictive value than that for security reasons.
  • As with the standard Run in PowerShell command, the script executes in the directory in which it is located as the working directory (current location).

  • To customize the exact invocation command, modify the $cmd = ... line below.

    • Notably, to target PowerShell Core instead of Windows PowerShell, replace powershell.exe with pwsh.exe.
# Specify if the change should apply to the CURRENT USER only, or to ALL users.
# NOTE: If you set this to $true - which is NOT ADVISABLE - 
#       you'll need to run this code command ELEVATED (as administrator)
$forAllUsers = $false

# Determine the chosen scope's target registry key path.
$targetKey = "$(('HKCU', 'HKLM')[$forAllUsers]):\Software\Classes\Microsoft.PowerShellScript.1\shell\Open\Command"

# In the user-specific hive (HKCU: == HKEY_CURRENT_USER), the target key
# doesn't exist by default (whereas it does in the local-machine hive (HLKM: == HKEY_LOCAL_MACHINE)),
# so we need to make sure that it exists.
if (-not $forAllUsers) {
  $null = New-Item -Force $targetKey -ErrorAction Stop
}

# Specify the command to use when opening / double-clicking *.ps1 scripts:
# As written here:
#   * The profiles are loaded (add -NoProfile to change).
#   * The current execution policy is respected (add -ExecutionPolicy <policy>)
#   * The window stays open after the script exits (remove -NoExit to change)
#   * Windows PowerShell is targeted - to target PowerShell *Core* instead,
#     replace 'powershell.exe' with 'pwsh.exe'
# For help with all parameters, see https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe
$cmd = "`"$((Get-Command powershell.exe)[0].Source)`" -noexit -file `"%1`""

#"# Write the command to the registry.
Set-ItemProperty -LiteralPath $targetKey -Name '(default)' -Value $cmd

The predefined Run in PowerShell shortcut-menu command:

It is defined in registry key HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\shell\0\Command (as of Windows 10) as follows:

"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & '%1'"
  • Unless execution policy AllSigned is in effect - in which case only signed scripts can be executed but are executed without prompting - the command attempts to set the execution policy for the invoked process to Bypass, which means that any script can be executed, but only after the user responds to a confirmation prompt beforehand (irrespective of whether the script is signed or not, and whether it was downloaded from the web or not).

    • At least in earlier Windows 7 releases / PowerShell versions, the command was misdefined[1] in a way that effectively ignored the attempt to set the process' execution policy, which meant that whatever execution policy was persistently configured applied - and no confirmation prompt was shown.
  • Unless the targeted script explicitly pauses to wait for user input before exiting, the window in which the script will close automatically when the script finishes, so you may not get to see its output.

  • The targeted script executes in the directory in which it is located as the working directory (current location)


[1] The earlier, broken command definition was "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-file" "%1" "-Command" "if((Get-ExecutionPolicy ) -ne AllSigned) { Set-ExecutionPolicy -Scope Process Bypass }", which meant what anything after -file "%1" was passed as arguments to file "%1" instead of the intended execution of the commands following -Command; additionally - a moot point - the AllSigned operand would have need to be quoted.




回答2:


Server 2012 and newer by default do not associate the .PS1 file extension with the PowerShell executable; rather, they default to open .PS1 files with notepad by default for security reasons.

If you have access, you need to change the file association through the 'default programs' in your control panel for the .PS1 files to execute by double clicking.

Also be aware that you may have to change your execution policy to get particular scripts to run.

Also, as it sounds like this script might be a core automation, you can execute scripts from in another one with either of these, without the need to change the active working directory: Invoke-Item "" & ''



来源:https://stackoverflow.com/questions/58243310/how-to-open-multiple-power-shell-automatically-in-power-shell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!