Krish
Krish

Reputation: 629

reading and updating file using powershell

I created a log file using powershell in .txt or .config. Its look like :

# Hello
## This is readme.txt file
## This is commented line
# This is powershell command output
#
# File generated for read, re-load and edit the values
## -- many more comment is there
# Users can change values..
## There is no relation between $RegPath and $RegValue, this are only variables.

# this are registry path,
$RegPath = (
"\\hklm\software\microsoft\123",
"\\hklm\software\Adobe\123",
"\\hklm\software\Fax\123",
"\\hklm\software\IE\123");

# this are registry value.
$RegValue = (
"0",
"123",
"abc",
"456asdccxv",
"update",
"serv");

#this are some services with 0/1
# Win 7 OS exist
$IsWin7OS = 1

# Service pack installed
$IsSPInstalled = 0

# Check office
$MSOffice = 1

# This setting name is
$SettingName = "ReadMe.txt"

This is sample ReadMe.txt. I want to read this file in powershell and want to get values of $RegPath, $RegValue, $IsWin7OS, $IsSPInstalled, $MSOffice and $SettingName in powershell platform. Then I will update this value and save again in same file.

Upvotes: 0

Views: 233

Answers (1)

Keith Hill
Keith Hill

Reputation: 201812

DISCLAIMER: This is a security WORST practice. It really is quite dangerous. That said, an easy way to read in this data is:

PS> Invoke-Expression (Get-Content C:\readfile.txt -Raw)
PS> $RegPath[0]
\\hklm\software\microsoft\123

The reason it is bad is that if someone adds this remove-item c:\ -recurse -force to the file the command above will execute that and it will be a bad day for you. What I recommend is that you put the data in a .psd1 file if you can in the form of a hashtable. PowerShell will not execute arbitrary code in that case. Or you could store the data as CLIXML or JSON and then read it back in with Import-Csv or ConvertFrom-Json.

Upvotes: 1

Related Questions