I am writing a script that opens a file explorer window for any user to select a file to then copy to a preselected machine into a temp folder. I want to be able to select a file anywhere on the machine and break down the path to the file and the file itself for robocopy to then copy it to \WIN10\C$\TEMP however I cannot seem to get it to break down properly.
function Copy-FileToMachines {
Add-Type -AssemblyName System.Windows.Forms
$fileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{
InitialDirectory = [Environment]::GetFolderPath('Desktop')
}
$result = $fileBrowser.ShowDialog()
if ($result -eq 'OK') {
$file = $fileBrowser.SafeFileName
$source = $fileBrowser.InitialDirectory
$deviceList = @('Computer1', 'Computer2', 'Computer3') # Add the names of destination computers here
foreach ($device in $deviceList) {
try {
robocopy "$source" "\\$device\c$\Temp" "$file" /Z /NP /R:3 /W:5 /BYTES /LOG+:`"$env:TEMP\robocopy.log`" | Out-Null
Write-Host "File successfully copied to $device"
}
catch {
Write-Host "An error occurred while copying the file to $device: $_"
}
}
}
The above lets me select a file in D:\SOFTWARE but when I read the .log file it shows the source as C:\USERS\ADMINISTRATORS\DESKTOP\
I understand that to be because of InitialDirectory, however I have changed it to Split-Path
$file = Split-Path $(FileBrowser.Filename) -Leaf
$source = Split-Path $(FileBrowser.File) -Parent
Now when I run it the .log shows the destination of \\WIN10\C$\TEMP as the source now and the file is now showing as *.* in the log.
What am I missing?
Use $fileBrowser.FileName
in Split-Path
. Remove the COLON character after $device
.
function Copy-FileToMachines {
Add-Type -AssemblyName System.Windows.Forms
$fileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{
InitialDirectory = [Environment]::GetFolderPath('Desktop')
}
$result = $fileBrowser.ShowDialog()
if ($result -eq 'OK') {
$file = $fileBrowser.SafeFileName
$source = Split-Path -Path $fileBrowser.FileName -Parent # InitialDirectory
$deviceList = @('Computer1', 'Computer2', 'Computer3') # Add the names of destination computers here
foreach ($device in $deviceList) {
try {
robocopy "$source" "\\$device\c$\Temp" "$file" /Z /NP /R:3 /W:5 /BYTES /LOG+:`"$env:TEMP\robocopy.log`" | Out-Null
Write-Host "File successfully copied to $device"
}
catch {
Write-Host "An error occurred while copying the file to $device $_"
}
}
}
}