Access is Denied when Reset-ComputerMachinePassword is run through Invoke-command - powershell

I'm using the following command to reset a remote machine'
s password.
$user="Domain\domainadmin";
$pass="dapassword" | ConvertTo-SecureString -AsPlainText -Force;
$creds=New-Object System.Management.Automation.PSCredential -ArgumentList $UserName, $pass;
Invoke-Command -Credential $creds -ComputerName "DomainControllerMachine" -ScriptBlock{
$ComputerName = #"
SomeRemoteHost
"#
Import-Module ActiveDirectory;
Reset-ComputerMachinePassword -Server ${ComputerName};
}
I keep getting 'Access is denied' error.
This command cannot be executed on target computer('DomainControllerMachine') due to following error: Access is
denied.
+ CategoryInfo : InvalidOperation: (DomainControllerMachine:String) [Reset-ComputerMachinePasswor
d], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.ResetCompute
rMachinePasswordCommand
The account I use has all levels of access to the ActiveDirectory. So there won't be a issue with the credentials used for authentication.
If I run the same command on the 'DomainControllerMachine' (logged in as same user) it works fine.
Import-Module ActiveDirectory;
Reset-ComputerMachinePassword -Server "SomeRemoteHost";
Even the whole invoke-command block above just works without complaining on the DomainControllerMachine.
But when I do it remotely through Invoke-Command, or Enter-PSSession I get that dreaded access denied error..
I've also tried using CredSSP after setting up the WSManCredSSP (Client, delegation and Server) on the machines with no luck.
I may have missed something, or is there a better way to handle such a case?

It looks to me like you are running the Reset-computermachinepassword command on the domaincontroller. As far as I know it should be run on the computer that needs to be reset with the DC name in the -server field.
To do this you would need to run the command on the computer that needs it's credentials reset:
Reset-Computermachinepassword -server "DomainControllerMachine" -credential $PScredential
You can try to do it remotely with a PSsession if the computer has powershell remoting enabled. You will need to specify a different authentication method to reach a computer that has lost it's trust with the domain.
You can use Credssp but this will only work if your GPO allows delegating your credentials to the target computer.
Or you can use Basic authentication. But for that to work the Target must accept unencrypted traffic.
The command to do it remotely would probably look something like this:
$session = new-PSSession "targetcomputer" -Authentication Basic -Credential "Domain\domainadmin"
Invoke-Command -Session $session -scriptblock {Reset-Computermachinepassword -server "Domain\domainadmin"}

Related

CredSSP - Access is denied. For more information, see the about_Remote_Troubleshooting Help topic

The error:
New-PSSession : [{Public IP of my remote server}] Connecting to remote server
{Public IP of my remote server} failed with the following error message :
Access is denied. For more information, see the about_Remote_Troubleshooting
Help topic.
At C:\Scripts\Test.ps1:24 char:12
+ $Session = New-PSSession -Computer $target -Authentication Credssp -C ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed
The "about_Remote_Troubleshooting" seems to be referring to this post which I've tried to follow along, but without luck.
I have a scripting server (Server A) that I'm trying to have manage a remote DC with a different hosting company.
DISCLAIMER: Since I've been failing miserably so far, I'm trying to set my configuration to be as wide-open as possible (AKA: temporarily unsecure), so that I can just see it working and then work backwards, tightening my security - as much as I can given that I'm being tasked with CredSSP in the first place... Also, I'm way over my head in this and very new to Powershell. With that in mind...
Configuration I've done on Server A:
Set-Item WSMan:\localhost\Client\TrustedHosts -Value * -Force
Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB -Value 0 -Force
Enable-PSRemoting
Set-ExecutionPolicy Unrestricted
Enable-WSManCredSSP –Role Client –DelegateComputer *
Configuration I've done on Server B:
Enable-PSRemoting
Enable-WSManCredSSP –Role Server
And for kicks, on both machines, I've run gpedit and went under Local Computer Policy → Computer Configuration → Administrative Templates → System → Credentials Delegation... enabled "Allow delegating fresh credentials" and "Allow delegating fresh credentials with NTLM-only server authentication" and added * and wsman/* to the servers list (and a few other possible combinations of IP or computer names for good measure).
So, I can send remote commands to Server B without CredSSP:
This works:
$cred = New-Object System.Management.Automation.PSCredential $username, $securePassword
Invoke-Command -ComputerName $target -Credential $cred -ScriptBlock {
Write-Host $env:computername | Select-Object
}
(Outputs name of Server B)
But if I pass that same $cred into a New-PSSession with CredSSP, that is where the error above occurs.
$Session = New-PSSession -Computer $target -Authentication Credssp -Credential $cred
Server A is able to use CredSSP with a different Domain Controller (in the same network/hosting company). Every article I've gone through seems to lead me to believe that what I've done should work in both cases... What am I missing?

Unresolved parameters (Invoke-Command)

