我正在编写一个脚本,打开一个文件资源管理器窗口,供任何用户选择一个文件,然后将其复制到预先选择的计算机的临时文件夹中。我希望能够在计算机上的任何位置选择一个文件,并分解该文件的路径和文件本身以进行 robocopy,然后将其复制到 \WIN10\C$\TEMP 但我似乎无法让它正确分解.
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: $_"
}
}
}
上面让我在 D:\SOFTWARE 中选择一个文件,但是当我读取 .log 文件时,它显示源为 C:\USERS\ADMINISTRATORS\DESKTOP\
我知道这是因为InitialDirectory,但是我已将其更改为Split-Path
$file = Split-Path $(FileBrowser.Filename) -Leaf
$source = Split-Path $(FileBrowser.File) -Parent
现在,当我运行它时,.log 显示 \WIN10\C$\TEMP 的目的地作为源,并且该文件现在在日志中显示为 *.*。
我错过了什么?
确实如此。
.InitialDirectory
是错误使用的属性,因为它不反映用户最终选择的文件的目录路径。
.FileName
包含所选文件的完整路径,将其拆分为目录路径和文件名可以通过以下几种方式实现:
$dirPath, $fileName = $fileBrowser.FileName -split '\\', -2
Windows PowerShell 解决方案,使用 Split-Path
$dirPath = Split-Path $fileBrowser.FileName # -Parent implied
$fileName = Split-Path -Leaf $fileBrowser.FileName