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
Related
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
I've been trying to setup a Powershell module that would remotely call Windows/Microsoft update on a server using Invoke-Command, then process the updates, and send everything back to the calling server so it can send an email report.
My issue comes when I try and call the downloader: Powershell seems to be requesting Elevated rights on the remote computer.
Here is a snippet of what I'm trying to run and fail:
Invoke-Command -ComputerName $Server -Credential $Credentials -ScriptBlock {
$UpdateSession = New-Object -ComObject "Microsoft.Update.Session"
Write-Progress -Activity "Updating" -Status "Checking for new updates"
$Criteria = "IsInstalled=0 and Type='Software'"
$Updates = $UpdateSession.CreateUpdateSearcher().Search($Criteria).updates
$Downloader = $UpdateSession.CreateUpdateDownloader()
$Downloader.Updates = $Updates
}
I know the issue isn't with remoting, as the first 4 commands work fine.
The $Credentials variable points to pre-defined credentials, which are Local Admin on the remote server.
When the script gets to the 5th line, $Downloader = $UpdateSession.CreateUpdateDownloader(), I get this error from Powershell:
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
+ CategoryInfo : OperationStopped: (:) [], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException
+ PSComputerName : SERVER.sidlee.inc
What could be causing this exactly ?
Thanks in advance for the help!
As i just hit the same wall, and Google isn't of much help either, here is what i could dig up.
For the record, i am pretty much doing the same thing (using custom PS code to check remote systems for Windows Updates) but using WinRM over Python instead of Invoke-Command and also got stuck on Microsoft.Update.Searcher.Search() throwing a E_ACCESSDENIED error.
The UnauthorizedAccessException is indeed not related to Powershell but the underlying API.
I suspect Microsoft started cutting off impersonation in remote session in some recent update (Powershell v5?) as this was (and still is) working just fine on older Windows versions (e.g. Server 2012 with Powershell v3 or 2012 R2 with v4)
To get around this you will need to authenticate (on the remote server) prior to executing your stuff with a PSCredential object.
So Remote Auth -> Local Auth -> Run stuff for example using Start-Process -Credential ...
e.g.
$pass = ConvertTo-SecureString "PA$$W0RD" -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential "User", $pass
Start-Process -Credential $creds powershell -ArgumentList "-Command & { ... whatever you want to do ... }"
Keep in mind that this poses a security risk as your password will be parsed in clear text, so don't do this over an
unencrypted channel!
Im currently making a Powershell Script in Powershell ISE that is going to be used for entering all of the servers we're hosting and grabbing all the users from the servers ActiveDirectory. To do that I have to connect to all servers automatically (There are many servers but only 42 that we need to access). Let me explain what I've done so far and what te actual problem is.
So as you know there are many different servers, so we had to read all the server IP:S/Usernames/Passwords from a excel file that a colleague made, and then place them into arrays.
From there, we made a for loop looking like this:
for ($S = 0; $ -le $ServerAdressArray.Length; $S++)
{
if ($ServerAdressArray[$S] -like '192.168.*.10')
{
GetData($S)
}
}
What it does is going through the array filtering out all the local IP-Adresses from the array, if it finds a local ip adress, it runs the GetData function which looks like this at the moment:
function GetData([int]$arg1)
{
Enter-PSsession -ComputerName $ServerAdressArray[$arg1] -Credential $UsernamesArray[$arg1] $PasswordArray[$arg1]
}
What I want it to do is to use the row number it found the local IP-Adress on and then use that number to locate the correct Username and Password to log in with on that specific server.
The problem is, i have to enter the password in powershell for every single server. And i just want to enter it on the same line as Enter-PSSession.
If you want more specific details, let me know. Also, I'm new to this type of scripting so if you cold be as basic as possible in your explanations that would be great :)
Thank you.
The problem here is how you're passing the "Credential" parameter. It should be of type PSCredential.
Assuming you've stored the username and password in clear text in your file you can create a credential object directly:
New-Object PSCredential -ArgumentList #("a", ("p"|ConvertTo-SecureString -AsPlainText -Force))
For your example :
Enter-PSsession -ComputerName $ServerAdressArray[$arg1] -Credential (New-object PSCredential -ArgumentList #($UsernamesArray[$arg1], ($PasswordArray[$arg1]|ConvertTo-secureString -AsPlainText -Force)))
However; if you're interested in returning some data for each server back to the executing host (e.g. for further processing) you wouldn't want to enter the session, you would want to use Invoke-command instead.
E.g.
Invoke-command -ComputerName $ServerAdressArray[$arg1] -Credential (New-object PSCredential -ArgumentList #($UsernamesArray[$arg1], ($PasswordArray[$arg1]|ConvertTo-secureString -AsPlainText -Force))) -Scriptblock $scriptblockToExecute
Hi CmdrTchort/Richard (:P). Thank you for the answer!
All the passwords in the excelfile are encrypted for security reasons. I am currently working on a function that will decrypt the password before using it.
I've looked around a bit more on the internet and i stumbled across this post:
Using PowerShell credentials without being prompted for a password
I tried what Jeroen Landheer said and the function now looks like this:
function GetData(int[$arg1])
{
$secstr = New-Object -TypeName System.Security.Securestring
$PasswordArray[$arg1].ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
$session = new-pssession -computername $ServerAdressArray[$arg1] -credential $UserNameArray[$arg1] $PasswordArray[$arg1]
}
The Prompt is appearing so the password hasn't automatically been filled in and when i close the prompt(s). I get this error:
New-PSSession : A positional parameter cannot be found that accepts argument '(encryptedpassword)'.
At C:\xxxxxxx\xxxxx\xxxxxx\superfile.ps1:109 char:16
+ ... $session = new-pssession -computername $ServerAdressArray[$arg1] -cr ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [New-PSSession], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.NewPSSessionCommand
Do I have to enter some kind of positional parameter or does it now work because its encrypted?
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.
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"}