Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set up PowerShell Script for Automatic Execution

I have a few lines of PowerShell code that I would like to use as an automated script. The way I would like it to be able to work is to be able to call it using one of the following options:

  1. One command line that opens PowerShell, executes script and closes PowerShell (this would be used for a global build-routine)
  2. A file that I can double-click to run the above (I would use this method when manually testing components of my build process)

I have been going through PowerShell documentation online, and although I can find lots of scripts, I have been unable to find instructions on how to do what I need. Thanks for the help.

like image 403
Yaakov Ellis Avatar asked Aug 27 '08 07:08

Yaakov Ellis


People also ask

Can we set PowerShell script to run automatically?

Windows makes it possible to schedule PowerShell scripts to run at a predetermined time. The mechanism of choice for automating PowerShell scripts is the Windows Task Scheduler.

Can I run a PowerShell script from Task Scheduler?

Microsoft Windows Task Scheduler can run PowerShell scripts, but to do so you will first need to specify it as an argument to PowerShell. Hopefully this article will help you automate many of your daily activities on your Windows system.


2 Answers

From http://blogs.msdn.com/b/jaybaz_ms/archive/2007/04/26/powershell-polyglot.aspx

If you're willing to sully your beautiful PowerShell script with a little CMD, you can use a PowerShell-CMD polyglot trick. Save your PowerShell script as a .CMD file, and put this line at the top:

@PowerShell -ExecutionPolicy Bypass -Command Invoke-Expression $('$args=@(^&{$args} %*);'+[String]::Join(';',(Get-Content '%~f0') -notmatch '^^@PowerShell.*EOF$')) & goto :EOF

If you need to support quoted arguments, there's a longer version, which also allows comments. (note the unusual CMD commenting trick of double @).

@@:: This prolog allows a PowerShell script to be embedded in a .CMD file.
@@:: Any non-PowerShell content must be preceeded by "@@"
@@setlocal
@@set POWERSHELL_BAT_ARGS=%*
@@if defined POWERSHELL_BAT_ARGS set POWERSHELL_BAT_ARGS=%POWERSHELL_BAT_ARGS:"=\"%
@@PowerShell -ExecutionPolicy Bypass -Command Invoke-Expression $('$args=@(^&{$args} %POWERSHELL_BAT_ARGS%);'+[String]::Join(';',$((Get-Content '%~f0') -notmatch '^^@@'))) & goto :EOF
like image 104
Jay Bazuzi Avatar answered Sep 18 '22 00:09

Jay Bazuzi


Save your script as a .ps1 file and launch it using powershell.exe, like this:

powershell.exe .\foo.ps1

Make sure you specify the full path to the script, and make sure you have set your execution policy level to at least "RemoteSigned" so that unsigned local scripts can be run.

like image 42
Matt Hamilton Avatar answered Sep 20 '22 00:09

Matt Hamilton