Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run powershell script from .ps1 file?

Tags:

powershell

cmd

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.

like image 916
Felipe Markakis Avatar asked Oct 23 '19 13:10

Felipe Markakis


People also ask

How do you execute a .ps1 file from CMD?

ps1 files are interpreted by PowerShell, the Command Prompt (CMD) cannot work with PowerShell scripts directly. If you would like to run a PowerShell script in CMD, you'll need to execute it by calling the PowerShell process with the -File parameter, as shown below: PowerShell -File C:\TEMP\MyNotepadScript. ps1.

How do I run a PowerShell script from a directory?

To run a script, type the full name and the full path to the script file. To run a script in the current directory, type the path to the current directory, or use a dot to represent the current directory, followed by a path backslash ( . \ ).

What type of file is a .ps1 PowerShell script file?

A PS1 file is a script, or "cmdlet," used by Windows PowerShell, a Windows shell program built on Microsoft's . NET Framework. It contains a series of commands written in the PowerShell scripting language.


1 Answers

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.

like image 195
Fler Avatar answered Sep 28 '22 21:09

Fler