Is there a way to read a text file D:\SetCredentials.txt which contains credentials and set the values in variables so that I can use those variables in other script.
File looks like this:
serv|16762646t|6879i0i2|9878p989868
I want to set the value of a variable in my script below is the code we use in batch script but i want it in powershell script
For /F "tokens=1-4 delims=|" %%A in (SetCredentials.txt) do (
set username=%%A
set password=%%B
set servername=%%C
set key=%%D
Below is something i wrote, it is just reads and splits the text file -
$credInFile = Get-Content -path "D:\SetCredentials.txt"
$credInFileSplit = credInFile.Split("|")
foreach($i in $credInFileSplit){
echo $i
}
CodePudding user response:
Import-CSV
can handle this easily. Assuming that the format is
username|password|servername|key
you can use
$Credential = Import-CSV -Path "D:\SetCredentials.txt" -Header "Username","Password","ServerName","Key" -Delimiter "|"
You now have a PSCustomObject
with four members Username
, Password
, ServerName
, and Key
, which can be passed as parameters (either as the object entire, or as individual strings, depending on the receiving code) to other cmdlets, advanced functions, or scripts.
(The PSCustomObject
is called $Credential
, and the fields (or members) are called $Credential.UserName
, $Credential.Password
, $Credential.ServerName
, and $Credential.Key
. You can use the individual fields as though they were separate variables.)
(If the order of the fields is different in the file, rearrange the entries in the -Header
parameter to match the actuality)
In general, it's a bad idea to try to replicate a batch file's process identically in PowerShell; there are enough differences that you should think carefully about the intent of the process, and take advantage of the capabilities that PowerShell offers that are not available in batch.
CodePudding user response:
You can assign variables directly from array elements:
$credInFile = Get-Content -path "D:\SetCredentials.txt"
$credInFileSplit = $credInFile.Split("|")
$username=$credInFileSplit[0]
$password=$credInFileSplit[1]
$servername=$credInFileSplit[2]
$key=$credInFileSplit[3]