I have a folder of log files on a shared network drive. I wrote a basic Powershell script to tail individual files. They are named like this: 20220818-123.log The script I made works by typing in the complete name of the file I want to view. I added this line to set a date variable in the format of the file name:
$date= get-date -format yyyyMMdd-
But I can't figure out how to add it to the $filename variable, so that all I have to do is type in the 123 part of the name.
$filename= read-host -prompt "Enter filename"
get-content $filename -wait
Is it even possible to do what I want? Like
$filename= $date (read-host -prompt "enter number").log
Which I know doesn't work.
CodePudding user response:
You could construct the filename in a number of ways, but I like the -f (Format operator) because it separates variable content from statci content:
$filename= read-host -prompt "Enter filename"
Get-Content ('{0:yyyymmdd}-{1}.log' -f (Get-Date) , $filename) -wait
Note that, as written, you only want to enter the 123 portion of the name, omitting .log, as that is taken care of by the filename construction as well.
CodePudding user response:
In another way or for better understanding.. you can construct your filename like this
$Today = Get-Date -Format yyyyMMdd
$spChar = "-"
$userInput = Read-host -Prompt "Enter Number"
$fileName = $Today $spChar $userInput
Get-Content "C:\temp\$filename.log"
