Search code examples
powershellpowershell-remoting

Entering password automatically in enter-pssession


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.


Solution

  • 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