How Can I Run a Windows PowerShell Script from the Run Dialog Box or a Shortcut?

How Can I Run a Windows PowerShell Script from the Run Dialog Box or a Shortcut?

  • Comments 13
  • Likes
Hey, Scripting Guy! Question

Hey, Scripting Guy! How can I run a Windows PowerShell script from the Run dialog box or from a shortcut? In the Run dialog box I type something like c:\scripts\test.ps1 but my script just opens up in Notepad.

-- RS

SpacerHey, Scripting Guy! AnswerScript Center

Hey, RS. We have just one thing to say: University of Washington 29, UCLA 19. And this after the Huskies trailed 16-0 late in the first half. Granted, it's still early, but at 3-1 the UW already has as many wins this year as they've had in the last two seasons combined.

But that’s all we’re going to say. After all, the Scripting Guy who writes this column knows enough about sports to know better than to jinx a team just when things are starting to look up. So let's just say that it's always nice to beat UCLA and leave it at that. See you all tomorrow!

Pardon? How can you run a Windows PowerShell script from the Run dialog box or from a shortcut? Um, didn't we tell you that we only had one thing to say? And we already said it: University of Washington 29, UCLA 19.

Could we put you on hold for a second? Really? You’re kidding, right? Wow; we wouldn’t have guessed that in a million years.

OK. Apparently, or at least from what we’ve been told, not everyone in the world is a college football fan. That’s hard for us to believe: people would rather know how to run a Windows PowerShell script from the Run dialog box or from a shortcut than talk about Saturday’s Husky-UW game? But, just in case, we’ll see if we can answer your question, RS.

No, no need to thank us; it’s no problem. Besides, we have a few hours to kill before the Husky Highlight show comes on anyway.

So why do your Windows PowerShell scripts keep opening up in Notepad? That’s because the Windows shell – bless its heart – doesn’t know what to do with Windows PowerShell scripts. The last time we installed Windows PowerShell (and remember, the application is still in beta, so the installation process might have changed since then) script files (files with a .ps1 file extension) were automatically associated with Notepad. That’s probably why your script files keep opening up in Notepad: ours do, too, simply because that’s what the Windows shell does with .ps1 files.

Of course, that might lead you to believe that all you have to do is associate .ps1 files with the Windows PowerShell executable file and everything will be hunky-dory. That’s what we thought, too, but that doesn’t seem to work. Instead, in order to start a Windows PowerShell script from the Run dialog box or from a shortcut (or, for that matter, from Cmd.exe) you need to explicitly start Windows PowerShell and then pass the path to the script file as a startup parameter. In other words, this command will start Windows PowerShell and run the script C:\Scripts\Test.ps1:

powershell.exe c:\scripts\test.ps1

Of course, if you immediately ran off and tried that command, without bothering to read the rest of the column (for shame!) you were likely disappointed. “Wait a second; that doesn’t work, either,” you’re likely grumbling. “I saw a brief flash and then, nothing. Nice try, Scripting Guys, but no cigar!”

To tell you the truth, your command probably did work; the problem is that Windows PowerShell started, the script ran, the script finished, and then Windows PowerShell automatically terminated, just like that. You can verify that this is what’s happening by running a script that saves data to a text file. Start the script using the method outlined above, and then check to see if the text file was created and the data saved. If it was, then the command worked; it’s just that Windows PowerShell did its thing and then, like the Lone Ranger, disappeared before you could even thank it.

Now, that’s all fine and dandy … unless you need to read the output onscreen. In that case we have a problem, because everything typically happens way too fast for the human eye to follow. (Granted, the Scripting Editor insists that she can spot dangling participles and split infinitives even at that speed. But, remember, we said it was too fast for the human eye to follow.) If you need to read output onscreen what you have to do is tell Windows PowerShell to keep its command window open after the script finishes running. That’s something you can do by adding the –noexit parameter to your command:

powershell.exe –noexit c:\scripts\test.ps1

Give that a try and see what happens. When you do, make sure you leave –noexit as the first parameter. In our experience, switching the parameters around (that is, first specifying the script path and then tacking on –noexit) won’t work.

