Unable to execute multi-command in power shell - windows

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:' }"

Related

Elevate rights in current directory with PowerShell

For example I'm in C:\Users\User\Desktop\Tools and I'm trying to stay here as admin.
I tried this way, gluing together different commands:
"C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -noexit" & -windowstyle hidden -Command Start-Process powershell -ArgumentList '-NoExit', '-Command cd %V' -Verb runAs""
The PATH changes to C:\WINDOWS\system32 why? How to elevate rights in current directory via simple command?
Use $PWD from the calling process to change the location on startup:
Start-Process powershell -ArgumentList '-NoExit', "-Command cd '$pwd'; & .\actual\script\you\want\to\run.ps1" -Verb runAs

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:"=%

Executing file from Admin CMD via CLI

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

How to QUIETLY start Powershell.exe using different credentials (without getting prompted for username/password)?

I've spent more time on this that I'd like to admit. I'm looking for powershell code that will quietly start a new PowerShell instance (in the existing PowerShell Window) using different credentials.
The best I can come up with is extremely clunky... popping up two different Powershell Windows on my screen before finally giving me a prompt. Apparently, the -NoNewWindow argument doesn't prevent the opening of any new PowerShell windows.
My VERY clunky code:
Start-Process powershell.exe -Credential $DomainAdmin -WorkingDirectory $env:windir -NoNewWindow -ArgumentList "Start-Process powershell.exe -Verb runAs"
If there is a way to "Runas" Powershell.exe from a desktop shortcut (and saving the username/password). I'd also be happy with that. Below, is the code I attempted to make. However, there seems to be a bug that keeps giving me the error, "267: The directory name is invalid"
Batch file that doesn't work:
runas.exe /savecred /env /noprofile /user:MKA "powershell.exe -noprofile -command \"start-process -WorkingDirectory c:\temp powershell -verb RunAs\""
A solution would be greatly appreciated.
To run as user MKA, create a shortcut with this in Target window:
C:\Windows\System32\runas.exe /User:MKA /savecred C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
To hide a PowerShell console window, you can put this code at the top of the script being executed. which is my favoured solution in this StackOverflow post.
add-type -name win -member '[DllImport("user32.dll")] public static extern bool ShowWindow(int handle, int state);' -namespace native
[native.win]::ShowWindow(([System.Diagnostics.Process]::GetCurrentProcess() | Get-Process).MainWindowHandle, 0)
The post discusses other ways that may be more suitable for you.

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)

Resources