When running the code below I get the error message
Invoke-Command : Missing an argument for parameter 'ComputerName'. Specify a
parameter of type 'System.String[]' and try again.
At line:11 char:16
+ Invoke-Command -ComputerName -ScriptBlock $scriptblock -Credential $Cred -Argum ...
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-Command],
ParameterBindingException
+ FullyQualifiedErrorId : MissingArgument,Microsoft.PowerShell.Commands.InvokeCommandCommand
The code:
$item = "1337"
$username = "username"
$password = "password"
$Cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, ($password | ConvertTo-SecureString -AsPlainText -Force)
$scriptblock = {
New-PSDrive -Name SampleDC -PSProvider FileSystem -Root \\sampleDC\scripts
."C:\scripts\sample.ps1" # include global functions scripts
new_user $args[0] # new_user is a function in global functions
}
Invoke-Command -ScriptBlock $scriptblock -Credential $Cred -ArgumentList $item
You cannot run Invoke-Command with different credentials without specifying a computer. The error you're getting is because you used the parameter -ComputerName without an argument.
To have Invoke-Command run the scriptblock on the local computer use either of the following commands:
Invoke-Command -Computer . -ScriptBlock $scriptblock -Credential $Cred ...
Invoke-Command -Computer localhost -ScriptBlock $scriptblock -Credential $Cred ...
Invoke-Command -Computer $env:COMPUTERNAME -ScriptBlock $scriptblock -Credential $Cred ...
Note that if the user whose credentials you're passing does not have admin privileges you'll be getting an error like this:
[localhost] Connecting to remote server localhost failed with the following
error message : Access is denied. For more information, see the
about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (localhost:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken
In that case you need to enable PowerShell Remoting for them first. Run the following command in an elevated PowerShell console and add the user or group in the dialog that pops up.
Set-PSSessionConfiguration Microsoft.PowerShell -ShowSecurityDescriptorUI
From the documentation:
HOW TO ENABLE REMOTING FOR NON-ADMINISTRATIVE USERS
ERROR: ACCESS IS DENIED
To establish a PSSession or run a command on a remote computer, the user must have permission to use the session configurations on the remote computer.
By default, only members of the Administrators group on a computer have permission to use the default session configurations. Therefore, only members of the Administrators group can connect to the computer remotely.
To allow other users to connect to the local computer, give the user Execute permissions to the default session configurations on the local computer.
The following command opens a property sheet that lets you change the security descriptor of the default Microsoft.PowerShell session configuration on the local computer.
Set-PSSessionConfiguration Microsoft.PowerShell -ShowSecurityDescriptorUI
The computername parameter is missing. I believe you need to be at an elevated prompt to invoke-command on localhost.

Office 365 Powershell issue with Set-UserPhoto for anyone other than myself

I'm a global admin for our 365 environment and I'm having an issue with the Set-UserPhoto command in powershell. If I run it for my own username, it works just fine but if I run it using anyone else's username, it errors. Is there some kind of access I need to give myself to make this work? I'm a domain admin and global administrator in 365 so I should be able to do anything.
Connected through PowerShell 3.0 using the following:
$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/?proxyMethod=RPS -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session
Command I'm running:
Set-UserPhoto –Identity username -PictureData ([System.IO.File]::ReadAllBytes("C:\userpics\username.jpg"))
Works fine for my username, for any other username I get this:
Error on proxy command 'Set-UserPhoto -Identity:'username' -PictureData: Tons of numbers here that scrolls for quite a while -Confirm:$False' to server BN3PR0201MB1027.namprd02.prod.outlook.com: Server version 15.01.0534.0000, Proxy method
RPS:
The WinRM client cannot process the request. The connection string should be of the form
[://][:][/] where transport is one of "http" or "https". Transport, port and suffix are
optional. The host may be a hostname or an IP address. For IPv6 addresses, enclose the address in brackets - e.g.
"http://[1::2]:80/wsman". Change the connection string and try the request again. .
+ CategoryInfo : NotSpecified: (:) [Set-UserPhoto], CmdletProxyException
+ FullyQualifiedErrorId : Microsoft.Exchange.Configuration.CmdletProxyException,Microsoft.Exchange.Management.Reci
pientTasks.SetUserPhoto
+ PSComputerName : outlook.office365.com
just ran into the exact same problem.
the solution was to run Microsoft Azure Active Directory Module for Windows PowerShell 'as administrator' (Elevated)
as seen here https://www.blackforce.co.uk/2016/09/23/set-userphoto-error-proxy-command
If you are in hybrid mode and thumbnailPhoto property is synched, you can only change the user photo in your local Active Directory and not in Office 365 Exchange PowerShell session.
If you are not in hybrid mode you can try this sample code instead:
Set-UserPhoto "username" -PictureData ([Byte[]] $(Get-Content -Path "C:\userpics\username.jpg" -Encoding Byte -ReadCount 0)) -Confirm:$false
I had the same issue, and solved it from another post (I don't remember which one).
In the connection string:
$LiveCred = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri **https://outlook.office365.com/powershell-liveid/?proxymethod=rps** -Credential $LiveCred -Authentication Basic -AllowRedirection
Import-PSSession $Session

Invoking-Command for Exchange in Powershell - block is not allowed in a Data section

What I'm trying to do is run this script:
$WPFcmdCreateNewUser.Add_Click({
$ScriptBlockContent = {
param ($first,
$last,
$upn,
$ou,
$password
)
$encryptedpass = ConvertTo-SecureString -AsPlainText $password -Force
New-RemoteMailbox -Name $name -OnPremisesOrganizationalUnit $ou -UserPrincipalName $upn -FirstName $first -LastName $last -Password $encryptedpass -ResetPasswordOnNextLogon $false
}
$ex = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://SERVERNAME/PowerShell/
Invoke-Command -Session $ex -ScriptBlock $ScriptBlockContent -ArgumentList ($WPFtxtNewFirstName.Text, $WPFtxtNewLastName.Text, $WPFtxtNewAlias.Text, $WPFcboNewOU.SelectedItem.Content, $WPFtxtNewPassword.Text)
})
But it's giving me the error:
ERROR: A Begin statement block, Process statement block, or parameter statement is not allowed in a Data section.
ERROR: + CategoryInfo : ParserError: (:) [], ParseException
ERROR: + FullyQualifiedErrorId : InvalidScriptBlockInDataSection
ERROR: + PSComputerName : SERVERNAME
I'm running the whole command from a button click in a XAML Powershell GUI. I googled alot trying to solve the problem as I usually do but no luck :(
Any help would be GREATLY appreciated.
It looks like Exchange uses restricted language mode for remote sessions and you can't execute scriptblocks in your session.
As a security feature, the language mode is obviously controlled at
the server (Exchange), so if you want to enable execution of
scriptblocks you need to interactively logon (RDP or console) to
Exchange and create a new session configuration via
Register-PSSessionConfiguration. You may then connect to Exchange
using this session configuration via New-PSSession -ConfigurationName
and you will then be able to execute scriptblocks by passing this
session instance to Invoke-Command -Session.
Reference:
Remote powershell scriptblock execution question
Bit of an old bump here, but seeing as it is rather high on Google search I figured I could add how I fixed this issue:
$DomainCredential = (Get-Credential)
$fqdn = "<The fully qualified domain name of the target server>"
#Creates a session to the Exchange Remote Management Shell so that we can run Exchange commands. Use https:// if you have a proper setup with certificates. ( Mine was in test env )
$ConfigSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://$fqdn/powershell `
-Credential $DomainCredential -Authentication Kerberos
#Imports the module that exists in the session, in this case, Exchange Management -AllowClobber gives the imported commands presedence.
Import-Module (Import-PSSession $ConfigSession -AllowClobber)
This imports the Exchange Commands as you would in a local session. The Exchange commands will still be executed on the remote server. Remember to close the session when done.

Powershell : Accessing shared drive from remote server

I am trying to access shared drive vai remote server in my Powershell script. My code is below:
$bypass1 = "config"
$bypass2 = "web.config"
$Username = "test\newtest"
$Password = "xxxxxxxxx"
$srv = "xxx.xxx.xxx.xxx"
$securePassword = ConvertTo-SecureString -AsPlainText -Force $Password
$cred = New-Object System.Management.Automation.PSCredential $Username, $securePassword
$session = New-PSSession -ComputerName $srv -port 22 -Credential $cred
Invoke-Command -Session $session -ScriptBlock {
$computer = "xxx.xxx.xxx.xxx"
test-path \\$computer\netlog\php
Get-ChildItem \\$computer\netlog\
}
Remove-PSSession -Session $session
When I tried to access shared from Remote Desktop Connection on the server it is working but through powershell it is throwing following error.
False
Cannot find path '\\xxx.xxx.xxx.xxx\netlog\' because it does not exist.
+ CategoryInfo : ObjectNotFound: (\\xxx.xxx.xxx.xxx\netlog\:String) [Get-Ch
ildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCom
mand
+ PSComputerName : xxx.xxx.xxx.xxx
I am having Powershell 4 and remote server is windows 2008 R2.
Regards,
Vj
Did you try accessing the following path \\xxx.xxx.xxx.xxx\netlog\ locally? You have the creds to access the server. And also you say the drive is shared. Try accessing the path locally. Not via power-shell. But try the old fashioned way. Using Run. If you are prompted for any credentials to be entered. You may strike off any issues related to permissions. If not... The folder you are trying to access isn't shared at all. Try giving it the required permissions. If this isn't the case please leave a comment.
You might need to enable Multihop Remoting when you access a share from a remote machine and use CredSSP.
The credentials you use to create the remote session are not passed to the share access action by default. I think everyone runs into this problem at least once. :)
http://blogs.technet.com/b/heyscriptingguy/archive/2013/04/04/enabling-multihop-remoting.aspx
http://blogs.technet.com/b/heyscriptingguy/archive/2012/11/14/enable-powershell-quot-second-hop-quot-functionality-with-credssp.aspx