'Run PowerShell command(s) outside of PowerShell
I have this simple PowerShell script:
Copy-Item -path ('\\PC1\Images\' + (Get-ChildItem -Path '\\PC1\Images' -Attributes !Directory *.dat | Sort-Object -Descending -Property LastWriteTime | Select-Object -first 1)) 'C:\Temp\PC1\screen.jpg' | Start-Process 'C:\Program Files\Google\Chrome\Application\chrome.exe' -ArgumentList 'file:///C:/Temp/PC1/screen.jpg'
If I run this command from a PowerShell window, it works fine. If I save it as .ps1 file and run it from Windows Explorer, nothing happens (Chrome does not open the desired URL).
What can be done to allow to execute this script from some shortcut? (I want to add a shortcut/icon to my Windows taskbar for fast access).
Solution 1:[1]
You have two options:
Either: Make
.ps1files themselves - which by default are opened for editing when opened (double-clicked) from File Explorer / the desktop / the taskbar - directly executable:See this answer.
Important: Doing this will make all
.ps1files you drag to the taskbar be associated with a single icon, for PowerShell itself, with the dragged files getting pinned to that icon; that is, to run such a file you'll have to do so via the PowerShell icon's shortcut menu.
Or: For a given
.ps1file, create a companion shortcut file (.lnk) or batch file (.cmd) that launches it, via PowerShell's CLI (powershell.exefor Windows PowerShell,pwsh.exefor PowerShell (Core) 7+)Note: Once you've created a companion file as described below, dragging it to the taskbar will give it is own taskbar icon.
Batch-file approach:
Create a companion batch file in the same folder as your
.ps1, with the same base file name; e.g.,foo.cmdalongsidefoo.ps1Add the following content to the
.cmdfile (add-NoProfileand-ExecutionPolicy Bypassas needed):@powershell.exe -NoExit -File "%~dpn0.ps1" %*
Shortcut-file approach:
See this answer for how to create such a shortcut file interactively.
See this answer for how to create shortcut files programmatically.
Solution 2:[2]
What is the output of running next command in Powershell?
Get-ExecutionPolicy
If the output you get is "Restricted", you can try creating a .cmd file situated in the same folder as the .ps1 file with the next content:
PowerShell.exe -ExecutionPolicy Bypass -File "your_ps1_name.ps1"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | jerkdavi |
