How to run PowerShell in CMD - windows

I'm trying to run a PowerShell script inside cmd command line. Someone gave me an example and it worked:
powershell.exe -noexit "& 'c:\Data\ScheduledScripts\ShutdownVM.ps1'"
But the problem is my PowerShell script has input parameters, so I tried, but it doesn't work:
powershell.exe -noexit "& 'D:\Work\SQLExecutor.ps1 -gettedServerName "MY-PC" ' "
The error is:
The term 'D:\Work\SQLExecutor.ps1 -gettedServerName "MY-PC" ' is not recognized as the name of a cmdlet, function,
How can I fix this problem?

You need to separate the arguments from the file path:
powershell.exe -noexit "& 'D:\Work\SQLExecutor.ps1 ' -gettedServerName 'MY-PC'"
Another option that may ease the syntax using the File parameter and positional parameters:
powershell.exe -noexit -file "D:\Work\SQLExecutor.ps1" "MY-PC"

I'd like to add the following to Shay Levy's correct answer:
You can make your life easier if you create a little batch script run.cmd to launch your powershell script:
run.cmd
#echo off & setlocal
set batchPath=%~dp0
powershell.exe -noexit -file "%batchPath%SQLExecutor.ps1" "MY-PC"
Put it in the same path as SQLExecutor.ps1 and from now on you can run it by simply double-clicking on run.cmd.
Note:
If you require command line arguments inside the run.cmd batch, simply pass them as %1 ... %9 (or use %* to pass all parameters) to the powershell script, i.e.
powershell.exe -noexit -file "%batchPath%SQLExecutor.ps1" %*
The variable batchPath contains the executing path of the batch file itself (this is what the expression %~dp0 is used for). So you just put the powershell script in the same path as the calling batch file.

Try just:
powershell.exe -noexit D:\Work\SQLExecutor.ps1 -gettedServerName "MY-PC"

Related

How can I set location to current working folder?

I have a powershell script located in "register" folder which I want to use to execute and exe file in "app" subfolder also located in "register" folder dynamically. Each time I run the script I get path not found error but I want the powershell to maintain the current working folder location so that it can work each time I copy to another drive.
Below is the review of my code
"cmd.exe /c PowerShell.exe -windowstyle hidden Start-Process '.\Register\App\record.exe'"
Thanks.
It's not clear where your command is being executed, but I believe the surrounding double quotes are causing everything within to be treated as the executable file name instead of just cmd.exe.
If I open Command Prompt at %UserProfile% and copy %SystemRoot%\system32\calc.exe to %UserProfile%\Register\App\record.exe, then the following work for me:
Command Prompt without surrounding double quotes: cmd.exe /c PowerShell.exe -windowstyle hidden Start-Process '.\Register\App\record.exe'
PowerShell without surrounding double quotes: PowerShell.exe -windowstyle hidden Start-Process '.\Register\App\record.exe'
Both of these...
Command Prompt with surrounding double quotes: "cmd.exe /c PowerShell.exe -windowstyle hidden Start-Process '.\Register\App\record.exe'"
PowerShell with surrounding double quotes: "PowerShell.exe -windowstyle hidden Start-Process '.\Register\App\record.exe'"
...result in...
The system cannot find the path specified.
Also, just in case it's not clear, you are attempting to run cmd.exe to run powershell.exe to run record.exe. At the very least, the cmd.exe /c is unnecessary; just run PowerShell directly.

Using a cmd command in powershell script?

I am trying to make a powershell script that automatically sets up this program and requires to use a cmd command to run do it.
I know that the cmd command work and I tried cmd.exe.
cmd.exe /c "java -jar fitnesse-standalone.jar -p 9090"
Error Message:
cmd.exe : The term 'cmd.exe' is not recognized
You can use start-process
Start-Process -FilePath "cmd.exe" -ArgumentList '/c "java -jar fitnesse-standalone.jar -p 9090"'
The /c and everything following it is just part of the one set of parameters being passed to cmd. If you want powershell to wait for the the Java app to close, add the -wait parameter.
There's also no real need to use CMD at all in this case (since your giving it /c to exit immediately anyway), you can call java directly:
Start-Process -FilePath "java.exe" -ArgumentList '-jar fitnesse-standalone.jar -p 9090'
and it should be the same.
Note: you'll need Java in your path or the current working directory, and fitnesse-standalone.jar in the current directory for either of these to work.

How to start PowerShell script from BAT file with proper Working Directory?

