How do you call Windows Explorer with a file selected from Powershell? - powershell

I have run into a problem while writing my first basic PowerShell utility. I need to open an Explorer window with a file selected, but can't get the syntax of the command right.
I found this answer on SO, https://stackoverflow.com/a/12162855/957246 and had a read of this excellent blog on external commands, http://edgylogic.com/blog/powershell-and-external-commands-done-right/ - but still can't get it to work.
This is my example script (test.ps1):
$myFile = "C:\Projects\Scripts\any.txt"
# The backslash-backticks are to escape the speech marks, once for PowerShell and then again for DOS
& "C:\Projects\Scripts\EchoArgs.exe" /select",\`"$myFile\`""
& "explorer" /select",\`"$myFile\`""
..and this is the batch file that calls it, in case there's something wrong with the way I'm calling the PowerShell script:
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& 'C:\Projects\Scripts\test.ps1'"
I've tried a few different combinations and the output from echoargs suggests that the syntax is right (assuming the parameter string for explorer is taken as a single string) but whatever I try just opens an explorer window on 'my documents' and the parameters are ignored/being thrown away somewhere.
There's a bit on the MSDN page for explorer.exe switches that says the comma is an empty parameter, maybe that's the thing I need to be providing by formatting the command differently?

What is the point of using batch commands from powershell? Your only going to confuse yourself like that.. and me for that matter.
$myFile = "C:\Projects\Scripts\any.txt"
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.InitialDirectory = Split-Path $myFile -Parent
$OpenFileDialog.FileName = Split-path $myfile -leaf
$OpenFileDialog.ShowDialog() | Out-Null
EDIT
If you need to keep going the explorer route try this :
Start-Process -FilePath C:\Windows\explorer.exe -ArgumentList "/select, ""$myFile"""

Also you could just use:
$dir = "\\PATH\TO\YOUR\DIRECTORY"
C:\Windows\explorer.exe "/select,$dir"

Related

Powershell script using start-process and piping out-file to text file, not working, produces blank text file

This is my first question on SO so here goes!
I'm getting started with a simple powershell script that I intend to use to benchmark some archiving software.
I want to run the archiver (7-zip on Windows 10 in this case) and write the console output to a text file to keep as a log.
Then, I want to append to that same log the start time, end time, file sizes... etc.
The problem is I'm having difficulty sending the output to the text file.
During multiple tries I never could make it work.
I tried Out-File and also the normal ">" redirect but it still ends empty.
I even tried setting -PassThru parameter on Start-Process but it only sent the object properties instead of the Host contents.
Curiously, when I make this command run in CMD with the ">" redirect, it works as expected and I find a text file with the expected contents.
This is my current powershell script:
$7zFilePath = "C:\Program Files\7-Zip\7z.exe"
$dateStart = Get-Date
$contentsToArchive = "D:\Temp -Local\Attack on Titan- Before the Fall-002.jpg"
$workingFolder = "D:\Temp"
$archiveName = "testing {0:yyyy-MM-dd hh.mm.ss.ffff}" -f ($dateStart)
$argument = "a -t7z -m0=LZMA2 -mmt=on -mx9 -md=64m -ms=16g -mfb=273 -mqs=on -mtc=on -mta=on -bb3 `"$workingFolder\$archiveName.7z`" `"$contentsToArchive`""
Set-Location $workingFolder
Start-Process -FilePath $7zFilePath -NoNewWindow -ArgumentList $argument | Out-File ".\$archiveName.txt"
I'm answering my own question because Santiago Squarzon and mklement0 already suggested the solution in the comments to my OP.
Santiago's allowed me to produce the result with Start-Process:
$7zFilePath = "C:\Program Files\7-Zip\7z.exe"
$contentsToArchive = "D:\Temp -Local\Attack on Titan- Before the Fall-002.jpg"
$workingFolder = "D:\Games\Emulation\ROMS\GoodGen V3.21"
$archiveName = "testing {0:yyyy-MM-dd HH.mm.ss.ffff}" -f ($dateStart)
$argument = "a -t7z -m0=LZMA2 -mmt=on -mx9 -md=64m -ms=16g -mfb=273 -mqs=on -mtc=on -mta=on -bb3 `"$workingFolder\$archiveName.7z`" `"$contentsToArchive`""
Set-Location $workingFolder
Start-Process $7zFilePath "$argument" -NoNewWindow -Wait -RedirectStandardOutput ".\$archiveName.txt"
Basically, to use Start-Process and produce a text file with the output I needed to specify it in the -RedirectStandardOutput parameter (which I wasn't using).
However, the output isn't displayed in the Host because it goes straight to the specified text file.
For this, mklement0's explanation and wiki were really useful. Using the & call was much better:
& $7zFilePath `"$argument`" | Out-File -FilePath ".\$archiveName.txt"
With this, I get the output in the Host, and also it's copied to the text file.
Many thanks to you both.

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

Spaces cause split in path with PowerShell

I'm having an issue with powershell when invoking an exe at a path containing spaces.
PS C:\Windows Services> invoke-expression "C:\Windows Services\MyService.exe"
The term 'C:\Windows' 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.
It seems to be splitting on the space between 'Windows' and 'Services'. Any idea how to get around this problem?
Would this do what you want?:
& "C:\Windows Services\MyService.exe"
Use &, the call operator, to invoke commands whose names or paths are stored in quoted strings and/or are referenced via variables, as in the accepted answer. Invoke-Expression is not only the wrong tool to use in this particular case, it should generally be avoided.
You can escape the space by using single quotations and a backtick before the space:
$path = 'C:\Windows Services\MyService.exe'
$path -replace ' ', '` '
invoke-expression $path
Not sure if someone still needs it... I needed to invoke msbuild in powershell and following worked fine:
$MSBuild = "${Env:ProgramFiles(x86)}\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\MSBuild.exe"
& $MSBuild $PathToSolution /p:OutDir=$OutDirVar /t:Rebuild /p:Configuration=Release
"&'C:\Windows Services\MyService.exe'" | Invoke-Expression
via https://www.vistax64.com/powershell/52905-invoke-expression-exe-has-spaces-its-path.html
For any file path with space, simply put them in double quotations will work in Windows Powershell. For example, if you want to go to Program Files directory, instead of use
PS C:\> cd Program Files
which will induce error, simply use the following will solve the problem:
PS C:\> cd "Program Files"
This worked for me:
$scanresults = Invoke-Expression "& 'C:\Program Files (x86)\Nmap\nmap.exe' -vv -sn 192.168.1.1-150 --open"
Using Powershell on Windows10 in 2018, what worked for me was simply to replace double quotes " by simple quotes '. Adding the backtick before the space, as suggested in an answer, broke the path.
What worked for me (I needed the path to create a MySQL dump), was to place the directory in between 6 double quotes like so:
$path = """C:\Path\To\File"""
Can use the . dot operator.
. "C:\Users\user\AppData\Local\Programs\Microsoft VS Code\bin\code.cmd"
or the Start-Process command
Start-Process -PSPath "C:\Users\user\AppData\Local\Programs\Microsoft VS Code\bin\code.cmd"
or using ProcessStartInfo and Process
$ProcessInfo = New-Object -TypeName System.Diagnostics.ProcessStartInfo
$ProcessInfo.FileName = 'C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe'
if($Admin){ $ProcessInfo.Verb = 'runas' }
$ProcessInfo.UseShellExecute = $false
$CommandParameters = '-noexit -noprofile -command Set-Location -LiteralPath c:\; $host.ui.RawUI.WindowTitle = ''[{0}] PS''; Set-PSReadlineOption -HistorySaveStyle SaveNothing;' -f $Cred.UserName
$ProcessInfo.Arguments = $CommandParameters
$ProcessInfo.Domain = ($Cred.UserName -split '\\')[0]
$ProcessInfo.UserName = ($Cred.UserName -split '\\')[1]
$ProcessInfo.Password = $Cred.Password
$ProcessObject = New-Object -TypeName System.Diagnostics.Process
$ProcessObject.StartInfo = $ProcessInfo
$ProcessObject.Start() | Out-Null
There's a hack I've used since the Invoke-Expression works fine for me.
You could set the current location to the path with spaces, invoke the expression, get back to your previous location and continue:
$currLocation = Get-Location
Set-Location = "C:\Windows Services\"
Invoke-Expression ".\MyService.exe"
Set-Location $currLocation
This will only work if the exe doesn't have any spaces in its name.
Hope this helps
Please use this simple one liner:
Invoke-Expression "C:\'Program Files (x86)\Microsoft Office\root\Office16'\EXCEL.EXE"
Try this, simple and without much change:
invoke-expression "'C:\Windows Services\MyService.exe'"
using single quotations at the beginning and end of the path.
Due to several PowerShell quoting rules that are used for passing arguments to native commands which also have specific experimental Features in PowerShell, quoting might get very confusing. Therefore the solution in some cases might be simply to don't go down the rabbit hole:
Avoid quoting file paths with spaces by using the 8.3 filenames
$FSO = New-Object -ComObject Scripting.FileSystemObject
$FSO.getfile('C:\Windows Services\MyService.exe').ShortPath
C:\WINDOW~1\MYSERV~1.EXE
Just put ${yourpathtofile/folder}
PowerShell does not count spaces; to tell PowerShell to consider the whole path including spaces, add your path in between ${ & }.
Simply put the path in double quotes in front of cd, Like this:
cd "C:\Users\MyComputer\Documents\Visual Studio 2019\Projects"
enter the root C drive by entering command
C:
type cd and then press Tab key, it will toggle through all available locations and press enter when you have reached the desired one
cd {press tab}

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

How to reload user profile from script file in PowerShell

I want to reload my user profile from a script file. I thought that dot sourcing it from within the script file would do the trick, but it doesn't work:
# file.ps1
. $PROFILE
However, it does work if I dot source it from PowerShell's interpreter.
Why do I want to do this?
I run this script every time I update my profile and want to test it, so I'd like to avoid having to restart PowerShell to refresh the environment.
If you want to globally refresh your profile from a script, you will have to run that script "dot-sourced".
When you run your script, all the profile script runs in a "script" scope and will not modify your "global" scope.
In order for a script to modify your global scope, it needs to be "dot-source" or preceded with a period.
. ./yourrestartscript.ps1
where you have your profile script "dot-sourced" inside of "yourrestartscript.ps1". What you are actually doing is telling "yourrestartscript" to run in the current scope and inside that script, you are telling the $profile script to run in the script's scope. Since the script's scope is the global scope, any variables set or commands in your profile will happen in the global scope.
That doesn't buy you much advantage over running
. $profile
So, the approach that you marked as the answer may work inside the Powershell command prompt, but it doesn't work inside PowerShell ISE (which, to me, provides a superior PowerShell session) and probably won't work right in other PowerShell environments.
Here's a script that I have been using for a while, and it has worked very well for me in every environment. I simply put this function into my Profile.ps1 at ~\Documents\WindowsPowerShell, and whenever I want to reload my profile, I dot-source the function, i.e.
. Reload-Profile
Here's the function:
function Reload-Profile {
#(
$Profile.AllUsersAllHosts,
$Profile.AllUsersCurrentHost,
$Profile.CurrentUserAllHosts,
$Profile.CurrentUserCurrentHost
) | % {
if(Test-Path $_){
Write-Verbose "Running $_"
. $_
}
}
}
& $profile
works to reload the profile.
If your profile sets aliases or executes imports which fail then you will see errors because they were already set in the previous loading of the profile.
Why are you trying to do this?
Because it is likely to create duplicates (appends to $env:path) and problems with setting constant/readonly objects causing errors.
There was a thread on this topic recently on microsoft.public.windows.powershell.
If you are trying to reset the state of the session there is no way to do this, even using an inner scope ($host.EnterNestedPrompt()) because of the ability to set variables/aliases/... at "all scope".
I found this workaround:
#some-script.ps1
#restart profile (open new powershell session)
cmd.exe /c start powershell.exe -c { Set-Location $PWD } -NoExit
Stop-Process -Id $PID
A more elaborated version:
#publish.ps1
# Copy profile files to PowerShell user profile folder and restart PowerShell
# to reflect changes. Try to start from .lnk in the Start Menu or
# fallback to cmd.exe.
# We try the .lnk first because it can have environmental data attached
# to it like fonts, colors, etc.
[System.Reflection.Assembly]::LoadWithPartialName("System.Diagnostics")
$dest = Split-Path $PROFILE -Parent
Copy-Item "*.ps1" $dest -Confirm -Exclude "publish.ps1"
# 1) Get .lnk to PowerShell
# Locale's Start Menu name?...
$SM = [System.Environment+SpecialFolder]::StartMenu
$CurrentUserStartMenuPath = $([System.Environment]::GetFolderPath($SM))
$StartMenuName = Split-Path $CurrentUserStartMenuPath -Leaf
# Common Start Menu path?...
$CAD = [System.Environment+SpecialFolder]::CommonApplicationData
$allUsersPath = Split-Path $([System.Environment]::GetFolderPath($CAD)) -Parent
$AllUsersStartMenuPath = Join-Path $allUsersPath $StartMenuName
$PSLnkPath = #(Get-ChildItem $AllUsersStartMenuPath, $CurrentUserStartMenuPath `
-Recurse -Include "Windows PowerShell.lnk")
# 2) Restart...
# Is PowerShell available in PATH?
if ( Get-Command "powershell.exe" -ErrorAction SilentlyContinue ) {
if ($PSLnkPath) {
$pi = New-Object "System.Diagnostics.ProcessStartInfo"
$pi.FileName = $PSLnkPath[0]
$pi.UseShellExecute = $true
# See "powershell -help" for info on -Command
$pi.Arguments = "-NoExit -Command Set-Location $PWD"
[System.Diagnostics.Process]::Start($pi)
}
else {
# See "powershell -help" for info on -Command
cmd.exe /c start powershell.exe -Command { Set-Location $PWD } -NoExit
}
}
else {
Write-Host -ForegroundColor RED "Powershell not available in PATH."
}
# Let's clean up after ourselves...
Stop-Process -Id $PID
This is only a refinement of the two line script in guillermooo's answer above, which did not get the new PowerShell window into the correct directory for me. I believe this is because $PWD is evaluated in the new PowerShell window's context, which is not the value we want set-location to process.
function Restart-Ps {
$cline = "`"/c start powershell.exe -noexit -c `"Set-Location '{0}'" -f $PWD.path
cmd $cline
Stop-Process -Id $PID
}
By rights it shouldn't work, as the command line it spits out is malformed, but it seems to do the job and that's good enough for me.
since I stumbled onto this several years later, I thought to add that you can use the invocation operator: & to load your profile with the default variable to your profile: $profile.
so, if your session somehow fails to load your profile (happens to me with cmder/conemu) just type:
& $profile
I used this to troubleshoot what profile was taking forever to load.
Start Run:
powershell_ise -noprofile
Then i ran this:
function Reload-Profile {
#(
$Profile.AllUsersAllHosts,
$Profile.AllUsersCurrentHost,
$Profile.CurrentUserAllHosts,
$Profile.CurrentUserCurrentHost
) | % {
if(Test-Path $_){
Write-Verbose "Running $_"
$measure = Measure-Command {. $_}
"$($measure.TotalSeconds) for $_"
}
}
}
. Reload-Profile
Thank you #Winston Fassett for getting me closer to finding my issue.
Pseudo Alias (simulate keys)
If you just want a function to work like an alias in the console, just simulate the key presses to get around having to use the dot source.
# when "reload" is typed in the terminal, the profile is reloaded
# use sendkeys to send the enter key to the terminal
function reload {
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.SendKeys]::SendWait(". $")
[System.Windows.Forms.SendKeys]::SendWait("PROFILE")
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
}
screenshot of it working