How to run powershell script from .ps1 file?

52,766

Solution 1

Create a batch file which points at your .ps1 file. You may be required to run the batch file with elevated permissions, depending on your access levels (the logged in account will be used for execution).

E.g.:

Powershell.exe -executionpolicy remotesigned -File  "C:\Path\script.ps1"

If this still isn't working, please execute your batch file via CMD (copying the path, wrapped in quotation marks, into CMD) and let me know the response.

Solution 2

There are several ways to run a .ps1 file. The simplest way is to right-click the file and choose 'Run with PowerShell'.

As others have suggested, you can also run your .ps1 file using powershell.exe either in command prompt or from a BATCH or CMD file. As follows:

powershell.exe -File C:\Script.ps1

If you are still having problems it could be the execution policy. For this, simply add -ExecutionPolicy Bypass to your command as follows:

powershell.exe -File C:\Script.ps1 -ExecutionPolicy Bypass

To change your execution policy you can use:

Set-ExecutionPolicy
Share:
52,766

Related videos on Youtube

Author by

Felipe Markakis

Updated on July 13, 2022

Comments

  • Felipe Markakis 5 months

    I'm trying to automate the execution of a simple PS script (to delete a certain .txt file). Obviously, I'm new to powershell :) When I run the code in shell, it works flawless. But when i save the code as a .ps1 and double-click it (or execute it remotely), it just pops up a window and does nothing.

    I've tried to save the code as a .bat file and execute it on Windows command line, but it behaves the same: Works by coding directly on prompt, but doesn't Works by executing the .bat file.

    $Excel = New-Object -ComObject Excel.Application
    $Workbook = $Excel.Workbooks.Open('H:\codes\test1.xlsm')
    $workSheet = $Workbook.Sheets.Item(2)
    $str_name = $WorkSheet.Cells.Item(2,1).Text
    Remove-Item -Path "H:\text files\$str_name.txt" -Force
    

    I expected it to work by double-clicking it, just as it does by running in shell, or in the command line, but i can't figure out why it doesn't.

    • Mathias R. Jessen
      Mathias R. Jessen about 3 years
      powershell.exe -File "C:\your\script.ps1"
    • Patrick
      Patrick about 3 years
      I think you have some troubles with that: About Execution Policies
  • Felipe Markakis about 3 years
    Yep, it Works!!
  • mklement0
    mklement0 about 3 years
    Nice; worth noting that the Run with PowerShell shortcut-menu command will not keep the window in which the script runs open, so unless the script is designed to keep it self open with, say, a pause (Read-Host) statement at the end, you may not get to see the results.

Related