#1 01 Jan 2014 10:50

NDog
Member
From: New Zealand
Registered: 31 May 2006
Posts: 106
Website

Retrieve variable from text file

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
$username
$password

file.profile

_admin_0_name=Administrator
_admin_0_pass=

Here is my attempt

userpass.ps1

$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?

Thanks


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

Offline

#2 04 Jan 2014 03:48

NDog
Member
From: New Zealand
Registered: 31 May 2006
Posts: 106
Website

Re: Retrieve variable from text file

I see noone has aanswered this yet...

Any other forum I could ask at you suggest?


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

Offline

#3 04 Jan 2014 04:28

foxidrive
Member
Registered: 04 Apr 2013
Posts: 339

Re: Retrieve variable from text file

Offline

#4 04 Jan 2014 17:48

Simon Sheppard
Super Administrator
Registered: 27 Aug 2005
Posts: 867
Website

Re: Retrieve variable from text file

How about this

$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!'}

Offline

#5 14 Jan 2014 05:04

NDog
Member
From: New Zealand
Registered: 31 May 2006
Posts: 106
Website

Re: Retrieve variable from text file

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.


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

Offline

Board footer

Powered by FluxBB