Search code examples
powershellwrite-host

Run a command in middle of Write-Host


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.


Solution

  • 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