I am certain there are better, cleaner, more efficient ways of writing this code, I will take your advise/suggestions and attempt to improve my code, but at my current skill level - this is what I was able to piece together which gave me the end result I was looking for.
$FileServer = hostname
$DestPath = "c:\PSTs\$FileServer"
#Checks if the Destination Dir/Path exists, if not it creates the folder and names it whatever the hostname is
If ((Test-Path -path $DestPath -PathType Container) -eq $false) {New-Item $DestPath -ItemType Directory}
#Searches for .psts files on host, exports results to .csv file.
Get-psdrive -PSProvider "FileSystem" `
| ForEach-Object {(get-childitem $_.Root -recurse -file -Filter *.PST -erroraction silentlyContinue `
| Select-Object -Property Directory,Name)} | Export-Csv -path "$DestPath\$FileServer.csv" -NoTypeInformation -Force
#Sets variable for .CSV file from previous command
$PstPath = Get-Content -Path "$DestPath\$FileServer.csv"
#Modifying .CSV for preceding commands to work.
$PSTsCSV = "$DestPath\$FileServer.csv"
($PstPath).Replace('"Directory",','"Path"').replace('"Name"','').replace('","','\') | Out-File -FilePath $PSTsCSV -force
#Reads each line of .CSV file, copies .pst file from source to destination, if file name exsists...
#in destination, it will re-name file appending a consecutive number
$CSV = Import-Csv $DestPath\$FileServer.csv
Get-ChildItem -Path $CSV.Path | ForEach-Object {
$num=1
$newName = Join-Path -Path $DestPath -ChildPath $_.Name
while(Test-Path -Path $newName)
{
$newName = Join-Path $DestPath ($_.BaseName + "_$num" + $_.Extension)
$num+=1
}
$_ | Copy-Item -Destination $newName
}
I found an issue in my script, this is the line in question.
($PstPath).Replace('"Directory",','"Path"').replace('"Name"','').replace('","','\') | Out-File -FilePath $PSTsCSV -force
If searching for .psts on a server that yields no .pst files, the output to the .csv file will have no results. An error will surface stating You cannot call a method on a null-valued expression.
You cannot call a method on a null-valued expression.
At D:\Scripts\PowerShell\tempCodeRunnerFile.ps1:6 char:1
+ ($PstPath).Replace('"Directory",','"Path"').replace('"Name"','').repl ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
to remedy [as best as I could figure out], in the event no .psts are found I re-wrote the code by adding -ErrorAction Stop
so the script stops at this point, like this
Get-Content $PSTsCSV.Replace('"Directory",','"Path"').replace('"Name"','').replace('","','\') -ErrorAction Stop | Out-File -FilePath $PSTsCSV -force