Executing file from Admin CMD via CLI - windows

I am trying to execute a file via the CMD with Administrative privileges.
How can I open a cmd via command line with Administrative privileges.
I have to execute a script within a script.
powershell -ExecutionPolicy ByPass -noprofile -command "&{ start-process powershell -ArgumentList '-noprofile -File C:\scripts\install_ims.ps1' -verb RunAs}"
I have tried this in a bat file, but it doesn't work when executed within the script.

This should work fine for your purposes.
powershell -Command "Start-Process <filename> -Verb RunAs"
This is copy-pasted from some Batch files that I finally added to GitHub in the last few days if you have questions, that's probably the best place to go. https://github.com/Benny121221/Batch-BS

Related

Batch script to run Powershell script: Flashing window

System: Windows 10
Powershell Version: 5.1
Purpose: Run a powershell script from a batch file
Parameters: Directory, Filename, Server, Username, Password all being passed in as string encompassed in "" when called from command to handle the situation when there is a space (such as the Directory which currently has a space in)
The Powershell script works perfectly, it creates the credential and starts the RDP connection without issues. When calling from a batch file however the Powershell window flashes and closes immediately. Command Prompt window is run as Administrator.
I've tried using:
- pause
- -noexit
- code from https://blog.danskingdom.com/allow-others-to-run-your-powershell-scripts-from-a-batch-file-they-will-love-you-for-it/
if ($Host.Name -eq "ConsoleHost")
{
Write-Host "Press any key to continue..."
$Host.UI.RawUI.FlushInputBuffer() # Make sure buffered input doesn't "press a key" and skip the ReadKey().
$Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp") > $null
}
Clicking on the appearing Powershell window (To try get the select function to pause the window).
None of which have worked.
The code in question is:
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File """"%PowerShellScriptPath%"""" """"%server%"""" """"%username%"""" """"%password%""""' -Verb RunAs}";
Outside of this code no changes have been made to the system, the four speech marks were marked as required to pass through parameters and can be found under the blog post link above at the bottom just before the comments.
There is a high chance i'm using this incorrectly, I am a novice to batch and even newer to powershell. The batch scripts are being made as internal as possible, they need to be able to be used by a base install of Windows. They will eventually be migrated onto versions of Windows Server 2008 and up.
Is there anything that needs to be done with command prompt to allow it to run Powershell code?
Is the powershell code correct for the purpose i'm intending to use it for?
Is there any way, besides the ones listed, to view error, log information or pause the powershell window when run from a batch script?
Any input would be really appreciated!
Edit:
-NoExit variations:
Parent Call
PowerShell **-NoExit** -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File """"%PowerShellScriptPath%"""" """"%server%"""" """"%username%"""" """"%password%""""' -Verb RunAs}";
Nested call
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '**-NoExit** -NoProfile -ExecutionPolicy Bypass -File """"%PowerShellScriptPath%"""" """"%server%"""" """"%username%"""" """"%password%""""' -Verb RunAs}";
Parent and Nested
PowerShell **-NoExit** -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '**-NoExit** -NoProfile -ExecutionPolicy Bypass -File """"%PowerShellScriptPath%"""" """"%server%"""" """"%username%"""" """"%password%""""' -Verb RunAs}";
Variables set inside batch script as:
SET server=%~1
To remove the quotation marks I have also tried using:
SET server=%1
SET server=%server:"=%

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)

Powershell Unable to send Email through Batch file or Cmd prompt or Task Scheduler

I've been stuck at this same issue from past 5 days. The script has no issues and is sending email without any issues when executed from ISE directly.
#ECHO OFF C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noprofile -executionpolicy RemoteSigned -file D:\powershell\Fedex_Meter_Check1.ps1 PAUSE
Also tried
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noprofile -executionpolicy RemoteSigned -file D:\powershell\Fedex_Meter_Check1.ps1
There are no errors when executed from powershell.exe or cmd but no email. Please assist me on this.
Send-MailMessage -from 'Trax_FedEx ittraxsupport#xpo.com' -to 'Rahul `Rahul.Lalwani#xpo.com'<#'TRAX ittraxsupport#xpo.com' #> -subject 'Daily Rates `Check for FedEx Meters.' -body 'Perfect! All FedEx Meters Have Good Rates!'` `-Encoding Unicode -port 25 -smtpserver mailhost.cnf.com
I have had numerous issues running Powershell from BAT files in the past. One thing that I remember is that there are weird issues dealing with starting directory. From the command line, try changing the directory to the same directory as the powershell script, and then run it from there. I have this in a BAT file that works as long as the .bat and .ps1 share the same name.
#ECHO OFF
SET ThisScriptsDirectory=%~dpn0
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& '%~dpn0'"
PAUSE
Another solution I found in another old script is to run powershell.exe from the .bat or command line and give the .ps1 as a command to powershell instead of as a file.
powershell.exe -command "& {C:\filepath.ps1}"
I found a solution. Just adding Start-Sleep -Seconds 1 as the last line and it worked for me.

Wrapping a PowerShell Program in a Batch File and Using "Set-Location" Returns Root

The following code worked perfectly-
$ScriptLocation = Get-Location
Set-Location "$ScriptLocation"
...until I created a batch file to kick the script off. I understand that by opening the script via the batch file the location will be the root directory.
My question is, how can I set the current directory to the directory where the script is when launching the script from a batch file?
My batch file has the following code-
#ECHO OFF
SET ScriptDirectory=%~dp0
SET ScriptPath=%ScriptDirectory%FilePush_V0.1.ps1
PowerShell -NoProfile -ExecutionPolicy Unrestricted -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -File ""%ScriptPath%""' -Verb RunAs}";
set-Location $PSScriptRoot
cd..
See the following for your version of powershell.
whats-the-best-way-to-determine-the-location-of-the-current-powershell-script

Unable to execute multi-command in power shell

I'm working on power shell script using windows 2012 server, that do simple two functions
open powershell as an administrator
change the directory to c:\user\scrpt.bat
the code is:
powershell -Command "& {powershell Start-Process PowerShell -Verb RunAs; Set-Location C:\}
the problem is not when execute the first part, it's in the other part which is:
Set-Location C:\}
My question is there any way after running powershell as administrator execute the next command ?
I already tried to use semicolon ";" but no luck
If you want to change directory for the process you're spawning - use -WorkingDirectory option:
powershell -Command "& { Start-Process PowerShell -Verb RunAs -WorkingDirectory 'D:' }"

Resources