Run Command as administrator in PowerShell script. UAC - powershell

OK here is my issue:
I am trying to run a script remotely on a server.
I am an administrator on both boxes, firewall exceptions are in place, remote admin is enabled, and everything else looks good that i can see.
invoke-command -ComputerName $ComputerName -ScriptBlock `
{
cd C:\Windows\System32\inetsrv\;
./appcmd.exe ADD vdir /app.name:<SiteName>/ /path:/<VDir Name> /physicalPath:<Path to files>
}
I keep getting the following error in return
ERROR ( hresult:80070005, message:Failed to commit configuration changes. Access is denied.
The server it is trying to run on is a server 2k8 R2 box and I am thinking the issue is a UAC problem. Is there anyway to get this to run as administrator without having to click yes on a UAC box?
This piece of code will eventually become a script that will have to be completely automated.
Any help would be greatly appreciated.

OK. After some research and testing I figured out the issue. After disabling UAC and the firewall and the script still not working I dug a little deeper and discovered that the main issue was the way invoke-command runs the commands. it uses the credentials of the person running the script to authenticate to the server then tries to use another account to run the permissions or lowers the privileges of the user so that certain commands cannot be run.
I added the -Credentials switch to the invoke command and everything is working great now. Corrected code sample below:
$user = New-Object Management.Automation.PSCredential("$UserName", $securePassword)
invoke-command -ComputerName $ComputerName -Credential $user -ScriptBlock `
{
cd C:\Windows\System32\inetsrv\;
./appcmd.exe ADD vdir /app.name:<SiteName>/ /path:/<VDir Name> /physicalPath:<Path to files>
}

This seems to indicate that you need to ensure you are a local admin on the remote machine (although admittedly this is for WMI specifically). According to this you can change a registry key to stop UAC applying to remote logons for administrators (search for LocalAccountTokenFilterPolicy). That shouldn't disable UAC just not filter the token if you use powershell/WMI remotely with an administrator account.

Set the option "EnableLUA" (DWORD value) found in HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System to 0 and reboot.
This will disable UAC without a problem, I would do it for all your users, whether with or without permission is up to you.
This trick works in Windows Vista and Windows 7 too.

Is there anyway to get this to run as administrator without having to click yes on a UAC box?
If this were possible it would entirely defeat the point of UAC.
Thus, it would appear your only real solution is to disable UAC on the box.

Related

Double-Hop Errors when running Skype for Business Cmdlets

I am attempting to automate the Skype for Business Server installation process in Powershell, I have a script that remotes into specified machines and begins preparing them as Front-End servers. The problem lies when certain SfB cmdlets (SfB commands are all of the form "verb-Cs...", ex. Get-CsUser or Get-CsPool) are run in remote sessions, they throw the double-hop error:
Exception: Active Directory error "-2147016672" occurred while searching for domain controllers in domain...
This is after running Enable-CsComputer, which enables the computer's role-based off its definition in the topology (topology was published successfully). The user object is in all required groups (RTCUniversalServerAdmins, Schema Admins, CsAdministrators & Local Admin rights on all SfB Servers). Oddly enough, the command 'Import-CsConfiguration -localstore" does not throw errors, and it's in the same remote session. There may be other local or domain groups that I need to be in, but I cannot pinpoint exactly which and have not seen them documented in the Skype build guides. Skype commands that have parameters to specify targets or just pull data, such as Get-CsPool or Get-CsAdForest, do not have errors because they are run in the local scope. The Enable-CsComputer has no parameter for the computer name, it has to be executed from that machine itself.
Enabling CredSSP delegation on each server is not an option, and I'm not understanding why there is a "second hop" in this command! If the second hop was a resource on a file server or database, that would make sense, and be easy to solve, but in this case, I can't track it. Can anyone tell me what I may be missing?
Here's a code sample to try and illustrate. From the jumbox I get the pool data to create an array, and a session is opened to each machine:
$ServerArray =get-cspool -identity $poolName
$i=0
$SessionArray = #{}
foreach($server in $ServerArray.Computers){$SessionArray[$i] = new-PsSession -ComputerName $server}
foreach($session in $SessionArray.values){
invoke-Command -session $session -scriptBlock {
#remote commands:
import-csConfiguration -<config file path> -localstore; #no errors
enable-CsReplica; #no errors
enable-cscomputer; #double hop error here
}}
If I log into that machine and run the same command, it executes fine but the intention of the project is to automate it on an arbitrary number of machines.
It looks like it's just trying to authenticate to a domain controller, which is reasonable. You'll have to approach this like any other double-hop issue.
Microsoft has an article dedicated to the double hop issue, and has a few solutions other than CredSSP that you can look at: Making the second hop in PowerShell Remoting

Powershell remoting - cannot execute an exe as another user

