Powershell script not firing from batch file - powershell

I've been trying to launch a simple powershell script from a batch file. After looking online the advice is to set the policy using Set-ExecutionPolicy.
I've done this and using Get-ExecutionPolicy the policy has been changed.
However running this batch file results in an 'Open With' dialog rather than the execution of the script.
Batch:
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe ^&'./script.psl'
Powershell:
Write-Host "This is a message"
I have sampled on both Windows 7 and Server 2008 R2. Both have same result. What am I missing?

To run a script file from the command line, use the -file parameter of powershell.exe.
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -file './script.psl'

To run a script file from the *.cmd file , use the -file parameter of powershell.exe and double quotes:
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -file "./script.ps1"
When you will use only one quote in batch file you can expect powershell error like:
Processing -File ''./build.ps1'' failed because the file does not have
a '.ps1' extension. Specify a valid Windows PowerShell script file
name, and then try again.

Related

How to run powershell script from .ps1 file?

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

how do I make it easy for my parents to run this Powershell command?

I am not a programmer and my parents' Windows 10 PC tends to loose its start menu and cortana processes, resulting in start menu not showing up at all when the start icon is clicked.
I made a quick search and found + tested this Powershell command and it worked:
Get-AppxPackage | % { Add-AppxPackage -DisableDevelopmentMode -Register "$($_.InstallLocation)\AppxManifest.xml" -verbose }
I wish to turn this command into a shortcut/batchfile that executes the command and restarts the PC whenever the desktop icon is double clicked, in order to avoid explaining to my parents what to do to fix the problem. Can any one help me out please?
Thank you in Advance.
you can encode the command and put the whole thing into a single batch file (no .ps1 necessary)
details here
https://blogs.msdn.microsoft.com/timid/2014/03/26/powershell-encodedcommand-and-round-trips/
or you can use this function
https://github.com/gangstanthony/PowerShell/blob/master/Encode-Text.ps1
first, either use Get-Content or Get-Clipboard (copy your whole script to the clipboard) to encode your desired script
PS> Encode-Text (Get-Clipboard | out-string)
RwBlAHQALQBBAHAAcAB4AFAAYQBjAGsAYQBnAGUAIAB8ACAAJQAgAHsAIABBAGQAZAAtAEEAcABwAHgAUABhAGMAawBhAGcAZQAgAC0ARABpAHMAYQBiAGwAZQBEAGUAdgBlAGwAbwBwAG0AZQBuAHQATQBvAGQAZQAgAC0AUgBlAGcAaQBzAHQAZQByACAAIgAkACgAJABfAC4ASQBuAHMAdABhAGwAbABMAG8AYwBhAHQAaQBvAG4AKQBcAEEAcABwAHgATQBhAG4AaQBmAGUAcwB0AC4AeABtAGwAIgAgAC0AdgBlAHIAYgBvAHMAZQAgAH0ADQAKAA==
then you can use that in your batch file like so
powershell -encodedcommand RwBlAHQALQBBAHAAcAB4AFAAYQBjAGsAYQBnAGUAIAB8ACAAJQAgAHsAIABBAGQAZAAtAEEAcABwAHgAUABhAGMAawBhAGcAZQAgAC0ARABpAHMAYQBiAGwAZQBEAGUAdgBlAGwAbwBwAG0AZQBuAHQATQBvAGQAZQAgAC0AUgBlAGcAaQBzAHQAZQByACAAIgAkACgAJABfAC4ASQBuAHMAdABhAGwAbABMAG8AYwBhAHQAaQBvAG4AKQBcAEEAcABwAHgATQBhAG4AaQBmAGUAcwB0AC4AeABtAGwAIgAgAC0AdgBlAHIAYgBvAHMAZQAgAH0ADQAKAA==
You could execute the PowerShell script via a batch file.
Batch file:
set powerscriptPath=C:\Example.ps1
PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%powerscriptPath%""' -Verb RunAs}"
This will bypass the execution policies on the computer allowing the script to run in Administrator mode too. NOTE: You will need to edit the powerscriptPath to point to your PowerShell script location, I just used C:\Example.ps1 as an example.
You will want to add Restart-Computer -Force to the end of your PowerShell script to restart the computer
Get-AppxPackage | % { Add-AppxPackage -DisableDevelopmentMode -Register "$($_.InstallLocation)\AppxManifest.xml" -verbose }
Restart-Computer -Force
Make a bat file which executes powershell with that file. Then add a shortcut to the bat file
I am really unsure why you would run a batch file just to call a powershell script! Talk about hokey approaches to a non-problem.
To call a powershell script is really no different than calling a batch script:
It's simply path to PowerShell, and the script path as a parameter:
"%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe" "C:\users\austinfrench\desktop\example.ps1"
You can also use the exact same format as the target for a desktop shortcut.

