"Access is denied" error during "New-Item" call in PS - powershell

I am trying to create a folder on a server using powershell. The script looks like this:
$pass = ConvertTo-SecureString "myPW" -AsPlainText -Force
$cred = new-object System.Management.Automation.PSCredential("myUser", $pass)
$session = New-PSSession -ComputerName "localhost" -Credential $cred
Invoke-Command -session $session -ScriptBlock {
New-Item -Path "\\myServer\myShare\" -Name "myFolder" -ItemType directory -Force
}
I'm getting the following error:
Access is denied
+ CategoryInfo : PermissionDenied: (\\myServer\myShare:String) [New-Item], UnauthorizedAccessException
+ FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.NewItemCommand
+ PSComputerName : localhost
Access to the path 'myShare' is denied.
+ CategoryInfo : PermissionDenied: (\\myServer\myShare:String) [New-Item], UnauthorizedAccessException
+ FullyQualifiedErrorId : CreateDirectoryUnauthorizedAccessError,Microsoft.PowerShell.Commands.NewItemCommand
+ PSComputerName : localhost
Access to the path 'myFolder' is denied.
+ CategoryInfo : PermissionDenied: (\\myServer\myShare\myFolder:String) [New-Item], UnauthorizedAccessException
+ FullyQualifiedErrorId : CreateDirectoryUnauthorizedAccessError,Microsoft.PowerShell.Commands.NewItemCommand
+ PSComputerName : localhost
At first I thought the message is pretty clear an the user I used is missing rights. But here is the thing: If I go to the share in the Explorer and log in with the same user, I can create a folder without any problems. Besides that, the user is Domain Admin.
What am I doing wrong?

It's a double hop, you're connecting to a PSSession and then trying to access the folder.
As a security measure PowerShell does not allow you to remote to one computer, then remote to another computer from there (even if two of those are the same computer). The exact reasoning is complex and heavily involved in how credentials are used in sessions and I don't fully understand it myself so I won't try to explain but basically it's to prevent the credentials being stolen.
You can do some reading on it (this looks like a good resource) but it would be a LOT simpler to just try to work out another way of doing it. You're only remoting to the local computer so you could for example start another PS process.

If you are just using a PSSession for the alternative credentials to access the share, then using New-PSDrive might be an alternative way to do it:
$pass = ConvertTo-SecureString "myPW" -AsPlainText -Force
$cred = new-object System.Management.Automation.PSCredential("myUser", $pass)
New-PSDrive -Name myShare -PSProvider FileSystem -Root "\\myServer\myShare\" -Credential $cred
New-Item -Path "myShare:\" -Name "myFolder" -ItemType directory -Force

Related

Running Windows updates from poweshell script on remote servers

