I want to execute a powershell script (ps1-file) with a hotkey on my keyboard (CTRL + SHIFT + F for instance).
I managed to create a shortcut of the script (right click in explorer > new > shortcut). The shortcut's target is: "%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File "PATH_TO_THE_SCRIPT" ".
When I execute the script manually (by double-clicking the shortcut), it works like a charm. But when I try to assign a "Shortcut key" in the Shortcut Properties (CTRL + SHIFT + F) and press the shortcut key I just defined, nothing happens. What's the matter?
I'm quite sure it has something to do with security policies. But I don't know what exactly it is.
This is my Execution-Policy:
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process RemoteSigned
CurrentUser Unrestricted
LocalMachine Unrestricted
Any help is appreciated.
That's it. As soon as I move the shortcut file to the desktop and redefine the "shortcut key", the shortcut key works!
Is there a particular reason, why the shortcut has to be on the desktop?
Fist start PowerShell with run as administrator .
then type this command on it :
Set-ExecutionPolicy Bypass -Force
after this you can run all script.
remember if you use Powershell_ise (IDE for powershell) don't use 86x when you're OS is 64 bit.and if you're directory in desktop you should fist set you're directory with :
cd "enter desktop directory"
Related
I a tool just downloaded that opens a Visual Studio Command prompt from within the IDE, in the root of the current project. My main gripe is that it opens an old style command window, where I would rather have a PowerShell window. According to this post, this simple change should allow this:
cmd.exe /k ""%VS120COMNTOOLS%VsDevCmd.bat" & powershell"
When I this command from outside of VS 2015, it seems to work fine and gives me a PowerShell window. Yet when I try and run it from inside VS, using the utility's menu item, it gives me this error:
Cannot load PSReadline module. Console is running without PSReadline.
. : File
C:\Users\brady\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
cannot be loaded because running scripts is disabled on this system.
For more information, see about_Execution_Policies at
http://go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:3
+ . 'C:\Users\brady\Documents\WindowsPowerShell\Microsoft.PowerShell_pr
...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : SecurityError: (:) [], PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess PS C:\Development\vNext\Commerce\src\Commerce.Test> Get-Execution-Policy
PS C:\Development\vNext\Commerce\src\Commerce.Test>
Get-ExecutionPolicy Restricted
My global execution policy is RemoteSigned, but in the same window that show me the error, when I run a Get-ExecutionPolicy, the returned value is Restricted.
I have tried modifying my command to include the PS switch:
cmd /k ""%VS140COMNTOOLS%VsDevCmd.bat" & powershell -ExecutionPolicy Bypass"
But this still gives me exactly the same error.
The output of the command suggested by #PetSerAl in the comments
[Environment]::Is64BitOperatingSystem;[Environment]::Is64BitProcess;Get-ExecutionPolicy -List
gives two different results. The first in a normal PS window external to VS:
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process Undefined
CurrentUser Undefined
LocalMachine RemoteSigned
And the second in the only PS window I can find inside VS, the Package Manager:
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process RemoteSigned
CurrentUser Undefined
LocalMachine Undefined
You can configure an external command and optionally configure a keystroke for it.
I just did this in my VS2015...neat!
Create a cmd file
Create cmd file to call VsDevCmd.bat (Developer Command Prompt for VS2015) and then PowerShell.
dev14powershell.cmd
call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\VsDevCmd.bat"
powershell -ExecutionPolicy Bypass
Configure External Tool
Tools -> External Tools
Calls the cmd file above, starts in Solution Dir (configurable)
Run the new External Tool
Result
A new command window started in Solution Directory.
Optional, configure keyboard shortcut
Tools -> Options -> Keyboard
Search for external and remember the number/order of the command you created (4 in my case)
Hit assign and you have:
When I setup my system, I use a number of config scripts to have my cosy place to play.
Based on this, I run by double-clicking the following enableps.js:
new ActiveXObject("Shell.Application").ShellExecute(
"powershell", "-noexit -Command \"& Set-ExecutionPolicy RemoteSigned\"", "", "runas");
Because of the -noexit I can issue in the displayed PowerShell window:
Get-ExecutionPolicy
and get as expected:
RemoteSigned
Unfortunately, when opening a new instance of PowerShell, the policy keeps to be Restricted.
If I run in a standard cmd prompt:
cscript "path\to\enableps.js"
it works. But if I embed the command in the enableps.cmd batch and again try to run it by double-clicking, it doesn't work. If I right-click enableps.cmd and use the Runas-Administrator entry, it works again.
So how can I make things working with the standard double-click (plus the related Windows prompt)?
You need to run the command and give it the -Scope argument so that it applies to more than the current session. Add the argument:
-Scope CurrentUser
... and the solution is:
Double click on the file:
// enableps.js
// -----------
new ActiveXObject("Shell.Application").ShellExecute(
"powershell", "-Command \"Set-ExecutionPolicy RemoteSigned\" -Scope CurrentUser",
"", "runas");
Consider replacing RemoteSigned with Unrestricted to allow running downloaded scripts too.
Credit goes to TheMadTechnician, who anyway did not write the full code.
By default making system-wide changes will require you to elevate the process if it hasn't been elevated already. If you want your script to disable the execution policy at the machine level then you will either need to switch off UAC or else you will have to run your cscript using a shellExecute, which will present the user with the required UAC approval dialog.
EDIT: To future readers, in short, PowerShell scripts weren't intended to be used this way which is why there is no elegant solution.
I have the following line which runs a script as an administrator from a shortcut:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noprofile
-noexit Start-Process Powershell -verb RunAs -ArgumentList "C:\Documents\WindowsPowerShell\Scripts\test.ps1"
I want to change:
"C:\Documents\WindowsPowerShell\Scripts\test.ps1"
to a relative path like:
".\test.ps1"
but I haven't figured out how I can do that. How can I run the script relative to the location of the shortcut? (The shortcut and script are in the same folder)
Here is an ugly workaround.
Shortcut.lnk file with Target: %COMSPEC% /C .\launcher.cmd (source) and Start In: %CD% (or blank).
Launcher.cmd file with contents:
Powershell -noprofile -noexit -File %CD%\PSlauncher.ps1
PSlauncher.ps1 file with contents:
Start-Process Powershell -verb RunAs -ArgumentList ($pwd.path + "\test.ps1")
Surely there is a better solution. Maybe with the -WorkingDirectory parameter of Start-Process? Or storing credentials with the Convert*-SecureString cmdlets? Count me curious.
Why do you want a shortcut?
After much trial and error, I've come up with a solution:
Create a shortcut with this (edited for your .ps1) to have scrips run as admin relative to any directory:
CMD /C PowerShell "SL -PSPath '%CD%'; $Path = (GL).Path; SL ~; Start PowerShell -Verb RunAs -Args \""SL -PSPath '"$Path"'; & '".\YourScriptHere.ps1"'"\""
You'll have to empty the shortcut's "Start in" field to have its relative path be set as the working directory.
Or, here's a script that will generate one of these shortcuts for each .ps1 in a directory (with "Start in" already cleared):
(GCI | Where-Object {$_.Extension -eq ".ps1"}).Name | ForEach-Object {
$WshShell = New-Object -ComObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut((GL).Path+"\$_ Run.lnk")
$Shortcut.TargetPath = 'CMD'
$Shortcut.Arguments = "/C PowerShell `"SL -PSPath `'%CD%`'; `$Path = (GL).Path; SL ~; Start PowerShell -Verb RunAs -Args \`"`"SL -PSPath `'`"`$Path`"`'; & `'`".\$_`"`'`"\`"`""
$Shortcut.IconLocation = 'PowerShell.exe'
$Shortcut.Save()
}
If needed, add -NoExit, -ExecutionPolicy Unrestricted, etc. just after the first \".
Notes:
The reason for a second, admin instance of PowerShell launching from the first, is that launching as admin directly (by ticking a shortcut's "Run as administrator" box), for some reason ignores "Start in" and always launches in System32.
CMD is being used to launch the first instance because PowerShell currently fails to resolve paths containing square brackets, interpreting them as regex characters. This would normally be avoided using the LiteralPath parameter (aka PSPath), but here, the path is being passed behind the scenes at launch, and it's up to the developers to fix (I just filed a bug report here).
When I run a script from a shortcut, it uses the path of the actual script. You can check the current directory with pwd (present working directory). You can check (and then use) the path of the script with split-path -parent $MyInvocation.MyCommand.Definition like the answer says in What's the best way to determine the location of the current PowerShell script?.
So to answer your question, you should already be able to use relative paths. Have you tried it? If so, what was your experience?
For your script, set it to open using Powershell by default. Create a shortcut for your script and assign it a hot key by right clicking on your shortcut, selecting properties, click the shortcut tab. Move your cursor the select shortcut key and define a shortcut key. Each time you press the shortcut key your script will run
This is definitely made out to be more difficult than it is.
This issue is more likely to affect you on Windows Server. On regular Windows, you can run Set-ExecutionPolicy unrestricted and it will stay in affect on the machine, on Windows Server (at least on AWS), setting the execution policy from a powershell script only lasts for the session of the script and it closes immediately so you can't see the error.
I just successfully modded the registry on an AWS instance bypassing group policy and can simply right click powershell scripts from any directory and send a shortcut to the desktop that is runnable.
How can one make a windows short-cut that opens Powershell into a specific directory?
Such as the target:
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe
-noexit -command {cd c:/path/to/open}
But that just spits out the command as text. How?
Use this command.
powershell.exe -noexit -command "cd c:\temp"
-NoExit: Do not exit after running startup commands.
You can also set the "Start in" shortcut field to your desired location.
Ok - you need to use the & parameter to specify it's a powershell comand & the syntax is slightly different:
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe
-noexit -command "& {cd c:\path\to\open}"
Define a Shortcut for Powershell, and Open the properties of that, and finally in "Start" type the folder target to be opened when Powershell Shortcut is triggered
If you want powershell to start as admin and run in a specific directory, even on a different drive, it is better to use the Set-Location command. Follow these steps
Create a ShortCutLink with the target being the powershellcommand exe.
Leave Start in: blank. (Normally this starts in current working directory when blank; but we do not care.)
Change Target to this with your targets for powershell and locations:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -command "Set-Location D:\_DCode\Main"
Click Advanced... and select Run as administrator.
Click OKs out.
Don't forget the handy trick to change the colors of the shortcut from the Colors tab. That way if you have two or more links which open powershell windows, seeing a different color can visually let you know which shell one is working in.
try:
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe
-noexit -command "cd c:/path/to/open"
If one wants a explorer right click options run this script:
New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT
if(-not (Test-Path -Path "HKCR:\Directory\shell\$KeyName"))
{
Try
{
New-Item -itemType String "HKCR:\Directory\shell\$KeyName" -value "Open PowerShell in this Folder" -ErrorAction Stop
New-Item -itemType String "HKCR:\Directory\shell\$KeyName\command" -value "$env:SystemRoot\system32\WindowsPowerShell\v1.0\powershell.exe -noexit -command Set-Location '%V'" -ErrorAction Stop
Write-Host "Successfully!"
}
Catch
{
Write-Error $_.Exception.Message
}
}
else
{
Write-Warning "The specified key name already exists. Type another name and try again."
}
This is what is shown now:
Note that you can download a detailed script from how to start PowerShell from Windows Explorer.
Copy this code into notepad and save with a reg extension.
Double click the resulting file.If you get a message about importing to the registry click on yes and then ok.
Navigate to any folder in explorer and bring up the context menu. This is typically done by clicking the right mouse button.
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\Directory\Background\shell\PShell]
"MUIVerb"="Open in Powershell Window"
[HKEY_CLASSES_ROOT\Directory\Background\shell\PShell\command]
#="c:\\windows\\system32\\WindowsPowerShell\\v1.0\\powershell.exe -NoExit -Command Set-Location -LiteralPath '%V'"
If you prefer to launch Windows Terminal with your prefered command line shell, you can use:
wt.exe -d "c:\temp"
I just wanted to add my Developer Powershell link ... for the records.
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe -noe -c "&{Import-Module """C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\Tools\Microsoft.VisualStudio.DevShell.dll"""; Enter-VsDevShell d998f19b; cd c:\dev\}"
This will start the Developer Powershell (VS 2019) in c:\dev\.
If you are using Powershell 7 (pwsh), simply use the -WorkingDirectory flag like this:
pwsh -WorkingDirectory "C:\path\to\your\directory"
I use a .ps1 script file to open a PowerShell terminal at a specific path from a shortcut in the taskbar.
The script:
cd 'directory path'
powershell
Running "powershell.exe" from a PowerShell terminal will start a new PowerShell session, preventing the terminal window from closing.
I am using Notepad++ to edit a PowerShell file and want to be able to execute that file from inside Notepad++.
How can I set that up?
It took me a little fiddling, but I finally got this working. (I am using version 1.0 but this should work in other versions as well.)
Notepad++ can be set up to run commands, and assign shortcuts to those commands, as follows:
From the menu, click Run → Run
Add the command
C:\NotepadRun.bat "$(FULL_CURRENT_PATH)"
Save the command, giving it a name and a key shortcut.
Below are the contents of the batch file. I named mine NotepadRun.bat, but you can name it whatever.
#echo off
GOTO %~sx1
:.ps1
cd "%~d1%~p1"
powershell.exe .\%~n1%~sx1
GOTO end
:.rb
ruby "%~f1"
GOTO end
:.php
php "%~f1"
GOTO end
:end
pause
As a note upgrading to Windows7 and Powershell 2 I found some Issues with this and have updated to passing in an ExecutionPolicy to ensure I can run the script I am editing.
:.ps1
cd "%~d1%~p1"
powershell -ExecutionPolicy Unrestricted -File "%~n1%~sx1"
GOTO end
See Using Notepad++ to Compile and Run Java Programs and replace "javac" with "C:Windows\system32\WindowsPowerShell\v1.0\powershell.exe" (or your path to PowerShell). (Caveat: I'm not a Notepad++ user and haven't tried this.)
That said, I'd just use PowerShell ISE (installs with PowerShell) or one of the other dedicated PowerShell IDEs instead.
I would recommend using PowerShell ISE which comes as part of PowerShell and designed specifically for Powershell.
You can run a saved script from "Run" -> "Run" menu in Notepad++ with the following command:
powershell.exe -noexit -command . \"$(FULL_CURRENT_PATH)\"
Based on the answers before:
powershell.exe -ExecutionPolicy Unrestricted -NoLogo -File "$(FULL_CURRENT_PATH)"
You can also add the -NoExit parameter to keep PowerShell from closing automatically:
powershell.exe -ExecutionPolicy Unrestricted -NoExit -NoLogo -File "$(FULL_CURRENT_PATH)"
Note: File has to be saved.