How to execute PowerShell script in MoveIT central?

I have a bat file include command em32\WindowsPowerShell\v1.0\powershell.EXE -NoLogo -NoProfile -Command c:\temp\GL_Format_Update.ps1. Then used command line App in MoveIT central to execute bat file. The script can't produce the output file as expected. Command can be run in CMD window successfully. It seems like MoveIT service owner can't execute PowerShell script.
I had a similar issue and found that simply putting the entire command into the CommandLineApp_AppPath was throwing an error. By breaking it up into the path to powershell and the arguments to powershell, I was able to successfully call and execute my script. My script also took 3 parameters.
Create a task with a process. Select the built-in script "Command Line App". Set the parameters as follows:
CommandLineApp_AppPath = C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.EXE
CommandLineApp_AppParms = -NoLogo -NoProfile -ExecutionPolicy Bypass -Command "E:\PowerShell\CreateManifest.ps1 -Folder \\mdcvmsfms11u\DataTransfer\BFClientGateway\Test\Download\2129\PPfAandDP -ManifestName MS_CONTROL_ -OutputType FULL"

Need to call powershell script from batch file

I have a batch file which is in a folder called script. The script folder also contains folder called powershell which has a script called IE-Settings.ps1.
I want to execute the powershell script from the batch file and I am unable to give powershell script path in the command. What I tried is
call %windir%\system32\WindowsPowerShell\v1.0\powershell.exe -File "& '%~dp0IESettings\IE-Settings.ps1'"
But it doesn't recognize the path
call is for running other batch files in a way that they return to the current batch file after they terminate, and per your question the subdirectory name is powershell, not IESettings. Also, when using the parameter -File you just specify the path to the file.
powershell.exe -File "%~dp0powershell\IE-Settings.ps1"
The call operator (&) is used when running PowerShell code via the -Command parameter, e.g.:
powershell.exe -Command "& { Write-Host 'foo' }"

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:
One command line that opens PowerShell, executes script and closes PowerShell (this would be used for a global build-routine)
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.
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
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.
Run Script Automatically From Another Script (e.g. Batch File)
As Matt Hamilton suggested, simply create your PowerShell .ps1 script and call it using:
PowerShell C:\Path\To\YourPowerShellScript.ps1
or if your batch file's working directory is the same directory that the PowerShell script is in, you can use a relative path:
PowerShell .\YourPowerShellScript.ps1
And before this will work you will need to set the PC's Execution Policy, which I show how to do down below.
Run Script Manually Method 1
You can see my blog post for more information, but essentially create your PowerShell .ps1 script file to do what you want, and then create a .cmd batch file in the same directory and use the following for the file's contents:
#ECHO OFF
SET ThisScriptsDirectory=%~dp0
SET PowerShellScriptPath=%ThisScriptsDirectory%MyPowerShellScript.ps1
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& '%PowerShellScriptPath%'"
Replacing MyPowerShellScript.ps1 on the 3rd line with the file name of your PowerShell script.
This will allow you to simply double click the batch file to run your PowerShell script, and will avoid you having to change your PowerShell Execution Policy.
My blog post also shows how to run the PowerShell script as an admin if that is something you need to do.
Run Script Manually Method 2
Alternatively, if you don't want to create a batch file for each of your PowerShell scripts, you can change the default PowerShell script behavior from Edit to Run, allowing you to double-click your .ps1 files to run them.
There is an additional registry setting that you will want to modify so that you can run scripts whose file path contains spaces. I show how to do both of these things on this blog post.
With this method however, you will first need to set your execution policy to allow scripts to be ran. You only need to do this once per PC and it can be done by running this line in a PowerShell command prompt.
Start-Process PowerShell -ArgumentList 'Set-ExecutionPolicy RemoteSigned -Force' -Verb RunAs
Set-ExecutionPolicy RemoteSigned -Force is the command that actually changes the execution policy; this sets it to RemoteSigned, so you can change that to something else if you need. Also, this line will automatically run PowerShell as an admin for you, which is required in order to change the execution policy.
Source for Matt's answer.
I can get it to run by double-clicking a file by creating a batch file with the following in it:
C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe LocationOfPS1File
you can use this command :
powershell.exe -argument c:\scriptPath\Script.ps1