But, then again, you should always do everything exactly the way the Scripting Guys tell you.

OK, good point, even though the first explosion wasn’t entirely our fault; if dolphins are so smart then they should known better. But at least type your Windows PowerShell command exactly the way we told you.

We hope that solves your problem, RS. If you need more information about Windows PowerShell you might take a look at our Windows PowerShell center; among other things, you’ll find a new excerpt from the forthcoming book Windows PowerShell in Action, written by Microsoft’s own Bruce Payette. And stay tuned for Windows PowerShell Week, a series of five webcasts (aimed squarely at beginners) scheduled for November 6-10. We’ll have more information on Windows PowerShell Week very soon.

Most important of all, next week the Huskies travel to Arizona to play the Wildcats. Could the Huskies really start the season 4-1, including 2-0 in conference play? Let’s put it this way: if they do, it’s a pretty safe bet you’ll be able to read about it here. Will you also be able to read about scripting-related stuff here? In the immortal words of Bart Simpson, we can’t promise to try. But we promise to try to try.


Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • When I run

    powershell.exe -noexit c:\PowerShellScripts\Test1.ps1

    I get the error:

    You must provide a value expression on the right-hand side of the '-' operator

    At c:\PowerShellScripts\Test1.ps1:4 char:7

    ...

  • You need to put in your quotes "C:\Powershellscripts..."

  • powershell.exe -noexit d:\scripts\mynicescript.ps1

    returns

    File D:\scripts\mynicescript.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about_signing" for more details.

    I can look that up, but it would be nice if the documentation told you this kind of thing before you spent hours putting a script together.

    Helpful.

  • You also need to set the execution policy to allow scripts to run. By defaut PowerShell can only be used in interactive mode.

    To enable scripts use teh command:

    Set-ExecutionPolicy RemoteSigned

    To run the above command you will need to run PowerShell as Administrator.

    Ref: technet.microsoft.com/.../dd347628.aspx

  • # 2>nul||@cls&echo off

    # 2>nul||REM --- SOLO.BAT - SAMPLE OF BATCH AND POWERSHELL IN ONE FILE

    # 2>nul||REM --- copy this .bat file to .ps1 and execute powershell

    # 2>nul||cd /d %0\..&copy %~n0.bat %~n0.ps1 1>nul||goto :EOF

    # 2>nul||REM --- execute this file as a powershell script

    # 2>nul||powershell.exe -file %0.ps1 -executionpolicy bypass -nologo

    # 2>nul||REM --- when powershell returns, delete the .ps1 file

    # 2>nul||del %~n0.ps1&goto :EOF

    Write-Host 'The PowerShell portion of this file has begun' -ForegroundColor 'Green'

    Get-Location;

    $MyInvocation;

    Write-Host 'The PowerShell portion of this file has ended' -ForegroundColor 'Green'

  • This doesn´t help, Win 7 doesn´t allow me to insert the -noexit param at the .ps1 file properties, where can i insert something INSIDE the script so it remains open?

  • Frankly, too much wasted prose to trying to be conversational and as discussed in the comments critical technical details are missing. We come here for accurate tech info, not for infotainment. The whole 'trying to be friendly neighbor next door' is super-annoying when I'm trying to quickly find precise, detailed, accurate info. I'd rather you spend the time testing each set of suggestions and bulleting or numbering the steps so I can find them quickly.

  • you should learn to write for short films, the text at the beginning seems an script, a film script .....

  • Having Trouble: I am getting the fallowing error when i run my ps1 file.

    The term 'C:\\PowerShell\Startups\StartStartUps.ps1' is not recognized as the n

    ame of a cmdlet, function, script file, or operable program. Check the spelling

    of the name, or if a path was included, verify that the path is correct and tr

    y again.

    At line:1 char:2

    + & <<<<  C:\$Scripts\PowerShell\Startups\StartStartUps.ps1

       + CategoryInfo          : ObjectNotFound: (C:\\PowerShell\...artStartUps.p

      s1:String) [], CommandNotFoundException

       + FullyQualifiedErrorId : CommandNotFoundException

  • 1) Correction to my SOLO.BAT sample, -File should be the last parameter.

    2) Better solution, SOLO2.BAT sample creates a scriptblock, removing the need for a temporary file.

    # 2>nul||@cls&echo off&title %~n0

    # 2>nul||PowerShell.exe -ExecutionPolicy 'Bypass' -NoLogo -Command "& {Get-Content %~f0|foreach{$s+=""""$_`n""""};Invoke-Command([scriptblock]::Create($s));}"

    # 2>nul||goto :EOF

    #--- Solo2.bat

    #--- This is an example of a PowerShell script embedded in a batch script.

    #--- This allows a single file to be invoked.  The PowerShell command reads

    #--- and formats the script file into a script block and executes it.

    [cmdletbinding()] param ();

    Set-StrictMode -Version 2;

    Write-Host 'This is the PowerShell script';

  • Even better, use these 3 lines to the top of the CMD. Directly reads the CMD as a PS1. Note that a "." include will not function in the PS1 portion.
    # 2>nul||@cls&echo off&title %~n0
    # 2>nul||PowerShell.exe -ExecutionPolicy 'Bypass' -NoLogo -Command "& {Get-Content %~f0|foreach{$s+=""""$_`n""""};Invoke-Command([scriptblock]::Create($s));}"
    # 2>nul||goto :EOF
    #--- Solo2.bat
    #--- This is an example of a PowerShell script embedded in a batch script.
    #--- This allows a single file to be invoked. The PowerShell command reads
    #--- and formats the script file into a script block and executes it.
    [cmdletbinding()] param ();
    Set-StrictMode -Version 2;
    Write-Host 'This is the PowerShell script';

  • Hi,
    I'm new to powershelle, can you tell me how to resolve this?

    The term '.\InFilesUsingList.ps1' is not recognized as the name of a cmdlet, function, script file, or operable
    program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
    At line:1 char:31
    + .\InFilesUsingList.ps1 <<<< -List ".\ReplacementList.csv" -Files ".\try\ISNF007_*.txt"
    + CategoryInfo : ObjectNotFound: (.\Replace-InFilesUsingList.ps1:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

  • I am trying two things that doesn’t work right.
    1st Code:
    Param (
    [String]$List = “ReplacementList.csv”,
    [String]$Files = “.\try\*.*”
    )
    $ReplacementList = Import-Csv $List;
    Get-ChildItem $Files |

    ForEach-Object {
    $Content = Get-Content -Path $_.FullName;
    foreach ($ReplacementItem in $ReplacementList)
    {
    $old = $ReplacementItem.OldValue
    $new = $ReplacementItem.NewValue
    $Content = $Content -Replace “$old”, “$new”
    }
    Set-Content -Path $_.FullName -Value $Content
    }

    The output I am getting is “ABC_10_9_8_7_6_5_4_3_2_1″ in all files.. =(

    How can I make the text output like this? Each File should be changed with different text from the .csv list
    “ABC_1″ in the 1st file (FILE1)
    “ABC_2″ in the 2nd file (FILE2)
    “ABC_3″ in the 3rd file (FILE3)

    I tried the 2nd Code:
    Param (
    [String]$List = “ReplacementList.csv”,
    [String]$Files = “.\try\*.*”
    )
    $ReplacementList = Import-Csv $List;
    Get-ChildItem $Files |

    ForEach-Object {
    $Content = Get-Content -Path $_.FullName;
    foreach ($ReplacementItem in $ReplacementList)
    {
    $Content = $Content.replace(“$ReplacementItem.OldValue”, “$ReplacementItem.NewValue”)
    }
    Set-Content -Path $_.FullName -Value $Content
    }

    The output is:
    Method invocation failed because [System.Object[]] doesn’t contain a method named ‘replace’.
    At C:\try\Files.pst:11 chat:34
    $Content = $Content.replace <<<< ("$ReplacementItem.OldValue", "$ReplacementItem.NewValue")
    Category Info: InvalidOperation: (replace:String)[], RuntimeException
    MethodNotFound

    Any suggestions?