The following PowerShell code was my first attempt at automating the copying of files to a large number of PCs (simplified to a single file for the purpose of this example). The destination folder already existed and contained a number of other files, hence the need to check the source file did not exist before copying. The results are additionally outputted to a log file as 100+ PCs were queried and any that failed needed to be followed-up.
Improved version.
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
#Text file of PCs to query
$targetPCs = Get-Content "C:\User Files\LabVIEW\LabVIEWPCs.txt"
#Location on remote PC to copy file to
$targetdirectory = "C$\PTL\YR1 FOUNDATION LAB\"
#Location on my PC where file exists
$sourcedirectory = "C:\User Files\LabVIEW\Files\*"
$file1 = "2017-18_Y1_Lab1_FoundationElectronics_2.exe"
#Variable to later output a log of results
$output =
#Take each PC in the text file in turn
ForEach ($computer in $targetPCs) {
#Check file does not already exist on remote PC
If (-Not(Test-Path "\\$computer\$targetdirectory\$file1")) {
#Copy file, display success in PowerShell console, write success to .csv log
Copy-Item -Path $sourcedirectory -Destination \\$computer\$targetdirectory\$file1
Write-Host "$computer, FoundationElectronics_2.exe copy success" -ForegroundColor Green #Display output in console
Write-Output "$computer, FoundationElectronics_2.exe copy success" #Display output in log file
}
#If file already exists then just log the results
Else {
Write-Host "$computer, FoundationElectronics_2.exe already exists" -ForegroundColor Yellow
Write-Output "$computer, FoundationElectronics_2.exe already exists"
}
}
#Log above 'Write-Output' to a .csv to keep track of results
$output | Out-File 'C:\User Files\LabVIEW\File Copy.csv' -Append
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Copy file into folder if not exist.ps1
No comments:
Post a Comment