2

Everyday a file is being saved with the current date in format testDDMMYYY.csv for an example test24112017.csv.

I need to open the current day's file with Powershell, however, I haven't found a way for it to work with variables.

#Date (24112017)
[String]$a=(Get-Date).ToShortDateString() | Foreach-Object {$_ -replace "\.", ""} 

#Open the file called test24112017
[int] $S1=Get-Content "D:\test$($a).csv" -Tail 1 |  Foreach-Object {$_ -replace "`"", ""} | ForEach-Object{$_.Split(",")[1]} | write-host

How can I get that variable working inside that path?

8
  • 2
    Can you not just do "get-content "D:\test$a.csv" Commented Nov 24, 2017 at 8:23
  • I can confirm what @Joseph says. It works with just "D:\test$a.csv". Commented Nov 24, 2017 at 8:31
  • I thought so too, but I have 2 files for testing "test.csv" and "test24112017.csv" . Using "D:\test$a.csv displays the contents of "test.csv" Commented Nov 24, 2017 at 8:32
  • 1
    You can simply use : Get-Content "D:\test$(Get-Date -Format 'ddMMyyyy').csv" -Tail 1 Commented Nov 24, 2017 at 8:39
  • Thank You! This works perfectly! Commented Nov 24, 2017 at 8:42

2 Answers 2

4

Do not use (Get-Date).ToShortDateString() | Foreach-Object {$_ -replace "\.", ""}, just use Get-Date -Format 'ddMMyyyy' to format the date the way you want :

Get-Content "D:\test$(Get-Date -Format 'ddMMyyyy').csv" -Tail 1

Formatting Dates and Times

Sign up to request clarification or add additional context in comments.

Comments

0

Hmm aren't you over-complicating things a bit?

First of all, (Get-Date).ToShortDateString() doesn't give me 24112017 but 24-11-2017. So i'm guessing we have different regional settings, what part of the world are you from?

Have you printed out $a? What does it give you?

I would go for a different approach. Since your filename is literally always newer than the previous one (because it holds a date). I would just sort on the Name and select the first one (aka the newest file).

$newestfile = Get-ChildItem c:\temp |  Sort-Object Name -Desc | select * -First 1

Now go do whatever you want with your latest file.

get-content $newestfile.fullname

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.