Using a remote Powershell Session to change a service username/password - windows

I have a list of servers, and then another list of services on each of those servers. I am trying to remove it, change a few values in the .bat and then install the services again. Right now I have started a remote Powershell Session using
$PSsession = New-PSSession -ComputerName $server -Credential $Credential
Enter-PSSession -Session $PSsession
I have been mainly using the Invoke-Command -ScriptBlock {//somecodehere} -Session $PSsession in order to run each of the commands that I have used so far. My initial approach was to use sc.exe config $serviceName obj=$username password=$passwd, but each time I make the change on the remote server, it tells me that there is a NativeCommandError and that there is a logon issue with the service.
Is there a way that I can use the credentials provided by the user in order to change the username/password of a service in a secure way? Or does anyone have any recommendations on a better approach I could research?

So my solution to my own problem was to create a script and copy it over to the server. Then it ran the sc.exe command inside of the machine itself. Since it is another machine, you can't send the credentials through as variables if they are a SecureString. So my solution is just to create those variables normally and then make sure to delete them afterwards.
If you are working with confidential data, don't forget that you usually need to overwrite the variable 3 times before deleting it.

Related

Powershell copy file from domain server to workgroup shared folder

Current situation:
We've got a domain with mostly Win Server 2022, including one database server. Next to that our backup server is in a different (accessible) VLAN, but did not join the domain (still in Workgroup). I've got a shared folder on our backup-server with permissions to Everyone.
Future situation:
I would love to write a powershell-script that automatically sends file from our Database-server (in domain) to our backup server (workgroup).
I keep struggling with permissions and auomatically putting them into the PowerShell scripting ... Anyone has got a solution to this?
You can authorize against the share with net-use first, then call your powershell
net use \\server\share /user:<domain\username> <password>
Or if you want to go powershell only, use the New-PSDrive cmdlet.
New-PSDrive -Name P -PSProvider FileSystem -Root \\Server01\Public -Credential user\domain -Persist
Hope this helps.

DCDIAG returns different output in PowerShell

When I run the command dcdiag /test:RIDManager in PowerShell in my Domain Controller, I get the test as passed.
But when I run it from another server in a different domain using Remote Session in PowerShell I get the test as failed.
$testSession= New-PSSession -ComputerName <hostname> -Credential Get-Credential
Invoke-Command -Session $testSession -ScriptBlock {dcdiag /test:RIDManager}
This command gives passed when I use the hostname of the Primary Domain Controller but failed for the Secondary Domain Controller. This comes as failed only when I run the command from as Computer in another domain.
I get the below error when failed:
DsBindWithSpnEx() failed with error 5,
Access is denied..
This issue is because of the double hop problem. So if you create a remote PS Session using Creedssp then the result is as it is in the target server.

Accessing SMB share from Windows when using Powershell

I'm trying to build a custom VeeamZip backup script using PowerShell from a Windows 7 box. The box doesn't have the space requirements to hold the actual data itself, it's just the catalyst to manage the VeeamZip files.
I've been hunting around and found a solution here on SO to work around the fact that the PS-Drive command doesn't function using the -Credentials flag in PowerShell 2.0 using this snippet:
$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive("u:", "\\share\point", $false, "user", "pass")
I can verify this is properly mounting the share and is searchable using Powershell, but when using the VeeamZip Powershell commands, the path U:\ isn't available.
I tried then using the net use command in Powershell which also mounted the volume, but even with /persistent:yes it won't show in Explorer and the backups fail.
What can I do? There has to be option to get this to work. I'm a Linux guy so I'm not powershell wiz.
EDIT: I've now updated to Powershell 3.0 and I still can't get it work...
I'm trying the following snippet, but only Powershell has access the new drive:
$credential = Get-Credential
New-PSDrive -Name V -PSProvider FileSystem -Root \\server\share -Credential $credential -Persist
EDIT: The New-PSDrive function now works to mount the volume in Explorer and can be browsed as expected as long as I don't launch PowerShell as administrator. The dilemma is now that I can't use the VeeamZip tool because it requires Admin to function. Ideas welcome.

Access is denied to localhost despite being administrator - PowerShell

Okay, so this has been bugging me for a while and I have tried too many things now.
I'm trying to run a PowerShell script - my user account is a regular one on the domain, it is however local administrator on my computer. Therefore I've created a PowerShell script prompting me for credentials (where I type the credentials of my domain administrator account) to be used to invoke another script which needs this domain administrator elevation.
This script looks like this:
Invoke-Command -FilePath "C:\Temp\script.ps1" -ComputerName localhost -Credential Get-Credential
Here the script.ps1 is the script which needs domain administrator elevation.
Executing the shown script results in a prompt for credential and then the following error:
[localhost] Connecting to remote server localhost failed with the following error message : Access is denied.
I've tried messing around with a .bat file looking like this:
SET ThisScriptsDirectory=%~dp0
SET PowerShellScriptPath=%ThisScriptsDirectory%script.ps1 PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%PowerShellScriptPath%""' -Verb RunAs}";
aswell, but I can't make it work - it is not elevating the script to domain administrator level.
Lastly however, I need to mention that the script I want to run with domain elevation works if I open PowerShell with the domain administrator elevation, navigates to C:\Temp\script.ps1 and executes it by .\script.ps1.
Any suggestions?
One topic that helped me (I had a similar case) was the section "HOW TO ENABLE REMOTING FOR NON-ADMINISTRATIVE USERS" in About Remote Troubleshooting. Basically, it tells you to execute a PS Command: Set-PSSessionConfiguration Microsoft.PowerShell -ShowSecurityDescriptorUI and grant execution permission to the user that you are trying to use it.
If you have local administrative rights, run powershell as administrator and run Invoke-Command without the -Credential flag.
If you're only running the script locally, you don't need Invoke-Command. You're better off just running the script and passing arguments to it.
Enable PSRemoting Service to Start Automatic
on both host and remote machines
Set-Service winrm -StartupType Automatic
Start-Service winrm
Enable PSREmoting
On both host and remote machines
EnablePSRemoting -Force
Add computers to Trusted Hosts
On Remote machine
Set-Item wsman:\localhost\Client\TrustedHosts -Value "$(hostname),*$((Get-WmiObject Win32_ComputerSystem).Domain)"
Enable Multi Hopping in Powershell Remoting
Identify which hosts to allow passing of Creds
Enable-WSManCredSSP –Role Client –DelegateComputer "$(hostname),*$((Get-WmiObject Win32_ComputerSystem).Domain)"
On the source machine.
Enable-WSManCredSSP –Role Server
You must specify Authentication and a Credential
on Host Machine
$Cred = [System.Management.Automation.PSCredential]::new("<username>",$("<Password>" | ConvertTo-SecureString -AsPlainText -Force))
invoke-command -ComputerName localhost -ScriptBlock {Write-Host $args[0]} -ArgumentList "Hello!, It Works" -Authentication Credssp -Credential $cred
REFERENCE
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_remote_troubleshooting?view=powershell-6
Well, you are doing it wrong if I understand it correctly.
Credential you provided is used to access localhost (which you don't need BTW). Script is still executed unelevated. There are two solutions:
You need to elevate the powershell itself and execute the script.
You need to change the script so that it itself accepts Credential parameter and use it to access things. There isn't much more I can say about it until you show the script.
You can elevate shell with:
start powershell -verb Runas
The problem here is that unless you disable UAC, it will prompt you. Unfortunately there is no easy way around this that I know. One sure way is to add the script to task scheduler and set the task to run elevated, then run it and delete the task. All of this can be automated ofc. This is a consequence of unfortunate design of UAC system (sudo on Linux that serves the same purpose will cache the response for some time so that subsequent commands do not prompt). This would go something like:
schtasks /Create /TN runner ... /TR powershell -File script.ps1 /RU username /RP password /RL HIGHEST
schtasks /run runner
schtasks /delete runner

Powershell drive map with authentication?

I am trying to make a script in powershell (if you have suggestions for another tool to make this with please advise) that would map network drives for userA to map their own drives temporarily while userB is still logged in.
I tried to use both the New-PSDrive method, as well as the MapNetworkDrive method.
They both throw this error:
"Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again"
After I saw this, I tried disconnecting all drives associated with the server before connecting the desired share via:
net use * /d /y
net use \\server\ipc$
net use \\server\ipc$ /d /y
(thanks #jessehouwing !)
The same error still occurs.
If you want to check my connection code I have it below:
$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive($drLetter, $share, $false, $user, $pass)
and
New-PSDrive -Name $drLetter -PSProvider FileSystem -Root $share -Credential $user -Persist
You are getting that error because you are not allowed to have multiple connection to the same resource with different credentials. I am going to Assume you don't just have a temporary connection to this resource defined by server.
What I always to in situations like this is use the IP address of the host. so...
net use \\10.10.10.10\ipc$
I am going to try and find the articles that discuss what is occurring here but in short this will allow the separate connections.

Resources