2

My end goal is to create a keyboard shortcut that runs a powershell script. I followed what this guy is doing here. Right now, when I run the script from a PowerShell terminal, everything works just fine. But when I run it from the shortcut by double-clicking in the File Explorer (or keyboard shortcut), a new window appears with some kind of text in red but the window disappears before I have time to read anything. I'm sure I could fix the issue if I could read the message, but the window disappears too quickly. My .ps1 script and shortcut are saved to the Desktop.

I found this article that suggests adding the -NoExitswitch, but this does not fix the issue for me.

I have tried changing the Execution Policy to Bypass and Unrestricted and neither made a difference.

I tried modifying my script to pause on the first line of code, but it doesn't get that far so I assume the issue is not with my script.

The shortcut's properties:

Target: %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -noexit -ExecutionPolicy Bypass -File C:\Users\%UserName%\Desktop\<script>.ps1

Start in: C:\Users\%UserName%\Desktop\

The script's properties window.

I need to know why my script isn't running.

Please let me know what other information I left out and thanks in advance.

tbriggs707
  • 99
  • 9
  • in your script, add `pause` at the very end to make the script stop & wait for a keypress. if the problem is deeper in the script than your original `pause`, that should allow you to read the message. – Lee_Dailey Aug 31 '19 at 00:44
  • I have several pauses throughout the script, the first is on the first line of execution, and it still isn't stopping there. – tbriggs707 Aug 31 '19 at 04:16
  • 1
    Are you on a domain? If so it's likely that running unsigned scripts on the domain is controlled by group policy What's the output of the command: Get-ExecutionPolicy -List ? – Scepticalist Aug 31 '19 at 05:19
  • 1
    @tbriggs707 - since it aint stopping ... then the script itself is almost certainly NOT running. [*sigh ...*] what happens if you replace your PS1 file with a BAT file that has only a `pause` in it? – Lee_Dailey Aug 31 '19 at 13:45

3 Answers3

2

Your symptom implies that C:\Users\%UserName%\Desktop\<script>.ps1 refers to a nonexistent script file.

<script>.ps1 is just a placeholder for the real filename.

Note: The use of environment-variable reference %UserName% per se is not a problem; any environment variable can be referenced this way, both in the Target: field (command line) and the Start in: field (working directory).
As an aside: Consider using %USERPROFILE%, or, more robustly, %HOMEDRIVE%%HOMEPATH% to refer to the current user's home directory[1].

Make sure that the path is correct, and try again.

If you want to troubleshoot an environment-variable-based path, temporarily modify your command line as follows:

powershell.exe -noexit -ExecutionPolicy Bypass -c 'C:\Users\%UserName%\Desktop\<script>.ps1'

-File was replaced with -c (-Command), and single quotes are used around the path, which makes PowerShell treat the content as a literal string to print.

The above will merely print the expanded script path.


As for the root cause:

Debatably, PowerShell always exits the new process if the script file path passed to the -File argument cannot be found - even if -NoExit is also present.

The same problem exists - but only in Windows PowerShell, not PowerShell Core - if the file exists but doesn't have extension .ps1.

I've reported this behavior on GitHub.


[1]%USERPROFILE% and %HOMEDRIVE%%HOMEPATH% by default point to the same directory (C:\Users\%USERNAME%), but can be configured point to point to different locations; %USERPROFILE% then points to a directory with OS and application configuration data only, whereas %HOMEDRIVE%%HOMEPATH% points to the directory where the user's desktop and documents are stored.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • 1
    Thanks for your help! I got this to work by using your troubleshooting advice and noticed that the file path was incorrect. I replaced 'C:\Users\%UserName%' with your more robust recommendation of '%HOMEDRIVE%%HOMEPATH%'. – tbriggs707 Sep 05 '19 at 14:17
  • 1
    Glad to hear it, @tbriggs707; my pleasure. While not common, `%USERPROFILE%` and `%HOMEDRIVE%%HOMEPATH%` can point to different locations - I've added a footnote to the answer. – mklement0 Sep 05 '19 at 14:47