I've a commandline program (c#) that encrypts config files based on machine key.
A powershell script copies the build to a Target Server, modifies configs accordingly and installs windows services.
All the windows services run as local system account (standard user, non-admin) - let's call this account "locuser".
The Target Server is a Win 2012 R2 Server. All of the above is achieved by PS remoting from the Build Server to this Target server.
Now, I need to run the encrypt commandline program as "locuser", so that the program can use the account specific key to do the encryption.
I know that this can be easily achieved by calling Start-Process cmdlet with -Credentials parameter. Well, here's the catch, the above works fine, if I remote in (RDP) to the Target Server and then run the Start-Process .... -Credential $cred from a Powershell Console.
However, I need this to be working while I remote-in (using my scripts) to the TargetServer whilst deploying. When I remote-in to the TargetServer I use credentials that has Admin privileges.
I've tried the following
I've granted "locuser" both "Full Control" and "Invoke (Execute)" permissions by using the Set-PSSessionConfiguration -Name Microsoft.PowerShell -ShowSecurityDescriptorUI command. I've run this command for both Microsoft.Powershell and Microsoft.Powershell32 - Still get Access Denied
I've edited the "Local Security Policy"->"Local Policies"->"User Rights Assignment"->Impersonate a client after authentication - and added both the Admin account (that I login with) and the "locuser" account - Still get Access Denied
I've also granted locuser admin rights - Still get Access Denied
I'm pretty sure, there is some configuration on the PS Remoting Side of things that I'm missing out but can't figure out what - because all Powershell throws me is a Access Denied error (see screenshot) with little to no useful information to troubleshoot further.
Also, checked Event logs for any traces but to no avail.
You've fallen prey to the dreaded Double Hop. Basically you're authenticating from computer A to computer B, then trying to authenticate again from computer B to computer C (which also happens to be B in this case).
If at all possible, you would be better off ending the session and starting a new one with the locuser credentials, then just calling Start-Process. Another, more messy approach is to use schtasks.
I can tell you how to do it in the same session but it's a bit messy and very complicated, and should only be a last resort:
On the originating server (Build Server):
Run the command Enable-WSManCredSSP -Role Client -Delegate [name] where [name] is an IP or DNS address / range including any target servers (eg "192.168.1.*")
Open GPEdit.msc, navigate to Computer Configuration\Administrative Templates\System\Credentials Delegation and check that the rules Allow delegating fresh credentials and Allow delegating fresh credentials with NTLM... are enabled and include [name]
On the Target Server:
Run the command Enable-WSManCredSSP -Role Server
Running the command:
Invoke-Command [targetserver] [-Credential $cred] -Scriptblock {
## do stuff
Invoke-Command . -Credential $locusercred -Authentication Credssp -ScriptBlock {
Start-Process -FilePath $sc #etc
}
}
Some things to be aware of:
Firstly I used this setup to create a local session, then remote from there (so A-A-B instead of A-B-B) so the Group Policy stuff might be in the wrong place but pretty sure it's right.
Secondly I found that credentials are a pain to get working in sessions (in this case $locusercred). I did get it going natively but weirdly it suddenly couldn't decrypt the securestring. I ended up saving a securestring with a defined key to the registry so it can always be decrypted from any account, you may need to come up with your own solution there.
All this stuff is explained in the free eBook "The Secrets of PowerShell Remoting", if you go for the double-hop approach I recommend giving it a read.

PowerShell - Cannot remove profile created with Enter-PSSession unless winrm service is stopped?

I am using the remove-profile script from here http://gallery.technet.microsoft.com/scriptcenter/Remove-Profile-787d9188 to remove profiles which is working great until an interesting problem I came across is not letting me remove a profile. When a profile is created by a user logging in with Enter-PSSession the profile cannot be removed until the winrm service is stopped. Does anyone know what causes this or know how to get around this so I don't have to stop the winrm service? Here is a screenshot of what it looks like - http://i.imgur.com/96J5T04.jpg
The PowerShell remote session were probably not closed correctly. Either make sure they are closed correctly (Remove-PSSession or Exit-PSSession) or try to remove them with something like below (PowerShell v3 and higher, see here).
Get-PSSession -ComputerName MyServerName | Remove-PSSession

Powershell Active Directory Module in Remote Session

Hi does anyone have any experience of how to get the Active Directory module to work in a remote ps session?
Nothing I'm trying seems to work.
My remoting between the computers are fine and working and they are joined to a domain.
Lets say I do this
$Session = New-PSSession -ComputerName DC01
Invoke-Command -Session $Session {Import-Module Active Directory}
WARNING: Error initializing default drive: 'Unable to contact the server. This
may be because this server does not exist, it is currently down, or it does not
have the Active Directory Web Services running.'.
If I logon to the server directly it works fine. Tried creating a SessionConfiguration also and told it to load the AD module but no luck there either.
May be the dreaded "double hop authentication" problem. Since you already have a Session Configuration set up, you can try adding -RunAs to that and see if it starts working:
http://www.vinithmenon.com/2012/11/delegated-administration-in-windows.html
I found the solution to my problem. I enabled CredSSP on the server again from scratch and on my client and now it's working :)

Backup Event Logs via Powershell and WMI

I have Powershell script that makes backups of all Event logs on current localhost.
It runs from Task Scheduler with "Run with highest privileges" under restricted account (this account only has Backup Operator rights). Script itself can be found here
OS: Windows Server 2008 R2, UAC is turned off.
The problem appears in the following line:
$Eventlogs = Get-WmiObject -Class Win32_NTEventLogFile -ComputerName $computer
In returned collection of Event logs Security log is missing and as result isn`t backuped. All other are present.
If the same script is run directly from Powershell using the same account - Security log is present.
Granting local Admin rights to account solves the issue but isn`t applicable.
Do you have any ideas what may be causing such behaviour? Appreciate any help!
I have not done a lot of research on this but I once encountered a similar problem. Using the switch -EnableAllPrivileges in the first call of get-WmiObject solved it for me.