How can I associate a file type with a powershell script? - powershell

I have a very powershell script that works perfectly and does:
Param(
[string]$fileName
)
echo "Woo I opened $fileName"
When I run it on the command line, it works:
my-script.ps1 .\somefile
Returns:
Woo I opened somefile
I would like to associate my-script.ps1 with a particular file type. I am attempting to do this via 'Open With' However:
Windows doesn't include Powershell scripts as 'Programs' (though it considers CMD and batch scripts as 'Programs')
When I pick 'All Files' instead, and pick my powershell script, Windows shows this message
How can I associate a file type with a Powershell script?

Use the proper tools for the job:
cmd /c assoc .fob=foobarfile
cmd /c ftype foobarfile=powershell.exe -File `"C:\path\to\your.ps1`" `"%1`"
Note that both assoc and ftype are CMD-builtins, so you need to run them via cmd /c from PowerShell.
For files without extension use this association:
cmd /c assoc .=foobarfile

I don't think you can do it through Windows UI.
The goal here is to associate a type with powershell.exe, arguments to which will be
The powershell script
The target filename
To do this
Launch Regedit.exe. //disclaimer: you are editing Windows registry. Here be tigers.
Go to HKEY_CLASSES_ROOT (admin access, for all users) or HKEY_CURRENT_USER\SOFTWARE\Classes
Create a key named .<extension>, e.g. if you want to associate *.zbs - create a key .zbs
Set it's (default) value to something like zbsfile -- this is a reference linking your extension to a filetype.
Create a key called zbsfile - this is your filetype
Set (default) value to something readable, e.g. "This file is ZBS."
Underneath create a tree of keys (examples are all around):
zbsfile
shell
open
command
Under command, set (default) value to e.g.
powershell.exe -File "C:\path\to your\file.ps1" "%1"
where %1 means the file user clicked
That should work.
EDIT:
or (crazy idea), create a bat file doing just powershell.exe -File "C:\path\to your\file.ps1" "%%1" and select it in Windows UI...

For those like me who got here looking for general file types associations, I ended up using this function:
Function Create-Association($ext, $exe) {
$name = cmd /c "assoc $ext 2>NUL"
if ($name) { # Association already exists: override it
$name = $name.Split('=')[1]
} else { # Name doesn't exist: create it
$name = "$($ext.Replace('.',''))file" # ".log.1" becomes "log1file"
cmd /c 'assoc $ext=$name'
}
cmd /c "ftype $name=`"$exe`" `"%1`""
}
I struggled with proper quoting from #Ansgar Wiechers's answer but finally got it right :)

Here's my remix of #Matthieu 's great remix of #Ansgar Weichar's great answer.
Matthieu's is set up for executables, and doesn't work for powershell scripts for the same reasons the OP describes.
Function Set-FileAssociationToPowerShellScript($extension, $pathToScript) {
# first create a filetype
$filetype = cmd /c "assoc $extension 2>NUL"
if ($filetype) {
# Association already exists: override it
$filetype = $filetype.Split('=')[1]
Write-Output "Using filetype $filetype"
}
else {
# Name doesn't exist: create it
# ".log.1" becomes "log1file"
$filetype = "$($extension.Replace('.', ''))file"
Write-Output "Creating filetype $filetype ($extension)"
cmd /c "assoc $extension=$filetype"
}
Write-Output "Associating filetype $filetype ($extension) with $pathToScript.."
cmd /c "ftype $filetype=powershell.exe -File `"$pathToScript`" `"%1`""
}

Here is a concrete answer tested under Windows 7 (but should work under 10 too). Open an administrative command shell and execute the following two lines once:
> assoc .ps1=Microsoft.PowerShellScript.1
> ftype Microsoft.PowerShellScript.1=%windir%\System32\WindowsPowerShell\v1.0\powershell.exe -File "%1"
Now PS1-files are executed by PowerShell 1.0 and not opened by Notepad anymore when double-clicked in the Explorer.

