Home > other >  Run PowerShell command(s) outside of PowerShell
Run PowerShell command(s) outside of PowerShell

Time:04-29

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

CodePudding user response:

You have two options:

  • Either: Make .ps1 files 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 .ps1 files 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 .ps1 file, create a companion shortcut file (.lnk) or batch file (.cmd) that launches it, via PowerShell's CLI (powershell.exe for Windows PowerShell, pwsh.exe for 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.cmd alongside foo.ps1

      • Add the following content to the .cmd file (add -NoProfile and -ExecutionPolicy Bypass as 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.

CodePudding user response:

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"
  • Related