Goal
I'm trying to create a log file in powershell. I'll read it in at the beginning of the script, run the script, then write out the log to the same place. It's a script that will be run everyday so I'll read it in, update it, and then write it back out each day when the script is run
What I've done
Define array
I started by defining the array like this:
# Define today's date
$today = Get-Date -Format "MM/dd/yyyy"
# Define array
$Robjects_log = @(
[pscustomobject]@{
log_date = $today;
log_covid_cases = "Not Checked";
log_allspecimens = "Not Checked";
log_snapshot = "Not Checked";
log_r_script = "No";
log_final_status = "Not Checked";
log_continue_checking = "Yes"}
)
I can do indexing and changing values like I'd like
# Index and select
$Robjects_log[$_.log_date -eq $today].log_date
# change a value
$Robjects_log[$_.log_date -eq $today].log_date = "tuesday"
# return entire row where log_date is equal to tuesday
$Robjects_log[$_.log_date -eq "tuesday"]
Write out array
I've tried doing this in two ways:
- Formatted as table
# Youll have to change this file path!
$Robjects_log | Format-Table -AutoSize | Out-File -FilePath "C:/R_projects/russ_stuff/Robjects_log.txt"
- Not formatted as table
# Youll have to change this file path!
$Robjects_log | Out-File -FilePath "C:/R_projects/russ_stuff/Robjects_log.txt"
Read array back in
I've tried reading the array back in a variety of different ways including the following:
$old_log = Get-Content -Path "C:/R_projects/russ_stuff/Robjects_log.txt"
Basically I tried a lot of what was suggested here with both variations of the write step: How to save each line of text file as array through powershell
Where I'm stuck
The log reads in fine and when I type $old_log
I see the log, but when I try to index like I did above I get a bunch of errors or blank elements. So the question is how do I write out and read back in an array so that I can keep indexing and changing values in the same way as before I did the write out step?
P.S. I'm super new at power shell. I apologize if this is easy or I missed a place where this has already been answered. Thank you!!
What I've tried
I've tried various combinations of writing out and reading in arrays.
What I haven't tried
redefining the array piece by piece in a loop or resorting to regular expressions. I'm hoping there's an easier way
What I want
I want to be able to read a text file in as an array that I can index and manipulate with standard array functions.