For get associate app i use [!magic] :) :
Set-Alias fa Get-AssocApp
#Get application by file extension Proto1
function Get-AssocApp ([string] $FileType) {
((cmd /c echo ((cmd /c ftype ( (cmd /c assoc $FileType) -replace "(.*=)*" ,"")) -replace "(.*=)","")).Replace('"','') -replace "\s%+.*$" ,"")
}
Out:
PS C:\Users\user> fa .txt
C:\WINDOWS\system32\NOTEPAD.EXE
PS C:\Users\user> fa .pdf
C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe
PS C:\Users\user> fa .js
C:\Windows\System32\WScript.exe

Related

Wrong encoding with powershell shell command

I setup my powershell so I can drag and drop files on .ps1 files and start the script with the file paths as arg parameters.
I set a default key to
\HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\Open\Command
Default key
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -File "%1" %*
But this command can't handle files with cyrillic or japanese characters.
For example, create a test.ps1 file:
foreach ($arg in $args) {
Write-Host "$arg"
}
pause
and I start this script like this:
powershell -File test.ps1 "ダーク" "Олег"
I get this result:
PS C:\Users\...\Desktop> powershell -File test.ps1 "ダーク" "Олег"
???
????
Is there an alternative command I can set to start a script or is there a way to force an encoding for this command?

Powershell file won't work with double-click [duplicate]

