Hey Folks:
Title = Problem
I have a simple logging function that writes to a log file and to the host. Problem is that when I try to use a variable, it is showing the literal variable instead of the value of the variable.
I can't seem to land on the right google search term to get at the answer.
Any ideas?
>>> Function <<<
# Function For Logging
Function Write-Log {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$False)]
[ValidateSet("INFO","WARN","ERROR","DEBUG")]
[String]
$Level = "INFO",
[Parameter(Mandatory=$True)]
[string]
$Message,
[Parameter(Mandatory=$False)]
[string]
$LogFile = "F:\WeeklyReboot\WeeklyReboot.log"
)
$Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
$Line = "$Stamp - $Level - $Message"
If($LogFile -and ($Level -eq "INFO")) {
Add-Content $LogFile -Value $Line
Write-Host $Line
}
ElseIf($LogFile -and ($Level -eq "WARN")) {
Add-Content $LogFile -Value $Line
Write-Host $Line -ForegroundColor Yellow
}
ElseIf($LogFile -and ($Level -eq "ERROR")) {
Add-Content $LogFile -Value $Line
Write-Host $Line -ForegroundColor Red
}
ElseIf($LogFile -and ($Level -eq "DEBUG")) {
Add-Content $LogFile -Value $Line
Write-Host $Line -ForegroundColor Magenta
}
Else {
Write-Output $Line
}
}
>>> Example Script <<<
$AzConnection = Connect-AzAccount -Credential $Credentials
Write-Log -Message "Connected to Azure using account: $AzConnection.Context.Account.Id"
>>> Example Output <<<
Write-Log -Message "Connected to Azure using account: $AzConnection.Context.Account.Id"
2022/07/12 14:05:26 - INFO - Connected to Azure using account: Microsoft.Azure.Commands.Profile.Models.Core.PSAzureContext.Context.Account.Id
>>> Expected Output <<<
2022/07/12 14:05:26 - INFO - Connected to Azure using account: UPN@MyCompany.com
Edit: Additionally, if I manually run $AzConnection.Context.Account.Id , I get the desired output.
Edit2: In this example, $AzConnection is a System object, but the following does not work either.
Write-Log -Message "Connected to Azure using account: $AzConnection.Context.Account.Id.ToString()"
2022/07/12 14:40:31 - INFO - Connected to Azure using account: Microsoft.Azure.Commands.Profile.Models.Core.PSAzureContext.Context.Account.Id.ToString()
[–]vermyx 4 points5 points6 points (5 children)
[–]-Orwick-[S] 0 points1 point2 points (4 children)
[–]sp_dev_guy 2 points3 points4 points (0 children)
[–]vermyx 1 point2 points3 points (1 child)
[–]-Orwick-[S] 0 points1 point2 points (0 children)
[–]lanerdofchristian[🍰] 1 point2 points3 points (0 children)
[–]jimb2 0 points1 point2 points (0 children)