Avatar of jskfan
jskfan
Flag for Cyprus asked on

Add User Name and Password in the Powershell command

Add User Name and Password in the Powershell command

I have this command below that access a file on a computer named windows7 and replaces a string  username with white.
it works when the remote Windows7 computer is logged on with the same username and password I am logged on to this computer I am running Powershell command from.
However now the remote computer is logged on with username: JDock and Password : Passw0rd
how do I include the username and password inside the powershell command ?

Thank you

((Get-Content -path '\\windows7\c$\test.txt' -Raw) -replace ' username', 'white') | Set-Content -Path '\\windows7\C$\test.txt'

Open in new window

PowershellScripting Languages

Avatar of undefined
Last Comment
jskfan

8/22/2022 - Mon
oBdA

You create a mapped drive connection to the remote machine using explicit credentials, edit the file, and remove the connection again.
You can get the credentials using Get-Credential.
Note that you don't need to connect with the logged no user; you just need to connect with any account that has local administrator privileges on the remote machine.
$username = 'JDock'
$credential = Get-Credential -Message 'Logon for the client administrator' -Username $username
$windows7Drive = New-PSDrive -Name Windows7Drive -PSProvider FileSystem -Root "\\windows7\C$" -Credential $credential -ErrorAction Stop
((Get-Content -Path '\\windows7\c$\test.txt' -Raw) -replace ' username', 'white') | Set-Content -Path '\\windows7\C$\test.txt'
$windows7Drive | Remove-PSDrive

Open in new window

jskfan

ASKER
It prompts me to enter Password, I type in the password then I get this error:

PS C:\> C:\changestring.ps1
New-PSDrive : The user name or password is incorrect
At C:\changestring.ps1:3 char:18
+ $windows7Drive = New-PSDrive -Name Windows7Drive -PSProvider FileSystem -Root "\ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (Windows7Drive:PSDriveInfo) [New-PSDrive], Win32Exception
    + FullyQualifiedErrorId : CouldNotMapNetworkDrive,Microsoft.PowerShell.Commands.NewPSDriveCommand

Open in new window

jskfan

ASKER
I got it almost working now. I changed this :
$username = 'JDock'

Open in new window

to
$username = 'DomainName\JDock'

Open in new window


However I do not want the prompt to password , can I hardcode it on the script ?
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
jskfan

ASKER
I also am getting :
New-PSDrive : Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed

Open in new window

oBdA

This will store the password securely; it can only be decrypted on the computer where it was encrypted, and by the user who encrypted it.
$username = 'JDock'
## Run the following command on the computer where you want to store the script, and with the user who executes the script.
## It will copy the complete PowerShell command into the clipboard, from where you can paste it and replace the "$password = ..."
## 'Passw0rd' | ConvertTo-SecureString -AsPlaintext -Force | ConvertFrom-SecureString | % {"`$password = '$($_)'"} | clip.exe
$password = '0101...'

$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, (ConvertTo-SecureString -String $password)

Open in new window


The "multiple connections" means exactly what it says: you already have a network connection open to the remote machine, but with another user account.
If that happens as well in a freshly opened PS console, you've mapped a drive in Explorer.
You can run a "net use" of connections, and delete them accordingly.
An alternative is the use the remote machine's IP address to connect to (both for the drive and the file read/write).
jskfan

ASKER
I used your code above but I am getting this error

ConvertTo-SecureString : Input string was not in a correct format.
At C:\changestring.ps1:13 char:104
+ ... st $username, (ConvertTo-SecureString -String $password)
+                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [ConvertTo-SecureString], FormatException
    + FullyQualifiedErrorId : System.FormatException,Microsoft.PowerShell.Commands.ConvertToSecureStringCommand
 
New-PSDrive : Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all 
previous connections to the server or shared resource and try again
At C:\changestring.ps1:14 char:18
+ $windows7Drive = New-PSDrive -Name Windows7Drive -PSProvider FileSystem -Root "\ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (Windows7Drive:PSDriveInfo) [New-PSDrive], Win32Exception
    + FullyQualifiedErrorId : CouldNotMapNetworkDrive,Microsoft.PowerShell.Commands.NewPSDriveCommand
 

PS C:\> 

Open in new window

⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
oBdA

You need to follow the description in the comment. Line 5 needs to be replaced with the contents of the clipboard created in line 4, not with the plain-text password.
jskfan

ASKER
Sorry , I am confused. Here is the Script. Please let me know what to change.
Thank you.

$username = 'JDock'
$password='Passw0rd'
ConvertTo-SecureString $password -AsPlainText -Force


$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, (ConvertTo-SecureString -String $password)
$windows7Drive = New-PSDrive -Name Windows7Drive -PSProvider FileSystem -Root "\\windows7\C$" -Credential $credential -ErrorAction Stop
((Get-Content -Path '\\windows7\c$\test.txt' -Raw) -replace ' username', 'white') | Set-Content -Path '\\windows7\C$\test.txt'
$windows7Drive | Remove-PSDrivecls

Open in new window

oBdA

OK, let me ask you a question first: embedding plain text passwords in a script is, as you probably know, not recommended.
You can safely embed a password in PS script, provided it is run on the machine where the password was encrypted, and by the user who encrypted the password.
Now, is that script really safe/temporary enough that you want to embed the password in cleartext, or is that something that will run on a regular basis, and the password should be encrypted?
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
jskfan

ASKER
The Script is one time Run to make changes on the remote computer.
ASKER CERTIFIED SOLUTION
oBdA

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
jskfan

ASKER
Thank you,

I will test it later