PowerShell Remote Access Configuration - powershell

Trying to configure remote PowerShell access on a server but cannot avoid access denied errors.
What I have done:
Register-PSSessionConfiguration
-Name EngrStudentAdmin
-RunAsCredential domain\delegatedAdmin
-StartupScript 'C:\Scripts\Students\Welcome.ps1'
-ShowSecurityDescriptorUI
(on a single line - displaying above for readability)
Using the permissions GUI, I granted the group DelegatedAdmins Read and Execute permissions. The startup script is just filler.
$welcome = 'Welcome to ' + $env:COMPUTERNAME
Write-Host $welcome
Attempting to connect to the endpoint with
Invoke-Command
-ComputerName $server
-ConfigurationName EngrStudentAdmin
-ScriptBlock { hostname }
fails with the error
AuthorizationManager check failed.
+ CategoryInfo : OpenError: (engr-mgr1.domain.edu:String) [], RemoteException
+ FullyQualifiedErrorId : PSSessionStateBroken
The execution policy on the server is RemoteSigned and the startup script is signed.
The account used to access the server is a member of the DelegatedAdmins group.
Opening a local shell as delegatedAdmin shows that the account has permission to run the startup script.
Using a member of the local admins group, the Invoke-Command, without the ConfiguationName switch (i.e. connecting to the default endpoint), executes so the winrm service is running and PSRemoting enabled.
The delegatedAdmin account has no profile.
What am I missing?

Check that the WMI service is enabled and running, if it's disabled try starting it and then retrying.
Also check the properties of the actual file, it might have been blocked.

are both Domain joined? If not you might take several further steps.
In general: Try this on the remote system: Enable-PSRemoting -Force -Verbose If you see nothing, it was already applied. If not, this will make alle necessary changes for you.
Just in case: Check your Firewall settings :-)
As Dewi mentioned: Check the WMI Service.
Here is a quick hack to enable it (if you want to enforce it):
# Configure WMI
Set-Item -Path wsman:\localhost\client\trustedhosts -Value * -Force -Confirm:$False
# Restart
Restart-Service -Name WinRM -Force
Last but not least: Use the -verbose switch to see more details.
Like this:
New-PSSession -ComputerName $ComputerName -Credential $credencial -Verbose
Cheers
Josh

Related

Powershell forum with button calling script