I am distributing a PowerShell script to my team. The script is to fetch an IP address from the Vsphere client, make an mstsc connection, and log it in a shared file.
The moment they used the script they got to know the IP address of machine. After that, they always tend to use mstsc directly instead of running the PowerShell script.
(As they are using mstsc I am not able to know whether they are using the VM frequently or not.)
Mainly they are telling me that running PowerShell is not straightforward.
I am sick by their laziness.
Is there a way to make a PowerShell script work by double clicking a .ps1 file?
Create a shortcut with something like this as the "Target":
powershell.exe -command "& 'C:\A path with spaces\MyScript.ps1' -MyArguments blah"
Or if you want all PS1 files to work the way VBS files do, you can edit the registry like this:
HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\open\command
Edit the Default value to be something like so...
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -noLogo -ExecutionPolicy unrestricted -file "%1"
Then you can just double click all your .PS1 files like you would like to. in my humble opinion, be able to out of the box.
I'm going to call this "The Powershell De-castration Hack". LOL enjoy!
This worked for me on Windows 10 and powershell 5.1:
right click on the .ps1 file
Open with...
Choose another app
Copy the location of powershell.exe to the address bar (by default it won't show windows folder) i.e. C:\Windows\System32\WindowsPowerShell\v1.0
select powershell.exe
select "Always use this app to open .ps1 files"
click OK
Be aware that one of PowerShell's security features is that users can NOT launch script with a double click. Use great care if you modify this setting. An alternative might be to package your script. Some editors like PrimalScript can do that. The users still need PowerShell installed but then they can double-click the exe. And it sounds like your team needs a little education.
I agree that setting a system setting may be a bit much, but the shortcut requiring a hardcoded path is not ideal. A bat file actually solves the problem nicely
RunMyPowershellScript.bat
start powershell -command "& '.\MyPowershellScript.ps1' -MyArguments blah"
This batch file can now be double clicked on, shortcuts can be easily created to the batch file, and the script can be deployed to any folder.
I wrote this a few years ago (run it with administrator rights):
<#
.SYNOPSIS
Change the registry key in order that double-clicking on a file with .PS1 extension
start its execution with PowerShell.
.DESCRIPTION
This operation bring (partly) .PS1 files to the level of .VBS as far as execution
through Explorer.exe is concern.
This operation is not advised by Microsoft.
.NOTES
File Name : ModifyExplorer.ps1
Author : J.P. Blanc - jean-paul_blanc#silogix-fr.com
Prerequisite: PowerShell V2 on Vista and later versions.
Copyright 2010 - Jean Paul Blanc/Silogix
.LINK
Script posted on:
http://www.silogix.fr
.EXAMPLE
PS C:\silogix> Set-PowAsDefault -On
Call Powershell for .PS1 files.
Done!
.EXAMPLE
PS C:\silogix> Set-PowAsDefault
Tries to go back
Done!
#>
function Set-PowAsDefault
{
[CmdletBinding()]
Param
(
[Parameter(mandatory=$false, ValueFromPipeline=$false)]
[Alias("Active")]
[switch]
[bool]$On
)
begin
{
if ($On.IsPresent)
{
Write-Host "Call PowerShell for .PS1 files."
}
else
{
Write-Host "Try to go back."
}
}
Process
{
# Text Menu
[string]$TexteMenu = "Go inside PowerShell"
# Text of the program to create
[string] $TexteCommande = "%systemroot%\system32\WindowsPowerShell\v1.0\powershell.exe -Command ""&'%1'"""
# Key to create
[String] $clefAModifier = "HKLM:\SOFTWARE\Classes\Microsoft.PowerShellScript.1\Shell\Open\Command"
try
{
$oldCmdKey = $null
$oldCmdKey = Get-Item $clefAModifier -ErrorAction SilentlyContinue
$oldCmdValue = $oldCmdKey.getvalue("")
if ($oldCmdValue -ne $null)
{
if ($On.IsPresent)
{
$slxOldValue = $null
$slxOldValue = Get-ItemProperty $clefAModifier -Name "slxOldValue" -ErrorAction SilentlyContinue
if ($slxOldValue -eq $null)
{
New-ItemProperty $clefAModifier -Name "slxOldValue" -Value $oldCmdValue -PropertyType "String" | Out-Null
New-ItemProperty $clefAModifier -Name "(default)" -Value $TexteCommande -PropertyType "ExpandString" | Out-Null
Write-Host "Done !"
}
else
{
Write-Host "Already done!"
}
}
else
{
$slxOldValue = $null
$slxOldValue = Get-ItemProperty $clefAModifier -Name "slxOldValue" -ErrorAction SilentlyContinue
if ($slxOldValue -ne $null)
{
New-ItemProperty $clefAModifier -Name "(default)" -Value $slxOldValue."slxOldValue" -PropertyType "String" | Out-Null
Remove-ItemProperty $clefAModifier -Name "slxOldValue"
Write-Host "Done!"
}
else
{
Write-Host "No former value!"
}
}
}
}
catch
{
$_.exception.message
}
}
end {}
}
You'll need to tweak registry.
First, configure a PSDrive for HKEY_CLASSES_ROOT since this isn’t set up by default. The command for this is:
New-PSDrive HKCR Registry HKEY_CLASSES_ROOT
Now you can navigate and edit registry keys and values in HKEY_CLASSES_ROOT just like you would in the regular HKCU and HKLM PSDrives.
To configure double-clicking to launch PowerShell scripts directly:
Set-ItemProperty HKCR:\Microsoft.PowerShellScript.1\Shell '(Default)' 0
To configure double-clicking to open PowerShell scripts in the PowerShell ISE:
Set-ItemProperty HKCR:\Microsoft.PowerShellScript.1\Shell '(Default)' 'Edit'
To restore the default value (sets double-click to open PowerShell scripts in Notepad):
Set-ItemProperty HKCR:\Microsoft.PowerShellScript.1\Shell '(Default)' 'Open'
Simple PowerShell commands to set this in the registry;
New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT
Set-ItemProperty -Path "HKCR:\Microsoft.PowerShellScript.1\Shell\open\command" -name '(Default)' -Value '"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -noLogo -ExecutionPolicy unrestricted -file "%1"'
You may set the default file association of ps1 files to be powershell.exe which will allow you to execute a powershell script by double clicking on it.
In Windows 10,
Right click on a ps1 file
Click Open with
Click Choose another app
In the popup window, select More apps
Scroll to the bottom and select Look for another app on this PC.
Browse to and select C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe.
List item
That will change the file association and ps1 files will execute by double-clicking them. You may change it back to its default behavior by setting notepad.exe to the default app.
Source
I tried the top-most answers to this question, but encountered error messages. Then I found the answer here:
PowerShell says "execution of scripts is disabled on this system."
What worked well for me was to use this solution:
powershell -ExecutionPolicy Bypass -File script.ps1
You can paste that into a .bat file and double-click on it.
put a simple .cmd file in my subfolder with my .ps1 file with the same name, so, for example, a script named "foobar" would have "foobar.ps1" and "foobar.cmd". So to run the .ps1, all I have to do is click the .cmd file from explorer or run the .cmd from a command prompt. I use the same base name because the .cmd file will automatically look for the .ps1 using its own name.
::====================================================================
:: Powershell script launcher
::=====================================================================
:MAIN
#echo off
for /f "tokens=*" %%p in ("%~p0") do set SCRIPT_PATH=%%p
pushd "%SCRIPT_PATH%"
powershell.exe -sta -c "& {.\%~n0.ps1 %*}"
popd
set SCRIPT_PATH=
pause
The pushd/popd allows you to launch the .cmd file from a command prompt without having to change to the specific directory where the scripts are located. It will change to the script directory then when complete go back to the original directory.
You can also take the pause off if you want the command window to disappear when the script finishes.
If my .ps1 script has parameters, I prompt for them with GUI prompts using .NET Forms, but also make the scripts flexible enough to accept parameters if I want to pass them instead. This way I can just double-click it from Explorer and not have to know the details of the parameters since it will ask me for what I need, with list boxes or other forms.
Navigate REGEDIT to
HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Microsoft.PowerShellScript.1\Shell
On the right pane, double-click "(Default)"
Delete existing value of "Open" (which launches Notepad) and type "0" (being zero, which launches Powershell directly).
Revert the value if you wish to use Notepad as the default again.
A solution in the same spirit as UNIX shar (shell archive).
You can put your powershell script in a file with the .cmd extension (instead of .ps1), and put this at the start:
#echo off
Rem Make powershell read this file, skip a number of lines, and execute it.
Rem This works around .ps1 bad file association as non executables.
PowerShell -Command "Get-Content '%~dpnx0' | Select-Object -Skip 5 | Out-String | Invoke-Expression"
goto :eof
# Start of PowerShell script here
If you are familiar with advanced Windows administration, then you can use this ADM package (instructions are included on that page) and allow running PowerShell scripts after double click via this template and Local GPO. After this you can simply change default program associated to .ps1 filetype to powershell.exe (use search, it's quite stashed) and you're ready to run PowerShell scripts with double click.
Otherwise, I would recommend to stick with other suggestions as you can mess up the whole system with these administrations tools.
I think that the default settings are too strict. If someone manages to put some malicious code on your computer then he/she is also able to bypass this restriction (wrap it into .cmd file or .exe, or trick with shortcut) and all that it in the end accomplishes is just to prevent you from easy way of running the script you've written.
there is my solution 2022
Install "PowerShell-7.2.2-win-x64.msi"
Right click on file.ps1 and change to exec with "pwsh"
Powershell registry hacks and policy bypass never worked for me.
This is based on KoZm0kNoT's answer. I modified it to work across drives.
#echo off
pushd "%~d0"
pushd "%~dp0"
powershell.exe -sta -c "& {.\%~n0.ps1 %*}"
popd
popd
The two pushd/popds are necessary in case the user's cwd is on a different drive. Without the outer set, the cwd on the drive with the script will get lost.
This is what I use to have scrips run as admin by default:
Powershell.exe -Command "& {Start-Process PowerShell.exe -Verb RunAs -ArgumentList '-File """%1"""'}"
You'll need to paste that into regedit as the default value for:
HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\Open\Command
Or here's a script that will do it for you:
$hive = [Microsoft.Win32.RegistryKey]::OpenBaseKey('ClassesRoot', 'Default')
$key = $hive.CreateSubKey('Microsoft.PowerShellScript.1\Shell\Open\Command')
$key.SetValue($null, 'Powershell.exe -Command "& {Start-Process PowerShell.exe -Verb RunAs -ArgumentList ''-File """%1"""''}"')
I used this (need to run it only once); also make sure you have rights to execute:
from PowerShell with elevated rights:
Set-ExecutionPolicy=RemoteSigned
then from a bat file:
-----------------------------------------
ftype Microsoft.PowerShellScript.1="C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe" -noexit ^&'%%1'
assoc .ps1=Microsoft.PowerShellScript.1
-----------------------------------------
auto exit: remove -noexit
and voila; double-clicking a *.ps1 will execute it.
In Windows 10 you might also want to delete Windows Explorer's override for file extension association:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.ps1\UserChoice
in addition to the HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\open\command change mentioned in other answers.
See https://stackoverflow.com/a/2697804/1360907
You may not want to but an easy way is just to create a .BAT file and put your command in:
powershell ./generate-strings-table-en.ps1
powershell ./generate-conjoined-tables-it.ps1
Then double-click said BAT file.
You can use the Windows 'SendTo' functionality to make running PS1 scripts easier. Using this method you can right click on
a PS1 script and execute. This is doesn't exactly answer the OP question but it is close. Hopefully, this is useful to others. BTW.. this is helpful for
a variety of other tasks.
Locate / Search for Powershell.exe
Right click on Powershell.exe and choose Open File Location
Right click on Powershell.exe and choose Create Shortcut. Temporarily save some place like your desktop
You might want to open as Admin by default. Select Shortcut > Properties > Advanced > Open As Admin
Open the Sendto folder. Start > Run > Shell:Sendto
Move the Powershell.exe shortcut to the Sendto folder
You should now be able to right click on a PS1 script.
Right Click on a PS1 file, Select the SendTo context option > Select the Powershell shortcut
Your PS1 script should execute.
From http://www.howtogeek.com/204166/how-to-configure-windows-to-work-with-powershell-scripts-more-easily:
Set the default value for the HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell to 0

Link a file extension to an app

I was wondering if it would be possible to create PowerShell script that would link a certain file extension to an application.
For example:
The .ntb extension has to be opened using the following application by default:
C:\Program Files\SMART Technologies\Education Software\Notebook.exe
Why would I need a script for this you ask?
It could indeed be done by using Run With and then ticking the Default box. However I need to perform this on about 150+ computers. So I'd think to run the script when booting once.
I am a newbie when it comes to PowerShell, so if anyone could give a "small" start, I would be grateful.
For a scripted solution I'd use the cmd built-ins assoc and ftype:
$prg = 'C:\Program Files\SMART Technologies\Education Software\Notebook.exe'
$ext = '.ntb'
& cmd /c "ftype SMART.Notebook=`"$prg`" %1"
& cmd /c "assoc $ext=SMART.Notebook"
The above can be run on remote hosts via the Invoke-Command cmdlet:
Invoke-Command -Computer HostA,HostB,... -ScriptBlock {
$prg = 'C:\Program Files\SMART Technologies\Education Software\Notebook.exe'
$ext = '.ntb'
& cmd /c "ftype SMART.Notebook=`"$prg`" %1"
& cmd /c "assoc $ext=SMART.Notebook"
}
Otherwise you'll have to edit the registry, in which case the deployment via group policy would be preferable, as others have already pointed out.

Is there a way to make a PowerShell script work by double clicking a .ps1 file?

I am distributing a PowerShell script to my team. The script is to fetch an IP address from the Vsphere client, make an mstsc connection, and log it in a shared file.
The moment they used the script they got to know the IP address of machine. After that, they always tend to use mstsc directly instead of running the PowerShell script.
(As they are using mstsc I am not able to know whether they are using the VM frequently or not.)
Mainly they are telling me that running PowerShell is not straightforward.
I am sick by their laziness.
Is there a way to make a PowerShell script work by double clicking a .ps1 file?
Create a shortcut with something like this as the "Target":
powershell.exe -command "& 'C:\A path with spaces\MyScript.ps1' -MyArguments blah"
Or if you want all PS1 files to work the way VBS files do, you can edit the registry like this:
HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\open\command
Edit the Default value to be something like so...
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -noLogo -ExecutionPolicy unrestricted -file "%1"
Then you can just double click all your .PS1 files like you would like to. in my humble opinion, be able to out of the box.
I'm going to call this "The Powershell De-castration Hack". LOL enjoy!
This worked for me on Windows 10 and powershell 5.1:
right click on the .ps1 file
Open with...
Choose another app
Copy the location of powershell.exe to the address bar (by default it won't show windows folder) i.e. C:\Windows\System32\WindowsPowerShell\v1.0
select powershell.exe
select "Always use this app to open .ps1 files"
click OK
Be aware that one of PowerShell's security features is that users can NOT launch script with a double click. Use great care if you modify this setting. An alternative might be to package your script. Some editors like PrimalScript can do that. The users still need PowerShell installed but then they can double-click the exe. And it sounds like your team needs a little education.
I agree that setting a system setting may be a bit much, but the shortcut requiring a hardcoded path is not ideal. A bat file actually solves the problem nicely
RunMyPowershellScript.bat
start powershell -command "& '.\MyPowershellScript.ps1' -MyArguments blah"
This batch file can now be double clicked on, shortcuts can be easily created to the batch file, and the script can be deployed to any folder.
I wrote this a few years ago (run it with administrator rights):
<#
.SYNOPSIS
Change the registry key in order that double-clicking on a file with .PS1 extension
start its execution with PowerShell.
.DESCRIPTION
This operation bring (partly) .PS1 files to the level of .VBS as far as execution
through Explorer.exe is concern.
This operation is not advised by Microsoft.
.NOTES
File Name : ModifyExplorer.ps1
Author : J.P. Blanc - jean-paul_blanc#silogix-fr.com
Prerequisite: PowerShell V2 on Vista and later versions.
Copyright 2010 - Jean Paul Blanc/Silogix
.LINK
Script posted on:
http://www.silogix.fr
.EXAMPLE
PS C:\silogix> Set-PowAsDefault -On
Call Powershell for .PS1 files.
Done!
.EXAMPLE
PS C:\silogix> Set-PowAsDefault
Tries to go back
Done!
#>
function Set-PowAsDefault
{
[CmdletBinding()]
Param
(
[Parameter(mandatory=$false, ValueFromPipeline=$false)]
[Alias("Active")]
[switch]
[bool]$On
)
begin
{
if ($On.IsPresent)
{
Write-Host "Call PowerShell for .PS1 files."
}
else
{
Write-Host "Try to go back."
}
}
Process
{
# Text Menu
[string]$TexteMenu = "Go inside PowerShell"
# Text of the program to create
[string] $TexteCommande = "%systemroot%\system32\WindowsPowerShell\v1.0\powershell.exe -Command ""&'%1'"""
# Key to create
[String] $clefAModifier = "HKLM:\SOFTWARE\Classes\Microsoft.PowerShellScript.1\Shell\Open\Command"
try
{
$oldCmdKey = $null
$oldCmdKey = Get-Item $clefAModifier -ErrorAction SilentlyContinue
$oldCmdValue = $oldCmdKey.getvalue("")
if ($oldCmdValue -ne $null)
{
if ($On.IsPresent)
{
$slxOldValue = $null
$slxOldValue = Get-ItemProperty $clefAModifier -Name "slxOldValue" -ErrorAction SilentlyContinue
if ($slxOldValue -eq $null)
{
New-ItemProperty $clefAModifier -Name "slxOldValue" -Value $oldCmdValue -PropertyType "String" | Out-Null
New-ItemProperty $clefAModifier -Name "(default)" -Value $TexteCommande -PropertyType "ExpandString" | Out-Null
Write-Host "Done !"
}
else
{
Write-Host "Already done!"
}
}
else
{
$slxOldValue = $null
$slxOldValue = Get-ItemProperty $clefAModifier -Name "slxOldValue" -ErrorAction SilentlyContinue
if ($slxOldValue -ne $null)
{
New-ItemProperty $clefAModifier -Name "(default)" -Value $slxOldValue."slxOldValue" -PropertyType "String" | Out-Null
Remove-ItemProperty $clefAModifier -Name "slxOldValue"
Write-Host "Done!"
}
else
{
Write-Host "No former value!"
}
}
}
}
catch
{
$_.exception.message
}
}
end {}
}
You'll need to tweak registry.
First, configure a PSDrive for HKEY_CLASSES_ROOT since this isn’t set up by default. The command for this is:
New-PSDrive HKCR Registry HKEY_CLASSES_ROOT
Now you can navigate and edit registry keys and values in HKEY_CLASSES_ROOT just like you would in the regular HKCU and HKLM PSDrives.
To configure double-clicking to launch PowerShell scripts directly:
Set-ItemProperty HKCR:\Microsoft.PowerShellScript.1\Shell '(Default)' 0
To configure double-clicking to open PowerShell scripts in the PowerShell ISE:
Set-ItemProperty HKCR:\Microsoft.PowerShellScript.1\Shell '(Default)' 'Edit'
To restore the default value (sets double-click to open PowerShell scripts in Notepad):
Set-ItemProperty HKCR:\Microsoft.PowerShellScript.1\Shell '(Default)' 'Open'
Simple PowerShell commands to set this in the registry;
New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT
Set-ItemProperty -Path "HKCR:\Microsoft.PowerShellScript.1\Shell\open\command" -name '(Default)' -Value '"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -noLogo -ExecutionPolicy unrestricted -file "%1"'
You may set the default file association of ps1 files to be powershell.exe which will allow you to execute a powershell script by double clicking on it.
In Windows 10,
Right click on a ps1 file
Click Open with
Click Choose another app
In the popup window, select More apps
Scroll to the bottom and select Look for another app on this PC.
Browse to and select C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe.
List item
That will change the file association and ps1 files will execute by double-clicking them. You may change it back to its default behavior by setting notepad.exe to the default app.
Source
I tried the top-most answers to this question, but encountered error messages. Then I found the answer here:
PowerShell says "execution of scripts is disabled on this system."
What worked well for me was to use this solution:
powershell -ExecutionPolicy Bypass -File script.ps1
You can paste that into a .bat file and double-click on it.
put a simple .cmd file in my subfolder with my .ps1 file with the same name, so, for example, a script named "foobar" would have "foobar.ps1" and "foobar.cmd". So to run the .ps1, all I have to do is click the .cmd file from explorer or run the .cmd from a command prompt. I use the same base name because the .cmd file will automatically look for the .ps1 using its own name.
::====================================================================
:: Powershell script launcher
::=====================================================================
:MAIN
#echo off
for /f "tokens=*" %%p in ("%~p0") do set SCRIPT_PATH=%%p
pushd "%SCRIPT_PATH%"
powershell.exe -sta -c "& {.\%~n0.ps1 %*}"
popd
set SCRIPT_PATH=
pause
The pushd/popd allows you to launch the .cmd file from a command prompt without having to change to the specific directory where the scripts are located. It will change to the script directory then when complete go back to the original directory.
You can also take the pause off if you want the command window to disappear when the script finishes.
If my .ps1 script has parameters, I prompt for them with GUI prompts using .NET Forms, but also make the scripts flexible enough to accept parameters if I want to pass them instead. This way I can just double-click it from Explorer and not have to know the details of the parameters since it will ask me for what I need, with list boxes or other forms.
Navigate REGEDIT to
HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Microsoft.PowerShellScript.1\Shell
On the right pane, double-click "(Default)"
Delete existing value of "Open" (which launches Notepad) and type "0" (being zero, which launches Powershell directly).
Revert the value if you wish to use Notepad as the default again.
A solution in the same spirit as UNIX shar (shell archive).
You can put your powershell script in a file with the .cmd extension (instead of .ps1), and put this at the start:
#echo off
Rem Make powershell read this file, skip a number of lines, and execute it.
Rem This works around .ps1 bad file association as non executables.
PowerShell -Command "Get-Content '%~dpnx0' | Select-Object -Skip 5 | Out-String | Invoke-Expression"
goto :eof
# Start of PowerShell script here
If you are familiar with advanced Windows administration, then you can use this ADM package (instructions are included on that page) and allow running PowerShell scripts after double click via this template and Local GPO. After this you can simply change default program associated to .ps1 filetype to powershell.exe (use search, it's quite stashed) and you're ready to run PowerShell scripts with double click.
Otherwise, I would recommend to stick with other suggestions as you can mess up the whole system with these administrations tools.
I think that the default settings are too strict. If someone manages to put some malicious code on your computer then he/she is also able to bypass this restriction (wrap it into .cmd file or .exe, or trick with shortcut) and all that it in the end accomplishes is just to prevent you from easy way of running the script you've written.
there is my solution 2022
Install "PowerShell-7.2.2-win-x64.msi"
Right click on file.ps1 and change to exec with "pwsh"
Powershell registry hacks and policy bypass never worked for me.
This is based on KoZm0kNoT's answer. I modified it to work across drives.
#echo off
pushd "%~d0"
pushd "%~dp0"
powershell.exe -sta -c "& {.\%~n0.ps1 %*}"
popd
popd
The two pushd/popds are necessary in case the user's cwd is on a different drive. Without the outer set, the cwd on the drive with the script will get lost.
This is what I use to have scrips run as admin by default:
Powershell.exe -Command "& {Start-Process PowerShell.exe -Verb RunAs -ArgumentList '-File """%1"""'}"
You'll need to paste that into regedit as the default value for:
HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\Open\Command
Or here's a script that will do it for you:
$hive = [Microsoft.Win32.RegistryKey]::OpenBaseKey('ClassesRoot', 'Default')
$key = $hive.CreateSubKey('Microsoft.PowerShellScript.1\Shell\Open\Command')
$key.SetValue($null, 'Powershell.exe -Command "& {Start-Process PowerShell.exe -Verb RunAs -ArgumentList ''-File """%1"""''}"')
I used this (need to run it only once); also make sure you have rights to execute:
from PowerShell with elevated rights:
Set-ExecutionPolicy=RemoteSigned
then from a bat file:
-----------------------------------------
ftype Microsoft.PowerShellScript.1="C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe" -noexit ^&'%%1'
assoc .ps1=Microsoft.PowerShellScript.1
-----------------------------------------
auto exit: remove -noexit
and voila; double-clicking a *.ps1 will execute it.
In Windows 10 you might also want to delete Windows Explorer's override for file extension association:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.ps1\UserChoice
in addition to the HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\open\command change mentioned in other answers.
See https://stackoverflow.com/a/2697804/1360907
You may not want to but an easy way is just to create a .BAT file and put your command in:
powershell ./generate-strings-table-en.ps1
powershell ./generate-conjoined-tables-it.ps1
Then double-click said BAT file.
You can use the Windows 'SendTo' functionality to make running PS1 scripts easier. Using this method you can right click on
a PS1 script and execute. This is doesn't exactly answer the OP question but it is close. Hopefully, this is useful to others. BTW.. this is helpful for
a variety of other tasks.
Locate / Search for Powershell.exe
Right click on Powershell.exe and choose Open File Location
Right click on Powershell.exe and choose Create Shortcut. Temporarily save some place like your desktop
You might want to open as Admin by default. Select Shortcut > Properties > Advanced > Open As Admin
Open the Sendto folder. Start > Run > Shell:Sendto
Move the Powershell.exe shortcut to the Sendto folder
You should now be able to right click on a PS1 script.
Right Click on a PS1 file, Select the SendTo context option > Select the Powershell shortcut
Your PS1 script should execute.
From http://www.howtogeek.com/204166/how-to-configure-windows-to-work-with-powershell-scripts-more-easily:
Set the default value for the HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell to 0

PowerShell alias syntax for running a cmd.exe builtin function?

As I have only recently switched to PowerShell from cmd.exe, I often find it convenient to do little things in a familiar way by calling cmd to do them. For instance, to do a 'bare' file listing this works great:
PS> cmd /c dir /b
dir1
dir2
file1.txt
I'd like to make an alias for this but I can't figure out the right syntax. So far I've tried:
PS> Set-Alias dirb cmd /c dir /b # error (alias not created)
PS> Set-Alias dirb "cmd /c dir /b" # fail (alias doesn't work)
PS> Set-Alias dirb "cmd `"/c dir /b`"" # fail (alias doesn't work)
Any suggestions? I'm looking for a general solution to calling builtin cmd.exe commands (such as dir). I'd also like to know how to produce bare output the right way using PowerShell cmdlets, but that's a secondary concern at the moment. This question is about the proper syntax for calling cmd.exe from an alias.
I believe what you want is a function, not an alias. For instance:
function dirb {
cmd /c dir $args[0] /b
}
From a PS prompt, run notepad $profile, paste that into your profile and then it will load automatically when you open a PS console and you can do this:
dirb c:\somedir
See get-help about_functions for more information about functions.
Aliases are not designed for this kind of tasks. An alias is just another name of a command. Use the function instead.
function dirb { cmd /c dir /b }
Aliases in powershell don't take parameters unfortunately - you need to define a function for this. For more info,
get-help aliases
Why on earth would you use powershell to open the command prompt? That seems to be defeating the purpose.
The Alias I prefer to list out files is simply ls