Reputation: 663
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.
Upvotes: 2
Views: 3617
Reputation: 10019
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.
Upvotes: 1