I'm trying to create bat script that can start PowerShell script named the same as bat file in proper working directotry.
This is what I got:
#ECHO OFF
PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%~dpn0.ps1""' -WorkingDirectory '%~dp0' -Verb RunAs}"
PAUSE
Passing working directory this way does not work.
How to make script that will pass proper working directroy and also command line arguments?
The -WorkingDirectory parameter doesn't work when using -Verb RunAs. Instead, you have to set the working directory by calling cd within a -Command string.
This is what I use: (cmd/batch-file command)
powershell -command " Start-Process PowerShell -Verb RunAs \""-Command `\""cd '%cd%'; & 'PathToPS1File';`\""\"" "
If you want to make a "Run script as admin" right-click command in Windows Explorer, create a new registry key at HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\Run with PowerShell (Admin)\Command, and set its value to the command above -- except replacing %cd% with %W, and PathToPS1File with %1 (if you want it to execute the right-clicked file).
Result: (Windows Explorer context-menu shell command)
powershell -command " Start-Process PowerShell -Verb RunAs \""-Command `\""cd '%W'; & '%1';`\""\"" "
EDIT: There's an alternative way to have the script be run as admin from Explorer, by using the "runas" sub-key: https://winaero.com/blog/run-as-administrator-context-menu-for-power-shell-ps1-files
If you want to run your script as admin from an existing powershell, remove the outer powershell call, replace %W with $pwd, replace %1 with the ps1 file-path, and replace each \"" with just ".
Note: The \""'s are just escaped quotes, for when calling from the Windows shell/command-line (it's quote-handling is terrible). In this particular case, just \" should also work, but I use the more robust \"" for easier extension.
See here for more info: https://stackoverflow.com/a/31413730/2441655
Result: (PowerShell command)
Start-Process PowerShell -Verb RunAs "-Command `"cd '$pwd'; & 'PathToPS1File';`""
Important note: The commands above are assuming that your computer has already been configured to allow script execution. If that's not the case, you may need to add -ExecutionPolicy Bypass to your powershell flags. (you may also want -NoProfile to avoid running profile scripts)
A workaround is to let the PowerShell script change the directory to it's own origin with:
Set-Location (Split-Path $MyInvocation.MyCommand.Path)
as the first command.
As per mklement0s hint: In PSv3+ use the simpler:
Set-Location -LiteralPath $PSScriptRoot
Or use this directory to open adjacent files.
$MyDir = Split-Path $MyInvocation.MyCommand.Path
$Content = Get-Content (Join-Path $MyDir OtherFile.txt)

Embedding PowerShell in batch

I want to run a few PowerShell commands through a batch file. Very similar question has been asked but I dont want to run a seperate shell file from a batch. Instead I want to embed PowerShell commands to a batch file.
When I try to run
powershell -command "&{$var = "something"}"
I get the following error:
something : The term 'something' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:10
&{$var = something}
CategoryInfo : ObjectNotFound: (something:String) [], CommandNotFoundException
FullyQualifiedErrorId : CommandNotFoundException
But if I run something like
powershell -command "&{echo "something"}"
Then everything is fine :/
Am I doing a syntax error or something? And please don't give answers like "Instead of using PowerShell commands use batch commands etc..."
Thanks in advance!
You can not use nested quotes when defining the value of a variable as a string. You may either use apostrophes instead of the nested quotes:
powershell -command "&{$var = 'something'; echo $var}"
... or escape the nested quotes:
powershell -command "&{$var = \"something\"; echo $var}"
Another example:
powershell -command "&{$var = 'one'+\" two\"; echo $var}"
Maybe a bit late but I program pure powershell scripts and embed the complete script in a .cmd file to bypass the execution policy setting. I have 2 variants pick the one you like. Both are one-liners that you put on the first line of the .cmd file. Starting from the second line you just program in pure powershell. No need for modifying anything in your powershell script.
Variant1:
#type "%0" | findstr /v "^#type \"%0\" | findstr /v " | PowerShell.exe -noprofile - & goto :eof
Varant2:
#powershell -command "(Get-Content '%0') | select -skip 1 " | powershell -noprofile - & goto :eof

The syntax of the command is incorrect running .ps1 from .bat

So I am trying to run a powershell script on windows server from a .bat file and I keep getting this error.
This is the only line I have in my script:
start /d "C:\Windows\SysWOW64\WindowsPowerShell\v1.0\" Powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "& 'C:\path\to\scripts\awesomescript.ps1'"
I have successfully run that command by itself in the cmd window by copying/pasting that whole line into the cmd prompt. The script has been tested as well.
However the same command will not work in the batch file and gives me the error "The syntax of the command is incorrect".
Does anyone happen to know why?
Update:
Thank you to the poster. I merely exited my old command prompt and started a new one. That old command and the previous posters worked. I hate those little things with windows.
Powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "& 'C:\path\to\script\script.ps1'"
I will be keeping the posters answer as the accepted.
Thank you!
Why are you putting path before powershell.exe? Seems to be working without this full path:
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& 'C:\Users\SE\Desktop\ps.ps1'"
Look there.

Resources