Monday, December 16, 2013

Pass arguments to powershell in batch file


Sometimes you want to run Powershell script without .ps1 files (directly from batch file).
My last post was about that but now I'll show you how to pass arguments to your scriptblock.
It is relatively easy but not easily found from internet.

Here goes:
powershell -Command "& { Write-host $args[0] }" "ARGUMENTS_HERE"

The output should be "ARGUMENTS_HERE".

Real life example:
I needed this for simple script that is fired from another batch file with arguments of files, that need to be scanned for lines. If lines are found, e-mail is sent.

powershell -Command "& { Get-Childitem -Path $args[0] -Filter $args[1] | foreach { $len = get-content $_.FullName | measure-object -char; if ($len.Characters -gt 0) { Send-MailMessage  -SmtpServer 'MAILSERVER HERE' -From 'SENDER HERE' -To 'RECEIVER HERE' -Subject $( 'Errors in log: ' + $($_.Name) ) } } }" "PATH HERE" "FILTER HERE"


It has been long since I posted anything here, I should make a better use for this blog as I search for my own code snippets pretty often :)

Merry Christmas!