I’m writing a backup utility to use when changing out computers, and I am using hash tables for the source and destination locations. I cannot figure out how to set it up to loop through the source locations and reference the destination locations. For example, a $Locations hashtable, which contains the directory name and the corresponding path (e.g. “Data” = “C:\Data”), and a $Destinations hashtable that represents the backup locations that is built from user responses (e.g. “Data” = “D:\Data”).
If I use the following code, it gives me the source locations like I want, but I don’t know how to reference the corresponding value in the destination hashtable.
[pre]ForEach ($Source in $Locations.Values) {
Write-Host $Source
}[/pre]
If I leave off the .Values and put it in the write statement like this:
[pre]ForEach ($Source in $Locations) {
Write-Host $Source.Values
}[/pre]
in an attempt to make it more generic, I get all the items in one big line, (e.g. C:\Data C:\Users<Username>\Downloads C:\Users<Username>\My Documents). Of course there is very likely a better way to do this, so I am open to suggestions. Thanks for your assistance.
Hi Mike,
You can use the key/name reference with the hashtable…
[pre]
PS C:> [hashtable] $Source = @{ Data = ‘C:\Data’; Files = ‘C:\Files’ }
PS C:> $Source
Name Value
Data C:\Data
Files C:\Files
PS C:> $Source.Data
C:\Data
PS C:> $Source[‘Files’]
C:\Files
[/pre]
You probably want a PSObject versus a hashtable.
$map = @()
$map += [pscustomobject]@{
Source = 'C:\Data'
Destination = 'D:\Data'
}
$map += [pscustomobject]@{
Source = 'C:\Scripts'
Destination = 'D:\Scripts'
}
foreach ($path in $map) {
'Moving {0} to {1}' -f $path.Source,$path.Destination
}
The $map could be a CSV or manually mapped like the example above. With that in mind, would a destination be a different path than the source? Traditionally, I would think you would want something more like this:
$paths = 'C:\Data',
'C:\Scripts'
$destination = '\\SomeServer\SomeShare\{0}' -f $env:COMPUTERNAME
foreach ($path in $paths) {
'Moving {0} to {1}' -f $path,$destination
}
This is an accidental duplicate of my original post. The solution to the process ended up being using the keys property of the hashtable, not the values property. That way I was able to use the same reference (e.g. $Location[“PSTs”] and $Destination[“PSTs”), and it worked out great. As usual, I spent a couple of days working on the problem, and then right after I ask for assistance, I stumble upon my answer. Thanks for the suggestions.