Invoke-command doesn't need credentials - powershell

I have 2 servers (windows server 2012 R2) in the same domain.
I execute a command on server01:
Invoke-Command -ComputerName server02 -Credential Administrator -ScriptBlock {Get-Culture}
I give the password of my Administrator (of server2) and it works well.
But when I try:
Invoke-Command -ComputerName server02 -ScriptBlock {Get-Culture}
It also seems to work. Probably because the 2 servers are in the same domain. While I only want it to work when you can provide the right credentials. Can someone help me with it?

You are probably doing this by Domain Admin account or account that it's in Domain Admins group or so.
In any case this results because your account has privelegies on that computer.

With which user do you execute the script on server01? Does that user have permissions on server02 too? If your user has admin permission on server01 and server02 then no credentials are neccessary... (as far as I know)
To check if the provided credentials are valid have a look here:
https://gallery.technet.microsoft.com/scriptcenter/Test-Credential-dda902c6
Or something like this:
$cred = Get-Credential #Read credentials
$username = $cred.username
$password = $cred.GetNetworkCredential().password
# Get current domain using logged-on user's credentials
$CurrentDomain = "LDAP://" + ([ADSI]"").distinguishedName
$domain = New-Object System.DirectoryServices.DirectoryEntry($CurrentDomain,$UserName,$Password)
if ($domain.name -eq $null)
{
write-host "Authentication failed - please verify your username and password."
exit #terminate the script.
}
else
{
write-host "Successfully authenticated with domain $domain.name"
}
Which was found here (but I haven't tested it):
https://serverfault.com/questions/276098/check-if-user-password-input-is-valid-in-powershell-script

Related

Why can I pass credentials to a regular user but not a local administrator?

So basically I've been working forever on a PS remote self help script that originally was thought to be simple: Restart the spooler service, clear the queue, and print a test page on the default printer. Getting there however hasn't been so easy, due to security issues. After some hours, I was able to get my local user test account to accept the credentials of my domain administrator. I thought all was well, until I tried to replicate it on a local administrator's account, in which event access was denied. This is sort of important, because the majority of the accounts we will be deploying the script on are local admins. I suspect it may be a UAC issue, but I have no idea what I should do to work around the problem. Here's what I'm working with currently:
$v = [bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544")
If ($v = "False")
{
$password = "ElPassword" | ConvertTo-SecureString -asPlainText -Force
$username = "Domainname\Username"
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
invoke-command {Stop-Service spooler} -comp $env:ComputerName -cred $credential
Remove-Item C:\Windows\System32\spool\PRINTERS\* -Force
invoke-command {Start-Service spooler} -comp $env:ComputerName -cred $credential
$printer = Get-WmiObject -Query " SELECT * FROM Win32_Printer WHERE Default=$true"
$PrintTestPage = $printer.PrintTestPage() } Else
{ Stop-Service spooler
$printer = Get-WmiObject -Query " SELECT * FROM Win32_Printer WHERE Default=$true"
Start-Service spooler
$PrintTestPage = $printer.PrintTestPage() }
The first thing this does is check if the current PS session is being run as admin; seeing as the users don't actually see the PowerShell window or script, and we recently started using the RMM tool, I'm still trying to figure out under what conditions the tool runs PS elevated - the documentation says that it runs with the credentials of the logged in user, but that doesn't seem to be the case, as an hour with their support team told me that the reason the script wasn't doing it's job on any admin accounts was because it wasn't being elevated. Anyways, after the check, it either passes credentials for the commands or it doesn't. This script seems to handle every scenario but that of a local admin account running PS non elevated. In that event, it simply denies me access where the exact same creds give me access on a regular user account. I'm not sure how to even approach this problem, so any help is appreciated.

Powershell 5.0 Invoke-Command Start Service with Credential

We have a problem with a Service on a Server. So we decided to write a PS-Script that a "normal" User without Admin privileges can start this Service. I have practiced now 2 Day's on this little Script. I'm a newbie (Apprentice) in PS but im glad that it works when I run it as an Admin. But why the heck not as an User?
I have generated the "Secure" Password as follow:
"P#ssword1" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\Temp\Password.txt"
I took the SecureString and pasted it in my Script that looks like this:
$User = "DOMAIN\USER"
$PwHash = "01000000d08c9ddf0....."
$MyCredential=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, ($PWHash | ConvertTo-SecureString)
Invoke-Command -ComputerName "MyServer" -ScriptBlock {Get-Service -Name "MyService" | Set-Service -Status Running} -Credential ($MyCredential)
The failure pops up by the $MyCredential row:
ConvertTo-SecureString: Key in specific Status is not valid.
I have nowhere read that for an ConvertTo... cmd are Admin rights needed.
Enable-PSRemoting is active on the specific Server.
Thanks for your time and engagement
Dirty.Stone
IMHO, you're going about this all wrong. This is an example of the kind of task you would use JEA (Just Enough Admin) for. Create a constrained, delegated session on the target server, configured with a function for starting or restarting that service and running under a local account that has permission to control the service, and then grant the non-admin users permission to use that session.

Unlocking an AD user with Powershell

I’m new to Powershell and am struggling to make a script work. I’ve read many articles here on Overflow and elsewhere and don’t see what I’m doing wrong. Any help would be appreciated.
I'm trying to create a script that will unlock an AD user remotely while I'm logged-on to may computer as a local admin. Here's my script:
Import-module Activedirectory
New-PSSession -ComputerName <Remote ComputerName> -Credential
<domain admin credential>
Import-Module Activedirectory
Unlock-ADAccount
Read-host “Press any key”
I try to execute this from my computer logged-on as a local admin, but pass domain admin credentials. The script is run as an administrator in Powershell. After I enter my domain password and indicate which user I want to unlock, the message I get is: “Insufficient access rights to perform the operation”.
If I run this code interactively in Powershell, line by line, it will unlock the account. If I run a script asking only to see if the user is locked, it will give me an answer. If I run the above script from my computer logged-on as the domain admin, it will run and unlock the user.
I don’t understand why it will not run when I’m logged-on as local admin, given that I’m passing domain admin credentials. Any help would be appreciated.
You're creating a PSSession, but not using it. Try something like this (untested):
$computer = "test1"
$cred = Get-Credential
$user = Read-Host User to unlock
$sess = New-PSSession -ComputerName $computer -Credential $cred
Invoke-Command -Scriptblock { param($ADuser) Import-Module Activedirectory; Unlock-ADAccount -Identity $ADuser } -ArgumentList $user -Session $sess
Read-host “Press any key”
Although you could create a PSSession, if you have RSAT installed and have access to the ActiveDirectory module there is no need to do that. Instead, just use the credential parameter on each AD cmdlet. For instance, to unlock a user account using alternate credentials, use the following:
Unlock-ADAccount -Identity username -Credential (get-credential)

Access Denied - Powershell

I'm having a bit of a wierd problem.
At my company we use seperate admin accounts for all AD modification puposes (for eg. if my normal AD ID is User01 then my admin a/c wud be something like User01_adm -> this has the modification rights over ad users / groups). Now, i can make changes like say change the login script from ARS web console using my adm a/c but if i use the same in powershell script i get "Access denied" [System.UnauthorizedAccessException]. Is there a difference between the way these both are setup (web console & powershell console?)
I'm using below part for connecting to ARS server with my adm credentials:
#Connect to ARS server
$GetCreds = Get-Credential -Credential $null
$ConnectARS = Connect-QADService -service $ArsServer -Proxy-Credential $GetCreds
#make changes
$PopulateData = Set-QADUser -Identity $UserID -Credential $GetCreds -ObjectAttributes #{scriptPath=$LogonScr}
Can any1 pls point wht am i doing wrong?
Any help would be highly appreciated...
I've nowhere to try it, but shouldn't it be:
#Connect to ARS server
$GetCreds = Get-Credential -Credential $null
$ConnectARS = Connect-QADService -service $ArsServer -Credential $GetCreds
#make changes
$PopulateData = Set-QADUser -Identity $UserID -Connection $ConnectARS -ObjectAttributes #{scriptPath=$LogonScr}
Ok, got it figured out, it was too simple:
it was mere -Proxy switch missing in Set-QADUser statement
working fine now, thx all for help :)

Powershell Server Network drive

I have a client and a server. The client will call a script like:
#Predefine necessary information
$Username = "Niels"
$Password = "password"
$ComputerName = "192.168.1.51"
$Script = {powershell c:/build/jclbuild2.bat}
#Create credential object
$SecurePassWord = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $Username, $SecurePassWord
#Create session object with this
$Session = New-PSSession -ComputerName $ComputerName -credential $Cred
#Invoke-Command
$Job = Invoke-Command -Session $Session -Scriptblock $Script
echo $Job
#Close Session
Remove-PSSession -Session $Session
On the server the jclbuild2.bat will run and access a network drive like \\otherserver\something, it says access denied if I do this command:
cmd.exe /C copy "\\server\file1.pdf" "\\server2\file1.pdf"
How do I access a network drive from a powershell file on a remote server? The user I use with the $username and $password should have access to the network drive.
I think it's a double hop issue, which I don't know how to solve.
You can't do this using the default authentication mechanism. You need to use an authentication mechanism that allows you to flow credentials, not just identity. Kerberos is one of these. CredSSP is another that is built into Windows starting from Vista/Server 2008 onwards.
I have experience setting up CredSSP. Note that there is some security risk because the target machine will have access to the credentials as plain text.
To set it up you will need to run two commands (both from an elevated shell). One on the machine you are running the above script on (the client) and another on the target that you will be connecting to via remoting (the server).
Enable-WSManCredSSP -Role Client -DelegateComputer $ComputerName -Force
This enables delegation to $ComputerName from the client (note you may have to use the FQDN). For security reasons you should avoid using the wild card '*' although you might consider using '*.mydomain.int' to enable delegation to all machines on the domain.
On the target server
Enable-WSManCredSSP -Role Server
Then when you create the session use the -Authentication flag
$Session = New-PSSession -ComputerName $ComputerName -credential $Cred -Authentication Credssp
There are questions on ServerFault on setting up CredSSP. There is also a blog post here with additional explanation. This post has troubleshooting tips for some commonly encountered error messages.
Another option is to use a delegated session on your server.
Basically, you create a custom remote session that uses the -RunAs parameter to designate the credentials that the session will run under. You can also constrain what scripts and cmdlets can be run in the session and specify who can connect to the session.
In this case, the session would run as the Niels account, and everything done in the session would be under that account authority, regardless of who was connected to the session. From that session, you can now make one hop to another server without needing CredSSP.
This also eliminates the security risk involved in storing that account password in the script file on the client computer.
http://blogs.technet.com/b/heyscriptingguy/archive/2014/04/03/use-delegated-administration-and-proxy-functions.aspx