I'm not really good at PS so I decided to ask for some advice.
I have a VBA script that uses Get-DhcpServerv4Lease in a PS command to query the DHCP server (as a domain admin user) for a given Scope and arrange the data returned into Excel.
strCommand = "%SystemRoot%\system32\WindowsPowerShell\v1.0\Powershell.exe start-job -credential <domain>\" & TheAdminUser & " -ScriptBlock{Get-DhcpServerv4Lease -ComputerName '<DHCP server>' -ScopeId " & TheScope & "} | wait-job | receive-job"
Set WshShell = CreateObject("WScript.Shell")
Set WshShellExec = WshShell.Exec(strCommand)
strOutput = WshShellExec.StdOut.ReadAll
The script was working perfectly before, now for some unknown reason it's no longer functioning.
Tried to manually run the command in PS and realized it is now only working if I run PS as administrator (works even as local admin), else it returns the following error:
[localhost] An error occurred while starting the background process. Error reported: The directory name is invalid.
+ CategoryInfo : OpenError: (localhost:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : -2147467259,PSSessionStateBroken
Any advice what might be the problem or where could I start looking for a solution?
Update:
In the meantime I found a different workaround that fixes the original code I used.
Adding [environment]::CurrentDirectory='C:\Windows\System32\WindowsPowerShell\v1.0'; makes it run again without the error.
strCommand = "%SystemRoot%\system32\WindowsPowerShell\v1.0\Powershell.exe "[environment]::CurrentDirectory='C:\Windows\System32\WindowsPowerShell\v1.0';start-job -credential <domain>\" & TheAdminUser & " -ScriptBlock{Get-DhcpServerv4Lease -ComputerName '<DHCP server>' -ScopeId " & TheScope & "} | wait-job | receive-job"
The answers were very useful, maybe alternative workarounds for others, and got me closer to understand Powershell better.
Any advice what might be the problem
The problem is a bug in the Start-Job cmdlet that affects both Windows PowerShell (v5.1, the latest and final version) and PowerShell (Core) v6+ (albeit with different symptoms, still as of PowerShell Core 7.2.0-preview.8 - see GitHub issue #7172).
In Windows PowerShell, the background process uses a (fixed) working directory in the calling user's home-directory tree (the Documents folder), which the user whose credentials are passed to -Credential is not allowed to access, causing the error you saw - and there's no way to specify a different working directory.
Start-Job -Credential does work if your session is elevated, i.e. running with admin privileges, in which case the target user's Documents folder is switched to. Given that the standard runas.exe utility can invoke commands as a different user even from non-elevated sessions, there should be no need for this requirement, however.
Also - as you have discovered yourself - there is a workaround:
If you explicitly set the process-level working directory (which is distinct from PowerShell's) to one the target user is permitted to access, Start-Job -Credential works; for instance, you can use C:\ or $env:SYSTEMROOT\Windows32 (the latter is what runas.exe uses); a quick example (replace otheruser with the username of interest):
[Environment]::CurrentDirectory = 'C:\' # set process-level working dir.
Start-Job -Credential (Get-Credential otheruser) { whoami } |
Receive-Job -Wait -AutoRemoveJob
PowerShell (Core) now makes the background process inherit the caller's working directory (which the caller could set to a directory accessible by the target user) and also has a -WorkingDirectory parameter, but neither approach solves the problem with -Credential as of PowerShell Core 7.2.0-preview - even if you run with elevation (and the above workaround doesn't help either).
Based on the update to your question, it seems the workaround solved your problem, implying that you do not require the operation running with the domain user identity to be elevated; the following may still be of interest for use cases where elevation is required.
If you need to run the operation that uses a different user identity with elevation (with admin privileges):
Launching an elevated (run as admin) process is something Start-Job -Credential fundamentally cannot provide.
The only (PowerShell-native) way to launch an elevated process is via Start-Process -Verb RunAs.
Note: Using Start-Process means that the launched process' output cannot be captured directly by the caller, and instead requires sending the output to files via the --RedirectStandardOutput and -RedirectStandardError parameters, which the caller - assuming termination of the process is waited for - can later read.
Therefore, try the following:
strCommand = "%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -c Start-Process -Wait -Verb RunAs powershell.exe \""-c Get-DhcpServerv4Lease -ComputerName '<DHCP server>' -ScopeId " & TheScope & "\"""
Note:
Another call to powershell.exe is required, launched with elevation (-Verb RunAs), synchronously (-Wait), which then performs the Get-DhcpServerv4Lease call in the foreground.
Because Start-Process -Verb RunAs invariably launches the process in a new window, you may want to hide that window too, by adding -WindowStyle Hidden to the Start-Process call. Conversely, if you do want to see that window, you may want to hide the intermediate window that launches the elevated one, using VBA features.
Note: I've added -c (-Command) to the powershell.exe calls for conceptual clarity; while this parameter is implied in powershell.exe (Windows PowerShell), in pwsh.exe, the PowerShell (Core) equivalent, the default is now -f (-File).
Also note the need to \-escape the embedded " chars. (escaped for VBA as ""), so that the PowerShell CLI retains them as part of the command to execute after command-line argument parsing.
As with your original attempt, this will prompt for a password, and if the calling user doesn't have administrative privileges in principle, an administrator's username will have to be entered too. Note that this prompt cannot be prevented (unless you turn UAC off, which is ill-advised).
The admin username to use for elevation cannot be passed, because -Verb RunAs is mutually exclusive with -Credential. The logic of -Verb RunAs is such that if the current user is an admin user (in principle), it is invariably used for the elevated session, and you're only presented with a Yes/No confirmation dialog. Thus, if you need a different admin user, such as a domain admin, this won't work - see below. (Only if the calling user is not an admin user does the UAC prompt ask for a username and password explicitly).
If you need to run the elevated session with a given admin user account:
Unfortunately, this requires an even more deeply nested command, with additional pitfalls:
In essence, you need to first call Start-Process -Credential to create an (of necessity) non-elevated session with the target user, which then allows you to call Start-Process -Verb RunAs to create an elevated session for that user.
Caveat: This requires you to answer two prompts: first, you need to enter the password to start the non-elevated session for the admin user, and then you need to answer the Yes/No UAC prompt to confirm the intent to start an elevated session for that user.
A Set-Location C:\ command is incorporated, to ensure that the working directory is valid for the target user (in the initial non-elevated session).
Using Start-Process -Wait in order to wait for termination of a process started with a different user (-Credential) inexplicably fails due lack of permissions when invoked from a non-elevated session; the workaround is to use (Start-Process -PassThru ...).WaitForExit().
To simplify quoting, only '...' quoting (escaped as ''...'' in the nested call) is used - therefore, the commands themselves mustn't contain ' chars.
This leads to the following monstrosity.
' Assumes that the following variables are defined:
' TheAdminUser, TheComputerName, TheScope
strCommand = "%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -c Set-Location C:\; (Start-Process -WindowStyle Hidden -PassThru -Credential " & TheAdminUser & " powershell.exe ' -c Start-Process -Wait -Verb RunAs powershell.exe '' -c Get-DhcpServerv4Lease -ComputerName " & TheComputerName & " -ScopeId " & TheScope & " '' ').WaitForExit()"
Note: For troubleshooting, precede the -c argument(s) with -noexit to keep the PowerShell session(s) open.
Alternative, with prior setup:
As Joel Coehoorn points out, one way to allow a non-admin user to execute a preconfigured operation - only - with administrative privileges is to set up a scheduled task that runs with admin credentials and performs the desired operation, which non-admin users can then invoke on demand.
This would obviate the need for a password altogether, but be sure that the operation is truly safe for non-admin users to perform.
Note: Having a scheduled task run by a non-admin user / from a non-elevated process can fail under certain circumstances - though it does work in the scenario at hand, according to Joel; as he notes in reference to this Server Fault post:
I think part of the problem was trying to run as SYSTEM rather than a specific privileged user in elevated mode. It also talks about contexts like SCCM and startup, where certain registry keys are not available, and the powershell code to invoke the task may also have changed.
You should be able to use Start-Process -RunAs for the powershell.exe command and it will elevate. Note that this will trigger UAC if the vBA process isn't already elevated.
The kicker is that if you are trying to self-elevate from a different process, Start-Process is a PowerShell cmdlet so you will need to basically run PowerShell to run another elevated PowerShell session. The command will look something like this:
powershell.exe -Command "Start-Process -Wait -Verb RunAs powershell.exe '-Command ""YOUR ELEVATED CODE HERE""'"
You can test this with the following command in Command Prompt that will output "hello", wait for a key-press, then exit:
powershell.exe -Command "Start-Process -Wait -Verb RunAs powershell.exe '-Command ""echo hello; cmd /c pause""'"
Note that this is how you would invoke the command from the command line, whether PowerShell or CMD. You may need to tweak the escape sequences if calling from another language.
You should also make use of the -Command parameter when invoking powershell.exe or pwsh from somewhere else and want to exit the session once the command is complete, or the -File parameter for the same but it's a script.
You also need to make use of the -Wait parameter when you call Start-Process or else it won't block. This is antithesis to the general executable invocation pattern that non-GUI programs usually don't need the -Wait parameter to block until the process exits.
Related
Trying to open CMD in elevated mode and running powershell script.
powershell -Command "Start-Process cmd \"/k "PowerShell -NoProfile -ExecutionPolicy Bypass -file ""C:\WIM_Creation.ps1 ""hello"" V7.0E V9.0A""\" -Verb RunAs"
Note: Problem is in order to open CMD in elevated mode from current CMD window it redirect to new window in elevated mode and run the command. due to which output is not getting captured in primary CMD window. HENCE NOT GETTING OUTPUT CAPTURED IN JENKINS.
Need to open elevated CMD in current CMD.
An elevated process launched from a non-elevated one invariably runs in a new window.
A non-elevated process that launches an elevated one cannot capture its output.
The workaround is to make the elevated process itself capture its output, by redirecting it to a file.
Unless the program running in the elevated process itself happens to support that, you must call it via a shell, i.e. launch the shell elevated, and pass it a command line that invokes the target executable with a shell redirection (>)
To make your code work:
You need to add -Wait to your Start-Process -Verb RunAs call to ensure that it waits for the elevated process to terminate.
This precludes using cmd /k in automated execution, as it would create a cmd.exe session that stays open until closed by the user.
While you could use cmd /c, there's no reason to create another cmd.exe process - just call the nested powershell instance directly.
*>$env:TEMP\out.txt is used to capture the elevated powershell instance's output in a temporary file, whose content is then output by the outer (non-elevated) instance.
Note:
The file's content is only output after the elevated process has exited, so you won't get realtime feedback; while implementing the latter is possible, it would significantly complicate the solution.
Using fixed file name out.txt creates the potential for name collisions; ruling those out would require more work.
powershell -Command "Start-Process -Verb RunAs -Wait powershell '-NoProfile -ExecutionPolicy Bypass -file C:\WIM_Creation.ps1 \"hello\" V7.0E V9.0A *>$env:TEMP\out.txt'; Get-Content $env:TEMP\out.txt; Remove-Item $env:TEMP\out.txt"
Note that I've made some corrections to the use of " quotes in your original command, based on what I think you're trying to do.
My user account does not have any special privileges. I try to start powershell as user with administrator privileges:
Start-Process -Credential $c -FilePath powershell
Unfortunately, while indeed another window opens, there must be some strange correlation between both processes: they cannot be practically used.
When I leave out the credential param, both windows appear to be independent.
BTW, I cannot use runas, since it doesn't support PSCredentials and, as far as I can tell, "verb" will not help, as my default user cannot elevate.
I would like to find a way to find out if a process is running as elevated or not using Powershell.
Use Case: Being able to run control panel tasks with elevated privilage as local domain user e.g. Add or Remove programs.
Any help will be appreciated.
#Start add or remove as admin
start-process appwiz.cpl -verb runas
#Check if path exists. Answer is Yes, so process is NOT elevated
get-wmiobject -class win32_process | select-object -properties name, path
These are the two usual options:
Use the #requires -RunAsAdministrator line in your script (requires PowerShell 3.0 or later). If you use this line at the top of your script, it will throw a terminating error and won't execute if the current process isn't elevated.
Use code like the following to detect whether the current process is elevated:
$IsElevated = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
I'm writing a small PowerShell script launched from a batch file which will change a Standard User (when logged in) to a Local Administrator. It needs to be fully automated, and I know the given machine's Admin credentials. I figured that I would begin by passing the Admin credentials, but I'm having trouble getting around the Password prompt (since it requires user action). So far I have this.
Start-Process powershell.exe -Credential "Domain\Username" -NoNewWindow -ArgumentList "Start-Process powershell.exe -Verb runAs"
$wshell = New-Object -ComObject wscript.shell;
$wshell.AppActivate('Windows PowerShell Credential Request')
Sleep 1
$wshell.SendKeys('SuperSecret')
Sendkeys isn't working as far as I can tell, and neither does -Password when I try to pass it as an argument. I'm not sure if I should pursue this method or if there is other logic that will let me assume a Local Administrator without being prompted to begin with. Also, this will be run on more than one machine, however the credentials are constant since they will all be on the same network.
So all I want to do is create a shortcut script that when clicked will restart the network adapter. The issue is that it needs to be ran on an account with basically no privileges so I need to have it run elevated and as a different user (admin account).
I cant quite figure out the right way to do this and its driving me nuts. This is what I have so far:
$username = "Domain\User"
$password = "Password"
$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList #($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
start-process powershell -Credential ($credentials) -ArgumentList '-ExecutionPolicy unrestricted -noprofile -verb runas -inputformat text -command "{restart-netadapter -InterfaceDescription "Dell Wireless 1538 802.11 a/g/n Adapter" -Confirm:$false}"'
It will open a new powershell window but the command fails to run. It works fine on its own in an elevated powershell prompt. I found out at one point that even though I was calling the powershell using an admin account it wasn't an elevated powershell so I added the -verb runas but it still isn't working.
This really shouldn't be that hard, but I am not a powershell guru by any means. Any help is much appreciated. Thanks!
In my opinion, the best way to do this is to create a scheduled task that runs the script as a privileged account. Get rid of the embedded credentials altogether.
The limited account then only needs to be able to start the task.
Since the code to restart the adapter is a one-liner, you don't need even need to put it in a script file, so you don't need to worry about execution policy or anything.
This is the code that I used to get mine to work, I can't take credit for writing it because I found it from Here
# Get the ID and security principal of the current user account
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
# Get the security principal for the Administrator role
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
# Check to see if we are currently running "as Administrator"
if ($myWindowsPrincipal.IsInRole($adminRole))
{
# We are running "as Administrator" - so change the title and background color to indicate this
$Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
$Host.UI.RawUI.BackgroundColor = "DarkBlue"
clear-host
}
else
{
# We are not running "as Administrator" - so relaunch as administrator
# Create a new process object that starts PowerShell
$newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
# Specify the current script path and name as a parameter
$newProcess.Arguments = $myInvocation.MyCommand.Definition;
# Indicate that the process should be elevated
$newProcess.Verb = "runas";
# Start the new process
[System.Diagnostics.Process]::Start($newProcess);
# Exit from the current, unelevated, process
exit
}
# Run your code that needs to be elevated here
Write-Host -NoNewLine "Press any key to continue..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
But this checks to see if it is elevated and then elevates it if it isn't.