2

I have a write-host line that I want to execute a command in the middle of, so the output will be inserted in the middle of the write-host string.

Basically I have a txt file that holds configuration data for a suite of scripts, one of the configurations is the format for dates and time. For example, there is a configuration for the year format which is 'YYYY' and it is written to $Year.

So what I would like to do is something like this:

Write-Host "The year is " Get-Date -Format $Year.ToLower()

What I expect to see on my screen when this is ran, is

The year is 2019

Now I know I can declare another variable with this logic and just have...

Write-Host "The year is $NewVariable"

...but I was hoping not to create another variable. This is a dumb-ed down example of my scrip, so I would be creating a lot of variables if I go this rout. Please note I am using .ToLower() to compensate for the user's input into the configuration text file.

Ken
  • 125
  • 1
  • 12
  • Google command mode vs expression mode. https://stackoverflow.com/questions/48776180/powershells-parsing-modes-argument-command-mode-vs-expression-mode – js2010 Oct 16 '19 at 15:32

1 Answers1

6

In order to print the year of the Get-Date run this:

Write-Host "The year is $(Get-Date -Format yyyy)"

This way you will always get the year that is generated by Get-Date

JimShapedCoding
  • 849
  • 1
  • 6
  • 17
  • Thank you very much. I had the syntax wrong....I wasn't encapsulating the command properly. I'm using what you have above with substituting the yyyy for my variable. – Ken Oct 16 '19 at 18:56
  • This works too. `Write-Host The year is (Get-Date -Format yyyy)` – js2010 Oct 17 '19 at 17:01