How can I know if a given user has an admin account in a window server 2012 machine? - powershell

I am required to run a Jenkins job that that is to be executed on a slave machine from the master machine. The job comprises of running some powershell scripts on the logged slave machine.
I am using an account to login from master to slave which I suppose, doesn't have the admin rights as the behavior of the script differs when run as an administrator in the machine to that when run in locally on it.
How can I really confirm if the user provided to me has the admin rights?

In PowerShell 4.0 and newer, you can use the #Requires -RunAsAdministrator comment at the top of the script to prevent the script from running if the current user is not elevated. For earlier PowerShell versions, you can terminate the script if the current user is not elevated using code. For example:
$elevated = ([Security.Principal.WindowsPrincipal] `
[Security.Principal.WindowsIdentity]::GetCurrent()
).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if ( -not $elevated ) {
throw "This script must be run elevated (Run as administrator)."
}

Related

Powershell script shows that $env:username is local system even if the script is executed by a process that is running under user account

I have a windows service that runs and manages multiple processes.
All the processes are running under the user account as per the task manager details tab. So one of the processes is executing a PowerShell script to do some operation that requires a local user account.
I tried logging $env:username, it says the PowerShell script is executed under the system account.
If I manually start the process without any help from the windows service then the PowerShell script executes successfully and also logs that the $env:username is locally logged in user account.
Note: the windows service is starting those processes using CreateProcessAsUser method which supposedly starts the child process under local user account. But somehow it seems that the task manager shows its running under user account but behind the scenes, it's running under the system account.
Can anyone tell me how I can execute the script under a local user account?
The cmd that I use to run the PowerShell script is
Powershell.exe -NoProfile -ExecutionPolicy Unrestricted -Command ../powershellscript.ps1

Scheduled Task Powershell Script - Runs OK as user account, but not as SYSTEM

I'm attempting to run a Powershell script as the SYSTEM account as a scheduled task, and the task runs OK, but the script runs incorrectly because it does not load some Citrix Powershell snap-ins that are needed when run as SYSTEM, but runs OK as my user account.
The script does a check to load the Citrix snap-ins, but those do not appear to work when run as SYSTEM.
if ((Get-PSSnapin "Citrix.Common.Commands" -EA silentlycontinue) -eq $null) {
try { Add-PSSnapin Citrix.* -ErrorAction Stop }
catch { write-error "Error Citrix.* Powershell snapin"; Return }
Is there anything special I need to do to get those Snap-ins loaded correctly? I'm calling the script like this, if it matters: powershell.exe -executionpolicy bypass -file C:\path\to\script.ps1.
EDIT: From running (Get-PSSnapin -registered).count as both SYSTEM and my user account, I can see that the snap-ins are loaded correctly, but still can't figure out why the script behaves differently.
OS is Server 2016, version 1607, this is the script: https://gist.github.com/4oo4/85cec464e123d7f2793745e662d6e7ab
This isn't the answer why your specific script doesn't work under the SYSTEM account but explains how you might troubleshoot your (or any other) PowerShell Script under the SYSTEM account.
Give a man a fish, and you feed him for a day. Teach a man to fish,
and you feed him for a lifetime.
The whole thing around this, is that you can actually open a interactive PowerShell command prompt under the SYSTEM account were you probably not aware of.
Run PowerShell as SYSTEM
There are a few ways to start a interactive PowerShell command prompt but probably the easiest one is using PsExec.
Using PsExec
Download
PsTools
Extract PSTools.zip and just copy PsExec into your executable path
Run PowerShell as Administrator (accept the User AccountControl prompt)
In the PowerShell administrator window, give the command: .\PsExec -i -s -d PowerShell
A new PowerShell command window will open:
(Type WhoAmI to confirm the current account)
From here you can troubleshoot the specific script:
Are there any errors when running the specific script?
Does it hang or crash at a specific command?
Are there any differences with running it under a user account?
If it appears that the script runs actually fine in the SYSTEM window, then I would check for any errors in the Task Scheduler:
Select Task Scheduler Local - Task Scheduler Library in the left pane
Select your task in the middle top pane
(Make sure you have Display All Task History in the right pane Enabled)
In the middle bottom pane check the events in the history tab

Powershell as scheduled task issue with importing module, it seems

I am attempting to configure some powershell/view powercli scripts for our VMware horizon environment. I have a powershell script that works properly to query the horizon instance and check machine states. However, when I try to run this as a scheduled task using a service account, it seems to fail to import a module, as a command is unrecognized ("The term 'Connect-HVServer' is not recognized as the name of a cmdlet, function, script file, or operable program.")
I tried profiles as well, didn't matter.
What I observed is that if I open powershell as the user in question (run as different user > authenticate as service account), leaving that powershell instance open will allow the scheduled task to run as expected. However, if i close the powershell instance, the scheduled task fails. This is obviously not viable since the goal is for this script to run on a schedule without the service account (or any account) being logged into the windows server at the time the powershell script gets run.
The problem you're running into is environment variables. In the course of running as a user versus running as machine, the PSModulePath environment variable changes to include user-directories for user-scoped module installs. You should install PowerCLI machine-wide.
Alternatives (these assume your service account has admin privileges):
Modify your $Env:PSModulePath in the script to include each user's module path
Specify the path in an Import-Module statement in your script before you use any of the cmdlets
Example of the first alternative:
foreach ($user in (Get-ChildItem -Path C:\Users)) {
$Env:PSModulePath += ";$($user.FullName)\Documents\WindowsPowerShell\Modules"
}
Example of the second:
Import-Module -Name 'C:\Users\KnownUser\Documents\WindowsPowerShell\Modules\PowerCLI'

How can I run this Powershell script as a user?

I am trying to run the following script upon startup of my machine because I cannot get a service to start on startup. I can schedule it to run. The problem I am facing seems to be a user vs administrator issue.
This is for a Windows 7 machine with PowerShell 4.0.
I have set the execution policy to unrestricted.
When I try to run the script as the User I designated to have administrative privileges I see the following error.
When I right click the powershell icon, run as administrator the command works fine.
The command is
get-service -name "*vmauthd*" |start-service
Is it possible to run this as my user account?
Solution I was able to get this script to run on startup as I initially desired. I turned off UAC and set the execution policy to unrestricted. I am not sure if the UAC was the issue before but the script runs now. I created a cmd file with this in the code. I set the cmd file to run at startup using Windows Task Scheduler and set the task to run whether logged in or not.
PowerShell -Command "Set-ExecutionPolicy Unrestricted"
PowerShell -Command "get-service -name "vmauthd" | start-service"
pause
Here is an image of the cmd file

Run specific commands in PowerShell under different credentials?

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.