I know this question has been asked a million times but I am really struggling with this and I would like to be able to add in a few extra features.
I have a list of servers which I would like to input into my script and then I would like the script to go off and check for updates on those servers. After which my aim is to get to it to ask if I want to continue giving the option to input Y/N.
Then I need it to go off and install updates without rebooting. It would be great then to tell me its finished and ask if I want to reboot.
Can anyone help? I am new to powershell and so far only got this which is erroring out.
$creds = Get-Credential
$serverlist = "C:\testlist.txt"
$session=New-PSSession -ComputerName $serverlist
Invoke-Command -Session $session -ScriptBlock {
[net.servicepointmanager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12
Install-module pswindowsupdate -force -AllowClobber
Get-WUInstall -AcceptAll
}
Get-PSSession | Remove-PSSession`
This doesn't get me anywhere and gives this error.
New-PSSession : One or more computer names are not valid. If you are trying to pass a URI, use the -ConnectionUri parameter, or pass URI objects instead of strings.
At C:\Untitled5.ps1:16 char:10
+ $session=New-PSSession -ComputerName $serverlist
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (System.String[]:String[]) [New-PSSession], ArgumentException
+ FullyQualifiedErrorId : PSSessionInvalidComputerName,Microsoft.PowerShell.Commands.NewPSSessionCommand
Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty.
Provide an argument that is not null or empty, and then try the
command again.
At C:\Untitled5.ps1:17 char:25
+ Invoke-Command -Session $session -ScriptBlock {
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand`

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

Getting access denied while running invoke command ,kerberos dula hop delegation authentication error

Hi I am getting below access denied error while accessing file remotely even though I have access to shared location .Kerberos credential delegation is enabled
PS C:\Users> $uname = "abrac\svc-igniopro-connect"
$password = "P#er***" | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $uname,$password
Invoke-Command -ComputerName EABP01IGCHEA01 -Credential $cred -ScriptBlock {Get-Content "\\Ebrfile01\tcs\IT\INFRA IGNIO SOX\vdi NS list 1.csv"}
Access is denied
+ CategoryInfo : PermissionDenied: (\\Ebrfile01\tcs...i NS list 1.csv:String) [Get-Content], UnauthorizedAccessExceptio
n
+ FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetContentCommand
+ PSComputerName : EABP01IGCHEA01
Cannot find path '\\Ebrfile01\tcs\IT\INFRA IGNIO SOX\vdi NS list 1.csv' because it does not exist.
+ CategoryInfo : ObjectNotFound: (\\Ebrfile01\tcs...i NS list 1.csv:String) [Get-Content], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand
+ PSComputerName : EABP01IGCHEA01
You have to enable CredSSP (see: Enable-WSManCredSSP) on both the client and server (necessary for this double hop authentication).
First enable on your client to server direction by running this on your machine:
Enable-WSManCredSSP -Role "Client" -DelegateComputer "EABP01IGCHEA01"
Then on your server EABP01IGCHEA01, enable the Server role so that it can act as a delegate:
Enable-WSManCredSSP -Role "Server"
Then you have to explicitly specify the authentication method as CredSSP as it won't connect with it by default:
Invoke-Command -ComputerName EABP01IGCHEA01 -Authentication Credssp -Credential $cred -ScriptBlock {Get-Content "\\Ebrfile01\tcs\IT\INFRA IGNIO SOX\vdi NS list 1.csv"}
Please note the security implications of enabling CredSSP:
Caution:
CredSSP authentication delegates the user credentials from the local
computer to a remote computer. This practice increases the security
risk of the remote operation. If the remote computer is compromised,
when credentials are passed to it, the credentials can be used to
control the network session.

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

Access to password protected network share (double/second hop limitation)

This is about the famous double-hop limitation that looks trivial and has at least 10 workarounds but I cannot find even one that works for my setup.
Here is my environment: I have ~50 virtual machines on Windows 10, every VM runs on a separate hardware - we use virtual machines because our IT guys claim it's easier to maintain and physical ones, I personally dislike VMs but it's not something that depends on me.
We are on a non-domain environment, no Active Directory, we use a workgroup and every machine is administered individually.
My goal is to optimize PC management like installing software, registering/starting services and etc - I need to do that on all machines at once not to perform each task 50 times. I managed to run PowerShell remote relatively quickly but very soon I stuck on non being able to access any network resource that requires additional authentication (all our network shares requires LDAP authentication).
What I tried so far.
Re-authenticate from the session, described here:
$mappedDrive = #{
Name = "u"
PSProvider = "FileSystem"
Root = "\\bladefs\share2"
Credential = 'svetlozar.draganov'
}
Invoke-Command -ComputerName bw33 -ScriptBlock {
New-PSDrive #using:mappedDrive
Get-Content -Path \\bladefs\share2\text.txt
Get-PSDrive
Remove-PSDrive -Name "u"
Get-PSDrive
} -Credential render
What the above command does is to run a remote command via Invoke-Command that request two authentications, the first authentication is to connect to the machine bw33 then with a New-PSDrive command another authentication is sent to an already establishes session with bw33 to mount a network share with username and password. This sometimes on very rare occasions actually works, but I cannot pinpoint when and why it works and why in most of the cases doesn't work. Even though I'm executing absolutely the same PowerShell script a dozen of times it only works for a very small percentage of them the rest of them it just says this:
A specified logon session does not exist. It may already have been
terminated
+ CategoryInfo : InvalidOperation: (u:PSDriveInfo) [New-PSDrive], Win32Exception
+ FullyQualifiedErrorId : CouldNotMapNetworkDrive,Microsoft.PowerShell.Commands.NewPSDriveCommand
+ PSComputerName : bw33
Cannot find path '\\bladefs\share2\text.txt' because it does not exist.
+ CategoryInfo : ObjectNotFound: (\\bladefs\share2\text.txt:String) [Get-Content], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand
+ PSComputerName : bw33
I actually captured a working and non-working attempt on the video bellow:
https://drive.google.com/uc?id=1HYD8p-VkLYyIExZVWO_8qgpI2kmlUDgF
As you can see with first execution everything is fine PSDrive is mapped successfully and I can reach \bladefs\share2 network path but with second execution I got some errors.
Similar as the above but instead of mapping drive via PSDrive command mapping it via NET USE command with username and password.
Invoke-Command -ComputerName bw33 -Credential render -ScriptBlock {
net use x: \\bladefs\share2 /user:svetlozar.draganov password
Test-Path \\bladefs\share2
}
This, as the first, sometimes works but again it only works once, all subsequent execution leads to this error:
System error 1312 has occurred.
+ CategoryInfo : NotSpecified: (System error 1312 has occurred.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : bw33
A specified logon session does not exist. It may already have been terminated.
Here is a video of another attempt that again captures working and non-working execution of that command:
https://drive.google.com/uc?id=1wP20sbmXMfWu4dvjsdF8REDWgNxiKAS-
Using CredSSP described here:
$session = New-PSSession -cn bw33 -Credential render -Authentication Credssp
Invoke-Command -Session $session -ScriptBlock {Test-Path \\bladefs\share2}
Although this is the most popular and insecure way to resolve this issue I decided to give it a try cause recommended options didn't work. Unfortunately I hit a brick with this approach as well, here are the errors:
New-PSSession : [bw33] Connecting to remote server bw33 failed with
the following error message : The request is not supported. For more
information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:12
+ $session = New-PSSession -cn bw33 -Credential render -Authentication ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : 50,PSSessionOpenFailed
Invoke-Command : Cannot validate argument on parameter 'Session'. The
argument is null or empty. Provide an argument that is not null or empty,
and then try the command again.
At line:2 char:25
+ Invoke-Command -Session $session -ScriptBlock {Test-Path \\bladefs\sh ...
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
And respectively the video:
https://drive.google.com/uc?id=10tbAq6vvRsvT-1SGqOzvPgIPcM-MT8CJ
I had a somewhat similar issue to yours a while back, but I have a domain joined setup. That shouldn't make to much difference as long as you have the credentials. In your example you don't seem to be using an actual PSCredential object, which might be you issue. If you can use the same credential to connect to the remote system and then back to your share then this should work:
$Password = Read-Host -Prompt 'Enter Password' -AsSecureString
$Credential = New-Object -TypeName PSCredential('username',$Password)
$mappedDrive = #{
Name = "u"
PSProvider = "FileSystem"
Root = "\\bladefs\share2"
Credential = $Credential
}
Invoke-Command -ComputerName bw33 -Credential $Credential -ScriptBlock {
New-PSDrive #Using:mappedDrive
# Do Stuff...
Remove-PSDrive -Name "u"
}