This is a question of understanding.
I construct a Directory Structure using a string Variable $path. I append the name of the Directory I want to create, this works as expected. When the path is completed I need the complete Directory as System.IO.DirectoryInfo but assigning the Path in this way $Path = Get-Item $Path results in a string type.
$path = "c:\dir1"
If(-Not (Test-Path $path))New-Item -ItemType Directory -Path $path
$path = $path + "\dir2"
If(-Not (Test-Path $path))New-Item -ItemType Directory -Path $path
# Assigned to same variable
$path = Get-Item $path
echo $path.GetType() # = string
# assigned to different variable
$p_a_t_h = Get-Item $path
echo $p_a_t_h.GetType() # = System.IO.DirectoryInfo
# solution but not understood the behavior
[System.IO.DirectoryInfo]$path = Get-Item $path
echo $path.GetType() # = System.IO.DirectoryInfo
It took hours to find out this behavior and I couldn't find any documentation why this is - maybe because I don't know what to search for.
It is clear, that for appending something to a variable, the type of the variable is relevant, but a $path = ... is a "new" assignement and should have the type of the assigned value - at least in my eyes. In the languages I used so far a variable becomes the type of its value and is not converted to a type the variable had earlier or I define the type of a variable and get an error if assigned with wrong type.
Where is the error in my logic?
[System.IO.DirectoryInfo]$pathafter i have created the Directorystructure using[string]$path-Pathparameter accepts a[System.IO.DirecetoryInfo]object - no need to use[System.IO.DirecetoryInfo]$path.FullName