I’m getting the following error message:
The variable '$dateTime' cannot be retrieved because it has not been set.
The error is generated by the line [DateTime]$dateTime in this code:
[string]$registryEntry = Read-Registry -path $SCRIPT_KEY -name $key
[DateTime]$dateTime
if ($null -ne $registryEntry) {
$dateTime = [DateTime]$registryEntry
}
return $dateTime
But the error message makes no sense: I’m not trying to retrieve the $dateTime variable, I’m just declaring it.
I have to return a DateTime object, or $null if it’s undefined. FYI, the registry entry is the string “19 Jul 2023 05:52”
How do I make this work?
$psVersionTable:
Name Value
---- -----
PSVersion 7.3.6
PSEdition Core
GitCommitId 7.3.6
OS Microsoft Windows 10.0.19045
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0
>Solution :
As the error very clearly states:
because it has not been set.
PowerShell doesn’t really have a concept of "variable declaration" – if you want to strongly type a variable, you’ll have to do it as part of an assignment operation – which in turn will solve your problem:
[string]$registryEntry = Read-Registry -path $SCRIPT_KEY -name $key
[datetime]$dateTime = [datetime]::MinValue
if ($null -ne $registryEntry) {
$dateTime = [DateTime]$registryEntry
}
return $dateTime