Open remote location from PowerShell as different user - powershell

I need to open some remote folder a lot of times, and I usually use start in powershell this way
start \\myserverXXX\some_hidden_drive$\some_folder
Sometimes I need to use an administrator account, and I would expect to be prompted to insert different credential, but i get an error instead. Am I missing something?

Use the credential option as follows
start \\myserverXXX\some_hidden_drive$\some_folder -Credential $(Get-Credential)
This will prompt you to enter different credentials

Have you tried mapping a drive using those credentials, then opening it? I don't have a place to test this at the moment.
New-PsDrive -Name X -PSProvider Filesystem -Root \\myserverXXX\some_hidden_drive$\some_folder -credential $(get-credential);
Invoke-Item X:

Related

Powershell invoke-command multihopping

I have a question regarding multihopping in a windows environment.
Let's say I have a schedule running on Server A (Central Scheduler) which executes a command on Server B. This script contains a call to save files on a remote filer (UNC path, Server C). Hop 1 (from A to B) works well, hop 2 (from B to C) fails.
I already tested to save the files locally on server B, that works flawlessly.
I think there's a problem with the second hop. I remember reading something like this on a forum a while ago, but can't remember a solution.
In detail, the command looks like this:
$session = New-PSSession -computer ComputerName
$templatepath = "\\filerpath\"
Invoke-Command -Session $session -Scriptblock { powershell ovpmutil cfg pol dnl $Using:templatepath /p \BSH }
To clarify: Powershell gives me an "Access denied" when performing the second hop. I already enabled Credential delegation as described here:
Enabling Multihop Remoting
Any help is appreciated. Thanks in advance
The solution is a real pain in the backside if you ask me but here it is...
On the originating server (A):
Set-Item WSMAN:\localhost\client\auth\credssp -value $true
On the intermediate server (B):
Set-Item WSMAN:\localhost\client\auth\credssp -value $true
Open Group Policy editor on server A, navigate to:
Computer Configuration > Administrative Templates > System > Credentials Delegation
Enable these options:
Allow delegating fresh credentials
Allow delegating fresh credentials with NTLM-only server authentication
Both policies need to have server B added to the allowed list, wildcards are allowed. Note that if you use RDP from server A you'll also need to add TERMSRV/*
When running Invoke-Command from server A, include the -Authentication CredSSP param.
Note that if saving SecureStrings somewhere for the credential to connect to server C, you'll want to either use a fixed encryption (specify byte array) or plain text and convert it.

How to disable windows firewall for all networked machines using the command line in Windows Server 2016?

I am currently building a Hyper-V lab consisting of a DC and multiple networked VMs, using Windows Server 2016. I'd like to completely disable the windows firewall for all existing and newly created VMs.
The best way that I've found to do this so far is via Group Policy for the Domain Profile. Then set Windows Firewall: Protect all network connections to disabled. What I would like to do is to have a way of scripting this out (using Powershell if possible).
I've found that by performing the above steps in the GUI, it creates a few entries in the registry:
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\WindowsFirewall\DomainProfile
HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Policies\Microsoft\WindowsFirewall\DomainProfile
In each of those entries, there is a property called EnableFirewall which is set to 0. So I tried creating all of this using Powershell like this:
New-Item -path "HKLM:\SOFTWARE\Policies\Microsoft" -name WindowsFirewall
New-Item -path "HKLM:\SOFTWARE\Policies\Microsoft\WindowsFirewall" -name DomainProfile
New-ItemProperty -path "HKLM:\SOFTWARE\Policies\Microsoft\WindowsFirewall\DomainProfile" -name EnableFirewall -value 0 -PropertyType DWord -Force
Unfortunately it doesn't seem to be working, so there must be something else that I'm missing.
Does anybody know how to completely disable the windows firewall for all networked machines using the command line in Windows Server 2016?
Setting up the Windows-Firewall for your domain-computers through computer-startup-script is not a great solution in my opinion.
You should definetly use Group Policy for this task.
GP does exactly what I want, I would just like a way of modifying GP using Powershell. I'm building a lab from scratch, and I'm looking to script as much of it as possible rather than using the gui.
I am not completely sure, what you are trying to achive.
You have created a lab now and I think you are trying to script a complete automatic built-up for future use. Is this correct?
If yes, then my solution is maybe what you are looking for:
Create a new GPO in your lab named "Firewall-Settings" for example.
Make all of your needed FireWall-Settings to the new GPO.
In Group Policy Editor open the main-node named „Group Policy Objects“. (important) Find the newly created GPO, right-click it and select "Backup":
Save the GPO-backup to a folder. (folder must exist)
The GPO is beeing saved and named like on the screenshot below (GUID):
That's it for the preparation. Now you maybe want to script the creation of the GPO with Powershell for future use and import the backup to obtain it's settings in a new environment:
New-GPO -Name "FireWall-Settings" | New-GPLink -Target "DC=mydomain,DC=local" # distinguishedName of Target-OU
Import-GPO -Path $PathtoGPOBackup -TargetName "FireWall-Settings" -BackupGpoName "FireWall-Settings"
The Script creates a GPO in the new environment with the name "FireWall-Settings" and links it to the target-OU.
After that you import the settings of the backup-GPO. All the domain-members in scope of the GPO will get the Windows-Firewall configured automatically.
Now the process is documented and fully automatic, if this is, what you are looking for.
Kind regards
open cmd prompt with elevated mode and run this:
netsh -r ComputerName -u Username -p Password -c advfirewall set allprofiles state off
If you want to do it for all the machines. Get all the ad computers using get-adcomputer. Run a foreach loop and put the variable istead of computername.
If you have the domain admin creds, then you are good to go with this.
Hope it helps.
Depending on the profile you want to disable, specify profiles (public, domain, private) using the -Name parameter. To disable all profiles for a networked machine, where $computerName array is the hostname of your DC, PC etc:
$computerName = 'DC1, PC1, MS1'
Invoke-Command -Computername $computerName -ScriptBlock {
Set-NetFirewallProfile -Name Domain, Public, Private -Enabled False
}

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.

Using a shared file variable in powershell

I am trying to execute a remote command to perform netsh command. The command will do a export of the nps configuration file and output it to a shared path. But, the command always give me an error "Access is denied". I realised the problem lies in the shared path value (\\shared-pc\temp). Without it, I am able to execute it successfully eg (C:\Users\User1\Desktop). I am able to browse to the shared location from the local and remote PC. Any advice is greatly appreciated. Below is the command. Thanks.
invoke-command -computername nap1 -scriptblock {netsh nps export filename = "\\shared-pc\temp\config.xml" exportPSK = yes}
This is the double-hop / second-hop authentication problem. You're credentials is passed to the nap1-server, but nap1 doesn't have the permission to pass on the same credentials(yours) to the fileserver to get access.
The solution to is to use CredSSP
There are some mixed feelings about how smart it is to use in a production enviroment, but that's up to your company to decide.

Run Command as administrator in PowerShell script. UAC

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.