Retrieve variable from text file

Microsoft Windows
Post Reply
User avatar
Posts: 336
Joined: 2021-Jul-12, 1:37 pm

Retrieve variable from text file

Post by MigrationUser »

01 Jan 2014 10:50

I have a text file which contains some data which I need to put into a variable in powershell

i just want to create two variables, which are pulled from the text file, _admin_0_name and _admin_0_pass


Code: Select all

Here is my attempt


Code: Select all

$invocation = (Get-Variable MyInvocation).Value
$directorypath = Split-Path $invocation.MyCommand.Path
$settingspath = $directorypath + '\*.profile'

# retrieve variables from a file
$profile = get-content $settingspath
$username = $profile | select-string '_admin_0_name' | %{$_.line.split('=')}
$password = $profile | select-string '_admin_0_pass' | %{$_.line.split('=')}

echo $username
echo $password

if($password) {            
    Write-Host "string is not empty"            
} else {            
    Write-Host "String is EMPTY or NULL"            
The problem is that $password is not an empty string because i think it is an array.

If it possible to simply get these values without creating an array, and check for blank value of password?


cmd, vbs, ps, bash
autoit, python, swift


#04 Jan 2014 03:48

I see no-one has answered this yet...

Any other forum I could ask at you suggest?

cmd, vbs, ps, bash
autoit, python, swift


#04 Jan 2014 04:28


#04 Jan 2014 17:48
Simon Sheppard

How about this

Code: Select all

$file = get-content DATAFILE.txt
$file | foreach {
  $items = $_.split("=")
  if ($items[0] -eq "_admin_0_name"){$username = $items[1]}
  if ($items[0] -eq "_admin_0_pass"){$password = $items[1]}

Echo $username  $password

If ($password -eq "") {Echo 'password missing!'}

#14 Jan 2014 05:04

Hello Simon.

Thanks for your reply. That worked for me. I'm having trouble with the basics of powershell scripting, but this worked for a Windows 8.1 project I am working on, as autoit and psexec was not able to runas another user.
Post Reply