Run specific commands in PowerShell under different credentials? - powershell

I am trying to run a specific command line function in my PowerShell script. The catch is the command needs elevated permissions to be able to execute.
Here is a condensed example:
# PowerShell code...
query session /server:"SERVERNAME" #NEEDS ELEVATED PERMISSIONS
# More PowerShell code
The query command needs to be run under elevated permissions.
I have tried the following:
Invoke-Command -ScriptBlock {
query session /server:"SERVERNAME"
} -Credential get-credential
But this doesn't work because the -ComputerName parameter needs to be present when using a -Credential parameter. I want to be able to run this without using a remote server.
I know I can get around it by having the users start up PowerShell under their elevated account credentials, but I'd rather just prompt for credentials while the script runs and just run that single command under their administrator account credentials. Everything else the script does is fine under normal credentials.

There are some add-ins for PowerShell, but I actually found the simplest way was to:
Sysinternals in regular command line
With the PSexec process, you can pass IP address, usermame, and password
Fiddle with it to a point you're happy
Create a batch file to then run from PowerShell if that is the desired deploy to environment
When creating the method, have it consume parameters if you want the call out to be dynamic and consume different usernames/passwords/IP addresses to log into
If the exec will always run on "computerA" using "loginA" and "pwA" then there is obviously no need to parameterize
*Sysinternals cannot be used to outright hack a terminal. The user of a remote exec must first have the same Sysinternals tools installed to the system that is to accept remote executables, that tool must be opened once and given GUI-based approval to allow run on said system must be physically addressed.
Note: Any remote PSexec's using credentials will execute with the same level of permissions that the provided username/password is granted on that system.
Here is the link: (PsExec v2.2). Although I recommend going a level or two up and downloading the entire toolbox.

Related

Auto Answer Powershell Prompts from Scripts