I have a powershell forum for level 1.
Now it has been asked to add a button that calls an script for solving automatic outlook issues.
The script works when i call it direct on the computer itself (via .\outlook.ps1)
When i add it to the button it does not work.
The button itself works and is visible.
example code:
$button_Outlookrest_Click={
Get-ComputerTXTBOX
Add-logs -text "$ComputerName - Create new Outlook profile"
function button{
Copy-Item -Path "D:\path\Repair_outlook_Profile.ps1" -Destination "\\$ComputerName\C$\local" -Recurse
Invoke-Command -ComputerName $ComputerName -ScriptBlock {C:\local\Repair_outlook_Profile.ps1}
}
}
I have tested the code individual, and the following is working:
Copy-Item -Path "D:\path\Repair_outlook_Profile.ps1" -Destination "\\replaced-with-targetcomputer\C$\local" -Recurse
When i whant to call the script, i use the following:
Invoke-Command -ComputerName $ComputerName -ScriptBlock {C:\local\Repair_outlook_Profile.ps1}
However, above text provides me below error:
PS C:\Users\admin> Invoke-Command -ComputerName targetcomputer -ScriptBlock {C:\local\Repair_outlook_Profile.ps1}
[targetcomputer] Connecting to remote server targetcomputer failed with the following error message : WinRM cannot
complete the operation. Verify that the specified computer name is valid, that the computer is accessible over the
network, and that a firewall exception for the WinRM service is enabled and allows access from this computer. By
default, the WinRM firewall exception for public profiles limits access to remote computers within the same local
subnet. For more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (clienttarget:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : WinRMOperationTimeout,PSSessionStateBroken
i want to avoid them using powershell, as its not the idea of this button.
in the script itself, it does not copy the file to the target computer, it does not run the script using the invoke command.
Is this blocked by company firewall?
Do i have something wrong in my code?
An example button that works without any problem is:
$button_DriverQuery_Click={
$button_DriverQuery.Enabled = $False
Get-ComputerTxtBox
$DriverQuery_command="cmd.exe"
$DriverQuery_arguments = "/k driverquery /s $ComputerName"
Start-Process $DriverQuery_command $DriverQuery_arguments
$button_DriverQuery.Enabled = $true
}
Only this aditional button does not work. And i cannot figure it out at the moment.
What am i doing wrong here?
thank you.

getting error while copying file to remote location using powershell scripts in gitlab runner

I am setting up a GitLab CI/CD pipeline to copy the war file using PowerShell copy-item function. I am getting below error in the pipeline. the user is already an administrator on the gitlab runner computer.
[servername] Connecting to remote server name failed with the
following error message: Access is denied. For more information, see
the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (servername:String) [], PSRemotingT ransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken ERROR: Job failed: exit status 1
Here is my script in .yml file.
GitLab Runner registered in windows server.
Here is my script in .yml file.
envvariable_username - Environment variable configured in gitlab CI/CD settings page
$envvariable_password - Environment variable configured in gitlab CI/CD settings page
- powershell Invoke-Command -ComputerName computer_name -argumentlist $envvariable_username,$envvariable_password -ScriptBlock {
$password = convertto-securestring -String $envvariable_password -AsPlainText -Force
$mycred = new-object -typename System.Management.Automation.PSCredential $envvariable_username, $password
New-PSDrive -Name "s" -PSProvider FileSystem -root "\\\\computer_name\\share" -Credential $mycred
New-PSDrive -Name "z" -PSProvider FileSystem -root "\\\\computer_name\\backup" -Credential $mycred
Copy-Item -Path "s:\\sample.war" -Destination "z:\\sample.war"
}
expected to copy .war file from one server location to another server location
Looking at your script, you try to execute a script block on a remote server without specifying credentials. That means that either the server has no restrictions or you assume that both servers belong to the same domain, so kerberos will be utilized.
In my experience, when the second is the case, most people forget to evaluate on who's behalf is the script executing. Keep in mind that a process inherits the user context of the parent process unless otherwise specified.
That would mean that the user running your script doesn't have the necessary access to the remote server. You can always evaluate this by first doing this $env:USERDOMAIN + "\" + $env:USERNAME
For example a line in your yaml
- powershell $env:USERDOMAIN + "\" + $env:USERNAME
So when you debug something from a console that you launched with your user, then you don't have 100% replication of the conditions as you are forgetting the most important aspect of any process, that is the logon user.
Then, if this works, I've noticed that from the remote server you are trying to access another remote location. I notice that you are specifying credentials for this part if please do note that if from within a remote session, you try to access any remote resource, then you need to be aware of some caveats. Please read more about them hereand especially the one specific to the double hop.
As a word of advice, best way to troubleshoot scripts that utilize remote execution, is to logon on the server with the same user as with the services that runs your scripts, thus replication the conditions 100%. It is also possible to launch only the console with the credentials of another user.

Using Powershell to remotely invoke commands in Azure

I'm writing a series of automation scripts that will allow our developers to stand up a simple development environment in Azure. This environment has 3 primary properties:
There is a client machine (Windows 10) where dev tools like their IDE and code will live.
There is a server machine (Windows Server 2016) where that their scripts will target.
Both of these machines live in the same domain, and 1 Domain Admin user is available for use.
I have steps 1 and 2 scripted out, but 3 is currently a mess. Since the script is designed to work from the Developer's local workstation, I need to have the script remote in to the Windows Server and run a few commands to set up the Domain Controller.
Here is my code currently:
Invoke-Command -ComputerName "$RGName-$VMPurpose" -ScriptBlock
{
$ADFeature = Install-WindowsFeature AD-Domain-Services
If ($ADFeature.Success -eq $true)
{
Import-Module ADDSDeployment
Install-ADDSForest -CreateDnsDelegation:$false -DatabasePath
"C:\Windows\NTDS" -DomainMode "Win2016R2" -DomainName "$project.com" -
DomainNetbiosName "$project" -ForestMode "Win2016R2" -InstallDns:$true -
LogPath "C:\Windows\NTDS" -NoRebootOnCompletion $false -sysvolpath
"C:\Windows\SYSVOL" -force $true
$domUserPassword = ConvertTo-SecureString "Th1s is a bad password" -
AsPlainText -Force
New-ADUser -Name "$VMPurpose-DomAdm" -AccountPassword
$domUserPassword
Add-ADGroupMember -Name "Administrators" -Member {Get-ADUser
"$VMPurpose-DomAdm"}
}
} -Credential $Cred
When I attempt to run this I get an error showing that WinRM cannot connect, specifically this error:
[Foo] Connecting to remote server Foo failed with the following error
message : WinRM cannot process the request. The following error with
errorcode 0x80090311
occurred while using Kerberos authentication: There are currently no logon
servers available to service the logon request.
Possible causes are:
-The user name or password specified are invalid.
-Kerberos is used when no authentication method and no user name are
specified.
-Kerberos accepts domain user names, but not local user names.
-The Service Principal Name (SPN) for the remote computer name and port
does not exist.
-The client and remote computers are in different domains and there is no
trust between the two domains.
After checking for the above issues, try the following:
-Check the Event Viewer for events related to authentication.
-Change the authentication method; add the destination computer to the
WinRM TrustedHosts configuration setting or use HTTPS transport.
Note that computers in the TrustedHosts list might not be authenticated.
-For more information about WinRM configuration, run the following
command: winrm help config. For more information, see the
about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (Foo:String) [],
PSRemotingTransportException
+ FullyQualifiedErrorId : AuthenticationFailed,PSSessionStateBroken
I added the target machine (Foo) to the TrustedHosts configuration setting in WinRM (I actually added the IP address to make sure that there wasn't any DNS problem happening), and then I get this error:
[Foo's IP] Connecting to remote server <Foo's IP> failed with the following
error message : WinRM cannot complete the operation. Verify that the
specified computer name is valid, that the
computer is accessible over the network, and that a firewall exception for
the WinRM service is enabled and allows access from this computer. By
default, the WinRM firewall exception for public
profiles limits access to remote computers within the same local subnet. For
more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (Foo's Ip[:String) [],
PSRemotingTransportException
+ FullyQualifiedErrorId : WinRMOperationTimeout,PSSessionStateBroken
Any thoughts here? Am what I trying simply not ever going to work via Powershell?
According to your error message, we can use this PowerShell script to invoke command to Azure:
$username = 'jason'
$pass = ConvertTo-SecureString -string 'password' -AsPlainText -Force
$cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $pass
$s = New-PSSession -ConnectionUri 'http://23.99.82.2:5985' -Credential $cred -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck)
Invoke-Command -Session $s -ScriptBlock {Get-Process PowerShell}
PowerShell result like this:
More information about invoke command, please refer to this answer.

Enable PowerShell remoting on new Azure VM

I've created a new VM in Windows Azure to use to act as a host to learn a bit of Powershell Remoting. After the VM was created I RDP'd onto the box and enabled remoting via the following command:
Enable-PSRemoting
I confirmed both prompts with 'a' replies and it finished without errors. If I run
Get-PSSessionConfiguration
I can see that three endpoints (?) have been set up. In the Azure portal I can see that the Powershell port is open - both 5986 is open as a public and private port.
I've added the public IP address of the machine to my hosts file, but when I try the following:
Enter-PSSession -ComputerName AZURESERVERNAME
I get an error:
Enter-PSSession : Connecting to remote server AZURESERVERNAME failed
with the following error message : A specified logon session does not
exist. It may already have been terminated. For more information, see
the about_Remote_Troubleshooting Help topic. At line:1 char:1
+ Enter-PSSession -ComputerName AZURESERVERNAME
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (AZURESERVERNAME:String) [Enter-PSSession],
PSRemotingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed
I've also tried setting all hosts as trused as follows:
cd wsman::localhost\client
Set-Item .\TrustedHosts *
Restart-Service WinRM
But that doesn't seemed to have helped either.
Is there anything else I need to do to get this working?
Thanks
OK, figured this out thanks to the awesome Secrets of Powershell Remoting ebook. Looks like you must add the machine directly to the TrustedHosts via IP address:
Set-Item -Path WSMan:\localhost\Client\TrustedHosts -Value '11.22.33.44'
Then use that IP address and specify credentials in the Enter-PSSession:
Enter-PSSession -ComputerName 11.22.33.44 -Credential 11.22.33.44\username
You should then get a prompt for your password and voila! :)
I've successfully created a SharePoint farm in Azure using the scripts from Automated-Deployment-of-SharePoint-2013-with-Windows-Azure-PowerShell
On that page there are steps that configure PowerShell to work with Azure
Set-ExecutionPolicy ByPass
Enable-PSRemoting
Enable-WSManCredSSP -role client -delegatecomputer "*.cloudapp.net"
$regKey = "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\Credssp\PolicyDefaults\AllowFreshCredentialsDomain"
Set-ItemProperty $regKey -Name WSMan -Value "WSMAN/*.cloudapp.net"
Get-AzureSubscription -ExtendedDetails
You may also need to do this
Run GPEdit.msc You must also enable delegating of fresh credentials
using group policy editor on your client machine. Computer
Configuration -> Administrative Templates -> System -> Credentials
Delegation and then change the state of "Allow Delegating Fresh
Credentials with NTLM-only server authentication" to "Enabled." Its
default state will say, "Not configured."
In the Add Servers sections add the following.
WSMAN/*.cloudapp.net

Cannot create remote powershell session after Enable-PSRemoting

I can not remote into any machine to save my life! I have tried everything I can find. If anyone could troubleshoot or guide me, I'd appreciate it as this would be a great tool to add on my domain.
SETUP:
Client machine inside domain
Server machine inside or outside domain - Virtualized and utilized for WSUS Computername: wsustest
CLIENT SERVER MACHINE physical- computername: epizzi-pc
STEPS:
enable-pssremoting done! on all machines
trustedhosts configured with * or client machine added
Firewalls with public profile off just in case
Enter-PSSession -ComputerName wsustest -Credential wsustest\administrator
Enter-PSSession -ComputerName epizzi-pc -Credential epizzi-pc\administrador
Enter-PSSession : Connecting to remote server epizzi-pc failed with the following error message : WinRM cannot process the request. The following error with errorcode 0x80090311
occurred while using Kerberos authentication: There are currently no logon servers available to service the logon request.
Possible causes are:
-The user name or password specified are invalid.
-Kerberos is used when no authentication method and no user name are specified.
-Kerberos accepts domain user names, but not local user names.
-The Service Principal Name (SPN) for the remote computer name and port does not exist.
-The client and remote computers are in different domains and there is no trust between the two domains.
After checking for the above issues, try the following:
-Check the Event Viewer for events related to authentication.
-Change the authentication method; add the destination computer to the WinRM TrustedHosts configuration setting or use HTTPS transport.
Note that computers in the TrustedHosts list might not be authenticated.
-For more information about WinRM configuration, run the following command: winrm help config. For more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ Enter-PSSession -ComputerName epizzi-pc -Credential epizzi-pc\administrador
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (epizzi-pc:String) [Enter-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed
Enter-PSSession -ComputerName wsustest -UseSSL -Credential wsustest\administrator
*Enter-PSSession : Connecting to remote server wsustest failed with the following error message : WinRM cannot complete the operation. Verify that the specified computer name is
valid, that the computer is accessible over the network, and that a firewall exception for the WinRM service is enabled and allows access from this computer. By default, the WinRM
firewall exception for public profiles limits access to remote computers within the same local subnet. For more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ Enter-PSSession -ComputerName wsustest -UseSSL -Credential wsustest\administrato ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (wsustest:String) [Enter-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed*
ERRORs:
I was receiving the same problem when remoting to a server and found this blog post very helpful - http://jeffgraves.me/2013/10/14/powershell-remoting/
For my specific case I did the following:
On the Local machine
winrm quickconfig (although this was already configured)
winrm s winrm/config/client '#{TrustedHosts="myservername.domain"}'
On the Remote machine
enable-psremoting -force
Set-PSSessionConfiguration -ShowSecurityDescriptorUI -Name Microsoft.PowerShell -Force
I got around this problem by using a fully qualified logon. Instead of "netbiosdomain\accountname", I used fqdn\accountname, as in Microsoft.com\myaccount in the get-credential prompt. May not work for everyone, but it's worth a shot.
This is how I do it. I use this on my scripts.
# This is only done once
Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File
c:\Windows\temp\securepass.txt
# Setup credentials
$SecureString = Get-Content c:\Windows\temp\securepass.txt | ConvertTo-SecureString
$mycredentials = New-Object -TypeName System.Management.Automation.PSCredential
-ArgumentList "yourDomain\userID",$SecureString
# Open remote session:
$MyRSession = New-PSSession -ComputerName Computer1 -Credential $mycredentials
-Authentication default
# Use remote session:
Enter-PSSession $MyRSession
Get rid of -UseSSL. I enabled PSRemoting and had problems with using that. I guess I could look at it later but for now it doesn't matter.
If there is no trust between the client and server computers, you have to enable basic authentication on the server side. Do this by toggling the correct properties on the WSMAN: drive on the server. You'll obviously have to do this interactively on the console or via remote desktop, due to the chicken and egg problem :) Also, this may come into play too:
http://www.nivot.org/blog/post/2009/10/30/PowerShell20EnablingRemotingWithVirtualXPModeOnWindows7
I was getting that same error currently no logon servers available.
The issue was resolved by using instead of Domain\Username as credentials the user UPN or Username#Domain.
I have achieved a remote session with Enter-pssession command, had to follow these exact parameters
$creds = get-credential (the -credential parameter in enter-pssession does not work properly, thus u must previously enter the object at another variable)
Enter-pssession -computername wsustest -authentication Default -credentials $creds
i Also had to set both client and remote server in the trusted hosts wsman: space
another solution which surely wouldve worked but i havent tried, wouldve been setting https: which is harder to do.
thx to all, your comments certainly led to the solution!