Making Run Once Registry Edit to Exec Power Shell Script - windows

I am trying to have a power shell script resume after a reboot. (I am rebooting to "apply" registry changes I have made") I believe I can accomplish what I want by making a registry edit to the Run Once key. I have looked at this question, but I can't get my similar code to execute at boot. The registry edit is made and at boot something runs because it disappears but it is not finishing the install.
$part2 = Get-ChildItem C:\Windows\ccmcache\ -Recurse -Force -Filter Full_Druva_Reinstall_part2.ps1
$FullPath = $part2.FullName
$KeyPath = "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
new-itemproperty -Path $KeyPath -Name !Install-Druva -propertytype String -value "Powershell -executionPolicy Unrestricted -File $FullPath"
Edit
This scrpit is inside a SCCM Package and any solution needs to automatic and require no user input.

Open task scheduler on general give a name> run wheter user logged in or not> trigger at startup>
action
program/script will be powershell.exe
arguments
-ExecutionPolicy Bypass -File "C:\myscripts.ps1"

I wasn't able to make the Run Once Registry work, plus it wouldn't tun with admin cred if a non admin logged in. I also wasn't able to make a schedule task in power shell because my environment is all Win7 and power shell v4.
The solution i used was making a task sequence in SCCM that ran part 1 of my script, restarted, and then ran part 2.

Related

Powershell on ansible-playbook remote host

I have a PowerShell script ex1.ps1 which takes user inputs and ex1.ps1 has commands to open a new PowerShell to execute an exe file:
Start-Process -FilePath "$PSHOME\powershell.exe" -ArgumentList "-command C:\APPLICATION1.exe`
I want to execute ex1.ps1 on a remote host. I am trying to call ex1.ps1 using Ansible-playbook as:
# ansible-playbook script
- name: Run basic PowerShell script
win_powershell:
script: |
powershell.exe -ExecutionPolicy ByPass -File C:/Users/ex1.ps1
It is executing fine but in remote host there is no PowerShell prompt open to get the inputs.
You shouldn't be expecting manual input when deploying with a tool like Ansible. I don't know the actual program you are trying to run but the best solution here is to figure out the required parameters for the program to install/start/run without user interaction.
If you are able to provide the name of the program (and it's not something internal to your organization) a more complete answer may be able to be provided.
Unrelated to your question, unless you've over-generalized your code for this question there isn't a reason to call powershell.exe from within PowerShell just to run an executable. You can either use Start-Process or the call operator & directly with the exe path in question.
I have an answer here that goes over Start-Process and the usage of & in a bit more detail.

Powershell command no longer working - only running as an administrator

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.

How to sudo on powershell on Windows

Whenever I need to run a powershell script it complains of security, if I add powershell.exe -nologo -executionpolicy bypass -File .\install.ps1 I still get permission denied unauthorizedAccessException. I just want to run this install script, what is the sudo equivalent to type on the powershell on windows?
If you are using Chocolatey (a package manager), you can install a package named sudo.
Then you can use sudo like Linux 😋
Note: If you're looking to add general-purpose, prepackaged sudo-like functionality to PowerShell, consider the
Enter-AdminPSSession (psa) function from this Gist, discussed in the bottom section of this answer.
If you are running from PowerShell already, then use Start-Process -Verb RunAs as follows:
Start-Process -Verb RunAs powershell.exe -Args "-executionpolicy bypass -command Set-Location \`"$PWD\`"; .\install.ps1"
Note:
The script invariably runs in a new window.
Since the new window's working directory is invariably $env:windir\System32, a Set-Location call that switches to the caller's working directory ($PWD) is prepended.
Note that in PowerShell (Core) 7+ (pwsh.exe) this is no longer necessary, because the caller's current location is inherited.
Executing Set-Location necessitates the use of -Command instead of -File.
A general caveat is that -Command can change the way arguments passed to your script are interpreted (there are none in your case), because they are interpreted the same way they would be if you passed the arguments from within PowerShell, whereas -File treats them as literals.
If you're calling from outside of PowerShell, typically from cmd.exe/ a batch file, you need to wrap the above in an outer call to powershell.exe, which complicates things in terms of quoting, unfortunately:
powershell.exe -command "Start-Process -Verb RunAs powershell.exe -Args '-executionpolicy bypass -command', \"Set-Location `\"$PWD`\"; .\install.ps1\""
Interactively, of course, you can:
Right-click the PowerShell shortcut (in your taskbar or Start Menu, or on your Desktop), select Run as Administrator to open a PowerShell window that runs with admin privileges, and run .\install.ps1 from there.
Alternatively, from an existing PowerShell window, you can open a run-as-admin window with Start-Process -Verb RunAs powershell.exe, as in AdminOfThings' answer.
You can utilize the Start-Process command and then use parameter -Verb runas to elevate. This works great for starting an elevated process.
I created a sudo function like this and added it to my powershell profile:
function sudo {
Start-Process #args -verb runas
}
Example: Open notepad as Admin to edit hosts file
sudo notepad C:\Windows\System32\drivers\etc\hosts
If you want to elevate a Powershell command, you can create a simple function like this:
function Start-ElevatedPS {
param([ScriptBlock]$code)
Start-Process -FilePath powershell.exe -Verb RunAs -ArgumentList $code
}
Then, call the function and pass command wrapped in {} (script block)
Example: Elevate to create a symbolic link
Start-ElevatedPS { New-Item -ItemType SymbolicLink -Name mySymlink.ps1 -Target C:\myTarget.ps1 }
You can start PowerShell with the Run as Administrator option:
Start-Process powershell -Verb runAs
As of today (October 2021), winget install gerardog.gsudo did the trick (on windows 10 home edition). Edit: Tested on Windows 11 as well (April 2022)
after that, you can do this:
gsudo notepad C:\windows\system32\something-editable-by-admin-only.txt
To test if it's working, or in your case:
gsudo powershell.exe install.ps1
You will be prompted by windows` UAC to elevate your priveleges by gsudo, and you can read the source code here: https://github.com/gerardog/gsudo
If you have a corporate policy that blocks scripts execution, then yes. ByPass does not change your profile (user context) state. That is not the design (use case) for any of those switches regarding Execution Policies.
There is not a direct comparison of sudo in Windows, this has nothing to do with PowerShell. You are either admin in a session / app or you are not. If you are installing software, that means you must be admin. If you are doing global system-wide changes, that means you must be admin.
There are folks who have strived to implement scripts, wrapper functions and or modules to mimic sudo …
Module from the MS PowerShell gallery.
Sudo 0.9.3
Use functionality similar to sudo in PowerShell
From GitHub
Sudo for PowerShell
Sudo for PowerShell Installation From PowerShell, create a $profile if
you don't have one:
if (!(test-path $profile)) { new-item -path $profile -itemtype file -force }
Open the profile in notepad:
notepad.exe $profile
Add the following line and save the file:
. /path/to/sudo.ps1
sudo will be available in all new PowerShell windows Usage
sudo application [arguments ...]
...but that does not change what Windows expects when dealing with security boundaries.
See also this Q&A
Sudo !! equivalent in PowerShell
$^ is a variable that expands to the last executed Powershell command.
You can run a command as another user using runas, so the following
works:
runas /user:domain\administrator $^
To shorten that up a bit, you can do some magic with aliases. Take a
look at this Technet article for more info.
EDIT: One caveat - $^ only executes the first command in a pipeline or
multi-command line. If you need to redo an entire command that is
peppered with pipes or semicolons, use Invoke-History instead (which
defaults to the last full command in its entirety).

Check elevated process status?

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)

Running powershell script from CMD does not load module

So i have fairly easy powershell script that contains following:
import-module activedirectory
Get-ADUser -Filter *
remove-module activedirectory
If i run it from powershell it runs OK, but when i try to call it from CMD nothing happens, it just opens powershell and thats it. I am using following command to run it:
powershell.exe -file "D:\test.ps1"
I noticed also following thing, 2 powershell.exe processes run after i execute this. If i exit from CMD from one powershell then i start seeing lists that this PS query should be returning. Is there a way to get this working since i am trying to run ps script as scheduled job. The crucial part here is import module when i run it over cmd which is not happening for some reason.
It's powershell 2.0 running on Windows 2008R2. I tried this script on win 2012r2, works fine from CMD... Looks like ps 2.0 limitation?
Could be a couple of things going on here. Since your windows opens and closes you wont get to see any errors that might be occurring. What is your ExecutionPolicy set to? Get-ExecutionPolicy
When I make scheduled tasks of my scripts I usually set up my action as such
Program/Script = %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe
Arguments = -ExecutionPolicy Unrestricted -NoProfile -File C:\data\script.ps1
Start In = %SystemRoot%\system32\WindowsPowerShell\v1.0
Also, I don't believe it matters in this case but be sure you have the script "Running with highest privilege" if required.

Resources