0

Try changing C:\Users\%UserName%\ to %userprofile%\. I don't believe that %username% works in shortcuts the way you are trying to use it.

Jesse
  • 1,386
  • 3
  • 9
  • 23
  • I didn't change it substantially, I just made it more specific. It's still the same general idea. I don't see why you're saying it's unhelpful just because it's standard for them to be equivalent. If there's a possibility that it may not be, then why not notify them of that? Who know, maybe it could even be the *answer* they were looking for. Also you probably shouldn't have deleted the first couple comments because they are still relevant. – Jesse Aug 31 '19 at 22:30
  • The original form of your answer erroneously claimed (albeit tempered with "I think") that use of `%username%` was _fundamentally unsupported_. The ensuing comment exchange was focused on disputing that claim. Then you changed your answer to qualify it with "the way your are using it" - which is a substantial change. Even that qualification is mere speculation, because, as stated, `C:\Users\%UserName%` and `%userprofile%` are equivalent in _standard installations_ of Windows. What _may_ help is to point out that they _can_ differ, in _exceptional_ circumstances - see my previous comment. – mklement0 Sep 01 '19 at 02:15
  • As for deleting comments: To be clear: it wasn't _I_ who deleted comments - as a fellow SO user I don't have that power - it was _moderators_ who deleted them, based on my flagging them as "no longer needed". – mklement0 Sep 01 '19 at 02:16
0

You could use the New-Shortcut function I've posted here to create your shortcut:

$myDesktop     = [Environment]::GetFolderPath("Desktop")
$myScriptPath  = Join-Path -Path $myDesktop -ChildPath 'YOUR PS1 SCRIPT FILE'

$shortcutProps = @{
    'ShortcutPath'     = Join-Path -Path $myDesktop -ChildPath 'Run PowerShell File.lnk'
    'TargetPath'       = '%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe'
    'Arguments'        = '-ExecutionPolicy Bypass', '-NoExit', '-NoLogo', ('-File "{0}"' -f $myScriptPath)
    'Description'      = "Run $myScriptPath"
    'WorkingDirectory' = $myDesktop
    'HotKey'           = 'Ctrl','Shift','F'
    'WindowStyle'      = 'Default'
}

New-Shortcut @shortcutProps

Besides the -NoExit switch, there are more options to leave the window open after the code has run.
For that have a look at deadlydog's answer and the blog he wrote about that.

Theo
  • 57,719
  • 8
  • 24
  • 41
  • Interesting; interactively, I can't reproduce the `-File` problem, neither on Windows 7 nor Windows 10 (version 1903). Leaving `-File` out means that `-Command` is implied, which changes the semantics of the invocation in terms of argument handling (not an issue here) and exit-code reporting (potentially an issue) here. What OS are you observing the problem on, and do you also see it when creating the shortcut interactively? – mklement0 Aug 31 '19 at 19:35
  • 1
    @mklement0 I did this on Windows 7, PowerShell 5.1 When I added `-File` to the argument, the script ran but the window closed. Without it, just adding the quoted file path to the arguments array, the script ran and left the window open. I honestly have no idea why `-noexit` seems to be ignored if I include the `-File` parameter name..Although I tried several times it is possible I made some stupid typo each time. Will check again tomorrow as I'm on a phone right now. – Theo Aug 31 '19 at 19:52
  • Thanks, @Theo. I now believe that the problem is simply caused by passing a nonexistent script file path to `-File`. – mklement0 Aug 31 '19 at 20:33
  • 1
    @mklement0 And today.. I cannot reproduce the closing of the window myself anymore, so I must have made some typo yesterday and kept overlooking that. You're probably right about the non existing script file path. I have edited my answer and included the `-File`. – Theo Sep 01 '19 at 08:39