I have a problem and I cannot find a solution online.
I have the following code, and I would like to read two inputs and save them in a text file. When the user puts his email and API token, it creates a text file and separates his input in two lines. I don't know what to use with the Read-Host
.
For example:
myname@example.com
123456789abcdefg
What I would like to do is to use his input, but have a default name in front of each line such as:
Email = myname@example.com
APIToken = 123456789abcdefg
Here is my code:
Write-Host 'Enter your email: '
Read-Host | Out-File $CredsFile
Write-Host 'Enter your API Token: '
Read-Host | Out-File $CredsFile -Append
$CredsFile = $CredsFile -join [Environment]::NewLine
$configuration = ConvertFrom-StringData($CredsFile)
$email = $configuration.'Email'
$api_token = $configuration.'APIToken'
You can place the calls to Read-Host
inside string literals using sub-expressions $(...)
:
Write-Host 'Enter your email: '
"Email = $(Read-Host)" | Out-File -Append $CredsFile
Write-Host 'Enter your API Token: '
"APIToken = $(Read-Host)" | Out-File -Append $CredsFile
This will allow you build a custom label around each input.
Also, the calls to Write-Host
are unnecessary since Read-Host
accepts a prompt string argument:
"Email = $(Read-Host 'Enter your email')" | Out-File -Append $CredsFile
"APIToken = $(Read-Host 'Enter your API Token')" | Out-File -Append $CredsFile
Finally, make sure you use the -Append
flag with Out-File
as I did above. Without this, the contents of the file will be overwritten with each write operation.
Since you are already trying to create a hashtable we could use a single Read-Host
and split the results. Depending on the target audience it could be considered less intuitive but I like opening your options. Especially if you don't need to send the data to file.
$input = (Read-Host "Please enter your email and key seperated by a space").Split(" ")
$configuration = @"
Email = {0}
APIToken = {1}
"@ -f $input[0],$input[1] | ConvertFrom-StringData
$email = $configuration.Email
$api_token = $configuration.'APIToken'
This is assuming that you don't really need to send it to file. You still could. Just does not need to be part of this process.
I saw a comment but I guess you deleted it. If you wanted to output this information to file exactly as you have in your example you could do this.
$configuration.GetEnumerator() | ForEach-Object{"$($_.Name) = $($_.Value)"} | Set-Content $CredsFile
Depending on the needs of the files you could make it simpler.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.