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.

4
  • 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. Commented Aug 31, 2019 at 0:44
  • I have several pauses throughout the script, the first is on the first line of execution, and it still isn't stopping there. Commented Aug 31, 2019 at 4: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 ? Commented Aug 31, 2019 at 5: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? Commented Aug 31, 2019 at 13:45

3 Answers 3

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 in GitHub issue #10471.


[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.

Sign up to request clarification or add additional context in comments.

2 Comments

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%'.
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.
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.

3 Comments

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.
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.
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".
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.

4 Comments

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 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.
Thanks, @Theo. I now believe that the problem is simply caused by passing a nonexistent script file path to -File.
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.