"Access denied" error when trying to enumerate drives on remote computers - powershell

I am trying to run a PowerShell command to get the total disk space of all drives for all our remote servers. When I run the command I am getting the error below. I have a text file which has names of the servers and I have also confirmed that WinRM is configured and is running.
$Servers = Get-Content "C:\users\anorris\desktop\DR\servers1.txt"
foreach ($s in $Servers) {
Invoke-Command -ComputerName $s {Get-PSDrive}
}
Error:
[ahv-a2acortst02] Connecting to remote server failed with the following error
message : Access is denied.
For more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (:) [], PSRemotingTransportException
+ FullyQualifiedErrorId : PSSessionStateBroken

Agreed that the message 'Access is denied' is a dead giveaway that you don't have access.
I would create a credential variable and make sure it is a credential that has rights to the remote system.
$Creds = Get-Credential
then change your code to the following (I added the -scriptblock and the bolded text
$Servers = Get-Content "C:\users\anorris\desktop\DR\servers1.txt"
foreach ($s in $Servers) {
Invoke-Command -ComputerName $s -ScriptBlock {Get-PSDrive} -Credential $creds
}

Related

Test-Path Access denied Error - To check if Directory Exists on Shared Drive/Folder using powershell with credentials

I am trying to check if folder exists on network location using Test-Path powershell script with different credential having access to the Network Server but I am getting access denied error. Below is my script which I am trying to execute on local from where I am trying to connect to Network server:
$username="username"
$pass = "#Passw0rd" | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username,$pass
$pathExists = Invoke-Command -ComputerName . -Credential $cred -ScriptBlock {
Test-Path "\\serverName\Folder"
}
Write-Host $pathExists
I am getting below error:
Access is denied
+ CategoryInfo : PermissionDenied: (\serverName\Folder:String) [Test-Path], UnauthorizedAccessException
+ FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.TestPathCommand
+ PSComputerName : localhost
Note: Admin access for the account is given which is used for accessing Network path and directory
Any help will be much appreciated
The issue most likely is because the credentials stored in $cred don't have Admin privileges on your localhost, hence cannot impersonate your invocation.
Here I'm trying something similar to what you're trying, the user stored in $cred is an Administrator on remote host but does not have any permissions on my laptop (I'm obfuscating for obvious reasons):
PS C:\> icm remoteServer -Credential $cred {test-path \\remoteServer\c$\users}
True
PS C:\> icm remoteServer -Credential $cred {test-path \\localhost\c$\users}
True
PS C:\> icm -computername . -Credential $cred {test-path \\localhost\c$\users}
[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
Edit:
Here is another solution to your problem, Start-Process using the remote credentials and save the results to a file (again obfuscating the name of the remote server):
$argument="-c `"`$path='\\remoteServer\c$\users';'Attempting Test-Path '+`$path;'Result is: '+(Test-Path `$path)`""
$initHash=#{
FilePath='powershell.exe'
Credential=$cred
ArgumentList=$argument
RedirectStandardOutput="$HOME\Documents\testPath.txt"
WindowStyle='Hidden'
}
Start-Process #initHash
PS C:\> gc "$HOME\Documents\testPath.txt"
Attempting Test-Path \\remoteServer\c$\users
Result is: True

powershell remote script execution errors

I notice an error " Connecting to remote server usa-chicago failed with the following error message : Access is denied. For more information, see the
about_Remote_Troubleshooting Help topic
CategoryInfo : OpenError: (usa-chicago:String) [], PSRemotingTransportException
FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken
". Below is the snippet used. Any suggestions?
All the machines are inside a workgroup.
$computers = gc "C:\servers.txt"
$source = "\\usa-chicago\c$\temp\one.jar"
$destination = "c$\july1\folder1\"
foreach ($computer in $computers) {
Invoke-Command -Computername $computer -ScriptBlock { & Copy-Item $using:source -Destination \\$using:computer\$using:destination -Force }
}
Does your user account have access both to the computer and also the share you try to copy something to? It could be that you hit the dreaded 'second hop' problem with PowerShell Remoting: https://learn.microsoft.com/en-us/powershell/scripting/learn/remoting/ps-remoting-second-hop?view=powershell-7
If this is the problem, there are some workarounds for that. What i like to do is:
In the Invoke Command, create a Scheduled Task with the commands you'd like to execute and pass the credentials into it, execute it, and delete it after.

Running Powershell script using inline admin credentials to start and stop windows services

I have access as an admin on a machine and I have to Start, Stop and Restart some of the window services using the Powershell script. We don't want to have UAC prompt while running the script because only one user would have access to that machine. Also due to some specific requirements, we have to have run that script file by adding the admin credentials inside it.
Along with other solutions I have tried so far, the one close to what I am looking for is as follows
$username = "Domain\user"
$password = ConvertTo-SecureString "myPassword" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential -ArgumentList ($username, $password)
Set-Service -Name Spooler -Status Running -PassThru -Credential $psCred
But I am getting following error.
Set-Service : A parameter cannot be found that matches parameter name
'Credential'. At line:6 char:53
+ ... t-Service -Name Spooler -Status Running -PassThru -Credential $psCred
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Service], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SetServiceCommand
Update 1 (Trying suggestion)
Invoke-Command -credential $psCred -command {Set-Service -Name Spooler -Status Running -PassThru} -computername myComputerName
[myComputerName] Connecting to remote server myComputerName failed
with the following error message : The client cannot connect to the
destination specified in the request. Verify that the service on the
destination is running and is accepting requests. Consult the logs and
documentation for the WS-Management service running on the
destination, most commonly IIS or WinRM. If the destination is the
WinRM service, run the following command on the destination to analyze
and configure the WinRM service: "winrm quickconfig". For more
information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (myComputerName:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : CannotConnect,PSSessionStateBroken
Update 2
I had to enabled PSRemoting on machine using command Enable-PSRemoting -Force -SkipNetworkProfileCheck so Invoke-Command can execute but after repeating the command Invoke-Command -credential $psCred -command {Set-Service -Name Spooler -Status Running -PassThru} -computername localhost I got following error
[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
Running the same set of command in elevated powershell window is working fine.
Can you please guide me in the right direction considering I am newbie in the Powershell world.
As mentioned in the official documentation of Set-Service
Can you try like this?
$Cred = Get-Credential
$hostname = "$env:computername.$env:userdnsdomain"
Write-Host $hostname
Invoke-Command -ComputerName $hostname -Credential $Cred -ScriptBlock{ Start-Service -Name Spooler}
Also if you don't want to prompt for the credentials then you can store the credentials in the Windows credentials manager and get it from their in your PowerShell script. Refer to this answer for using credential manager with PowerShell

New-PSSession - WinRM cannot process the request

I am trying to list all the websites in IIS on a remote server using PowerShell scripting. Below is how I am trying to connect to the server:
$s = New-PSSession -ComputerName $Server
But when I run the script I am getting the following error:
New-PSSession : [Server] Connecting to remote server Server failed with the
following error message : WinRM cannot process the request. The following error
occurred while using Kerberos authentication: Cannot find the computer Server.
Verify that the computer exists on the network and that the name provided is
spelled correctly. For more information, see the about_Remote_Troubleshooting
Help topic.
At C:\AppServers\Application.ps1:8 char:8
+ $s = New-PSSession -ComputerName Server
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : NetworkPathNotFound,PSSessionOpenFailed
The server is already enabled to receive remote requests.
Update:
Below is the full function that i am trying to run:
function audit-servers {
if (Test-path "ApplicationsOnTheServer.txt") {Remove-Item "ApplicationsOnTheServer.txt"}
if (Test-Path "ServersList.txt") {
foreach ($server in Get-Content .\ServersList.txt) {
"Application Server : $server`n" | out-file -FilePath "ApplicationsOnTheServer.txt" -Append
"Applications list:" | out-file -FilePath "ApplicationsOnTheServer.txt" -Append
$s = New-PSSession -ComputerName $server -Credential domainabc\myname
Invoke-Command -Session $s -ScriptBlock {Import-Module WebAdministration;Get-iissite} | out-file -FilePath "ApplicationsOnTheServer.txt" -Append
}
} else {
"ServersList.txt file is missing"
break;
}
"`nAll Done!`n"}
The ServersList.txt has atstappvmabc.tsteag.com
The error message clearly states that you wanted to connect to the server named Server not to the server which name is stored in $Server variable (text in bold is actually the name of the server you try to connect to):
New-PSSession : [Server] Connecting to remote server Server failed
If you tried to connect to the server named for example MyServer01.example.com you'd receive the error like below (truncated):
PS C:\> New-PSSession -ComputerName "MyServer01.example.com"
New-PSSession : [MyServer01.example.com] Connecting to remote server MyServer01.example.com failed (...)
Even though you state that you try to execute
$s = New-PSSession -ComputerName $Server
You actually execute (notice missing dollar sign)
$s = New-PSSession -ComputerName Server
The above was also taken from the error message you pasted. I'd suggest to first skip the variable and try to enter server path in the command itself to verify it's working:
$s = New-PSSession -ComputerName "MyServer01.example.com"
And then, if it works, put the path in variable and test again.
The error you're receiving FullyQualifiedErrorId : NetworkPathNotFound generally means that the name you're passing to the -ComputerName parameter can't be resolved.
Perhaps try running Test-Connection $Server to troubleshoot what's happening there.
Your variable $Server contains wrong value. You have to assign valid computer name to $Server.

Invoke-Command with parameter computername on local device

I'm writing a script that needs to be used on multiple devices.
This script uses an Invoke-command to connect to a specified server.
This script also has to be run on this same server.
Invoke-Command -ComputerName $Server -Credential $Cred -ScriptBlock {Write-Host "test"}
It's no problem to run this script from remote devices but when running it on the server used in $Server I get the following error
Connecting to remote server DC01 failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (DC01:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken
My question is if there is a possibility to fix it or if I have to write an if/else to check on which server it's running atm.