I have written a powershell script which uses a third party Cmdlet (https://www.powershellgallery.com/packages/OdooCmdlets/21.0.8137.1).
The script is working fine on my local enviroment, but i need to apply it to an Azure Function to generate a daily execution (since it process data into a Azure SQL Database).
On its first line (see script below), i have establish the connection parameters where a prompt / pop-up window appears, which is easy to anwser when via user interaction from a local enviromnt (Powershell ISE)
However, when i try to run the script on the azure function the following error appears:
ERROR: A command that prompts the user failed because the host program or the command type does not support user interaction. The host was attempting to request confirmation with the following message: Would you like to install a license now? (You may use "TRIAL" as the Product Key to activate a trial license.)
I need to adapt the script in order to auto-anwser the prompt / pop-up window, or find another solution.
Powershell Script:
Import-Module OdooCmdlets
$odoo = Connect-Odoo -User 'xxxxx' -Password 'xxxx' -URL 'xxxxx' -Database "xxxx"
I've never used the cmdlets before but inspecting the help files: https://www.powershellgallery.com/packages/OdooCmdlets/21.0.8137.1/Content/lib%5Cnet20%5CCData.OdooCmdlets.Commands.dll-help.xml it appears there is an -RTK parameter available.
Is it possible you have a key which you can pass as part of the connection which would suppress the prompt?
Failing that, the developer docs have examples for Python which you could either translate to PowerShell and not use the Cdata Odoo module or just use python in your Azure Functions
https://www.odoo.com/documentation/15.0/developer/misc/api/external_api.html

Unable to pass parameters to powershell script via SSH

I'm trying to run a basic powershell script over ssh, the script is this:
param($passedUrl)
Function Launch-Site($url) {
start chrome $url
}
Launch-Site $passedUrl
When I run this in powershell, in the correct directory, with the command
.\launchSite.ps1 google.co.uk
It runs as expected, it launches google chrome and goes to google.co.uk. However, when I use the same command from my ssh terminal (in the correct directory), it does nothing and gives me no errors as far as I can tell.
The default shell is set to powershell. I can run normal scripts that don't have any parameters passed to them, so I'm thinking this is just some security with windows that isn't letting me pass the parameter. Is there any way to get around/fix this?
For this you will need to use a PowerShell remote session. Something along the lines of:
New-PSSession -HostName HOSTNAME -UserName UserName
Hostname being an IP or FQDN. It will prompt you for a username for authentication. This can be stored also as a variable to pass into the module as well.

How can I make PowerShell run a program as a standard user?

Alright, so, I've been searching online forever, and I can't find anything on this at all.
Basically, what I want to do is run a program from an elevated PowerShell script, but I want the program to run as the standard user.
I need to do this because the program that I need to run requires access to a mapped network drive that the domain administrator accounts don't have access to. So, I basically need a line of code that will take the script out of elevated mode, or some extension to the Start-Program command that will make it run as the logged on user rather than the administrator account that the script is running from.
you could use psexec
psexec -l powershell.exe -executionpolicy unrestricted -noexit -file c:\temp\checkelevated.ps1
-l : Run process as limited user (strips the Administrators group and allows only privileges assigned to the Users group). On Windows Vista
the process runs with Low Integrity.
One way that I have used extensively in the past is to create a scheduled task on the fly specifying the currently logged user as the account that will run the task. The task would run some other script, command, etc. and it would occur in the context of the logged on user. This is possible by using Start-Process to call the schtasks.exe program that will...
Create the task (schtasks /create /tn "MyTask" /tr "powershell -file...." /ru "domain\username")
Run the task (schtasks /run /tn "MyTask")
Delete the task (schtasks /delete /tn "MyTask")
You would just need your script to get the current user, which can be done in a number of different ways. I've also put a 2 second pause in between those calls to schtasks just to ensure they all run.
There are more ways to do it (probably some even better) I guess, but this should also work.
If you need to run an executable or script under currently logged in user from an elevated environemnt, you can use RunAs with USERNAME environment variable passed as user argument:
runas /user:%USERNAME% program.exe
USERNAME environment variable should contain currently logged in user even in an elevated environment.
The generally intended and accepted way to do this is to specify the network UNC path instead of the network drive. You can even re-map the drive in the elevated process if you need it. That's how you're supposed to do it. If you have an account running a process that needs access to a network location, the proper answer is to grant that account the access it needs to do it's job.
However....
Does this or this or this describe the problem you're actually having? It's very unclear what you're trying to do. You've eliminated all context from your question.
If you're trying to run a script that needs to run elevated and needs to access the user's network drive and you can't use a UNC path for whatever reason, then the above three links are what you probably want.
If you really, truly need to impersonate a logged on user -- and I really struggle to think of a situation where I'd need to do this from a script -- then read on.
The alternatives that don't require knowledge of user credentials are:
Use a user logon script instead of a computer startup script. If necessary, grant the local user the permissions they need to run the rest of the script. I can't imagine you haven't thought of this already.
Create a scheduled task which runs as "Domain Users" or some other group that represents the users in question and the "Only run when logged on" is checked. Again, you'd need to grant the user the permissions they need to run the rest of the script, but it wouldn't tie you down to logon only.
Write a program which calls ImpersonateLoggedOnUser, which requires SeImpersonatePrivilege (Administrators have this by default, IIRC). These are native Win32 calls, not .Net, so they will not be straightforward to use in PowerShell. It's been about a decade since I've looked at this, and it used to be a huge pain because it would sometimes still prompt for credentials. I have to think that the increased security in Vista and later (UAC, et al) would have made this even worse. I also have no idea if you have access to mapped drives (i.e., if the impersonation survives network hops). I would choose this method approximately never.
For anything else, I think you will require credentials of the current user. What you'd be doing is credential hijacking, and OS security is specifically designed not to allow that.

How can I execute scripts in a code created powershell shell that has Host.Ui.prompt commands in it?

I have a Powershell Commandlet which prompts a user from a secure string based on a condition. Now I want to automate the testing of this commandlet for which I use a Powershell Remote Runspace to Invoke the commandlet. Currently it fails with this error.
Write-Host : A command that prompts the user failed because the host program or the command type does not support user interaction. Try a host program that supports user interaction, such as the Windows PowerShell Console or Windows PowerShell ISE, and remove prompt-related commands from command types that do not support user interaction, such as Windows PowerShell workflows.
How can I automate this?
It sounds like you are running powershell via c#. You can't prompt the user for input from the powershell script. You either need to pre-provide the necessary info in the script, or prompt for the info from your application and then pass the info to the powershell script.
As ojk mentioned the easiest way to accomplish this would probably be to use a powershell function then pass the necessary parameters to it via the code.

Run remote process by powershell

I have the following line of code to create object to access to a remote server before I associate it with user name, password and process:
$process = [WMIClass]"\\remoteServer\ROOT\cimv2:Win32_Process"
I tried this on two PCs, one is OK without any errors, but another one I am going to run has an exception:
Cannot convert value "\\remoteServer\ROOT\cimv2:Win32_Process" to type "System.Manage
ment.ManagementClass". Error: "Access is denied. (Exception from HRESULT: 0x800
70005 (E_ACCESSDENIED))"
The remoteServer is the same one. Not sure what I have to set on local PC or remote PC to make this work? On both client PCs, the user names are all member of Administrators.
Have you considered looking into PowerShell remoting? If your running PowerShell 2.0 I'd recommend that you take a look at it. Once you have set up remoting you'll be able to execute commands on the remote server using the Invoke-Command:
Invoke-Command -ComputerName {serverName} –ScriptBlock { commands }
The ScriptBlock can contain any powershell commands so you will be able to start processes on the remote machine with this mechanism. To enable remoting you'll need to use the Enable-PSRemoting cmdlet and you can get details of this at http://blogs.msdn.com/powershell/archive/2009/04/30/enable-psremoting.aspx and http://technet.microsoft.com/en-us/library/dd819498.aspx
Is there some reason you don't want to use psexec?
http://technet.microsoft.com/en-us/sysinternals/bb545027.aspx
I know this is an old post, but what I think you need to do is run the following command on the remote machine:
"Get-ExecutionPolicy"
it sounds like its set to "Restricted" which means it will not run any "Invoke-Commands" commands, or remote scripts.
You can change it to 1 of 7 options:
Unrestricted____(least secure but if you need to troubleshoot set this option)
RemoteSigned__(will only all scripts with a signature, this a so so option)
AllSigned______(Best option if youu need to run remote scripts, but all will beed signed)
Restricted_____(I believe this option is set by default in windows 7 nad WS2k8)
Default
Bypass
Undefined