How to execute a powershell script using a batch file? [duplicate] - powershell

This question already has answers here:
Why is no string output with 'echo %var%' after using 'set var = text' command in cmd? [duplicate]
(2 answers)
Closed 3 years ago.
I have powershell script which I am trying to execute using a batch file. I am not sure how to direct the .bat file to the powershell script without hardcoding the full path.
Both the script and .bat files are stored in the same folder. I've got this so far but it doesn't appear to do anything.
#ECHO OFF
REM PowerShell -WindowStyle Hidden -NoProfile....
SET ScriptDirectory = %~dpn0
SET ScriptPath = %ScriptDirectory% || "/" || counterscript.ps1
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& '%ScriptPath%'";

I don't think you can. You can only hard code the path. Maybe there is some way that you can do it, but I don't know any other ways rather than hard coding. You could hard code the file name though.

Related

Bat file that opens a powershell file how to get the right directory? [duplicate]

This question already has an answer here:
Unable to find file path of powershell file from a .bat file only when running as administrator
(1 answer)
Closed 2 months ago.
Have made a bat file thats point to a powershell and open this my problem is i need it on severel Computers and cant change every time the Script Path
what i made is this
cd %USERPROFILE%\Downloads\Pytho\Brd\ & REM cdinto the folder of update bat file
powershell -ExecutionPolicy Bypass -Command "& '%USERPROFILE%\Downloads\Pytho\Brd\updatebrewdall.ps1'"
this is working but i cant change path in every machines so is there a automatic solution of it??
i start this with task Schedule to let Task Schedule know were the file is i put in the cd comment
i cant open via arguments i need to open it in the real folder to let the update file find the rest needed files
some gave me advice i think this is better
pushd "%~dp0"
%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File updatebrewdall.ps1
popd

Put a Powershell Ouput into a variable inside a batch script [duplicate]

This question already has answers here:
How to set commands output as a variable in a batch file [duplicate]
(9 answers)
Closed 2 years ago.
I'm making following batch script
set FileVersion = powershell (Get-Command C:\Tool.exe).FileVersionInfo.ProductVersion
echo %FileVersion%
I'd like retrieve attribute 'Product Version' of file C:\Tool.exe. To do that I use a powershell command and I want save that value to a variable called 'File Version' and later print out it, but it doesnt works!
Can you help me?
For some yet to be understood logic, a FOR loop must be used.
FOR /F "delims=" %%A IN ('powershell (Get-Command C:\Tool.exe).FileVersionInfo.ProductVersion') DO (SET "FileVersion=%%~A")

%temp% etc not working

I have the below that is used as a batch file that launches powershell (too long to go over but it is used in another script).
Anyway, I noticed the %systemroot%\temp and %systemroot% does not work.
Any idea how I can fix this?
%systemroot%\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Unrestricted -File %SystemRoot%\TEMP\ROFS\testing_script_log.ps1
Thanks,
If you are executing that line from PowerShell rather than from CMD, you can use the PowerShell environment variable syntax:
PS C:\> & "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe"
You can use [Environment]::ExpandEnvironmentVariables to expand environment variables within a string the old-fashioned way.
$s = '%systemroot%\temp'
[Environment]::ExpandEnvironmentVariables($s)
Successfully verified with below code C#.
//file location - User Variables
string fileLocation = Environment.GetEnvironmentVariable("AZURE_FILE_PATH", EnvironmentVariableTarget.User);
//file location - System Variables
string fileLocation = Environment.GetEnvironmentVariable("AZURE_FILE_PATH", EnvironmentVariableTarget.Machine);
On Powershell script
& "D:\Visual_Studio_Workspace\AzureUpload\AzureUpload\bin\Debug\AzureUpload.exe"
AzureUpload.exe -- contain the above code C# code as Console application (Visual_Studio_Workspace\AzureUpload\AzureUpload\bin\Debug{.exe file location})

Execute powershell script inside batch file [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to execute powershell commands from a batch file?
I want to execute the below powershell statement from a batch file with out creating a ps1 file
if([System.Diagnostics.EventLog]::SourceExists("dfgdjg") -eq $false){[System.Diagnostics.EventLog]::CreateEventSource("dfgdjg","dfgdjgLogs");}
else{write("Event Log already exists");}
Is it possible to do so?
In general you can do:
#powershell -command "yourpowershellcommand"
You can use powershell.exe directly, but I would recomment you to use the above form of #powershell
The command line help powershell.exe /? covers this:
-Command
Executes the specified commands (and any parameters) as though they were
typed at the Windows PowerShell command prompt, and then exits, unless
NoExit is specified. The value of Command can be "-", a string. or a
script block.
If the value of Command is "-", the command text is read from standard
input.
If the value of Command is a script block, the script block must be enclosed
in braces ({}). You can specify a script block only when running PowerShell.exe
It shows an example at the end:
EXAMPLES
PowerShell -PSConsoleFile SqlSnapIn.Psc1
PowerShell -version 1.0 -NoLogo -InputFormat text -OutputFormat XML
PowerShell -Command {Get-EventLog -LogName security}
PowerShell -Command "& {Get-EventLog -LogName security}"

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