PowerShell script for doing the following tasks as below:
– Copy file from it own to another place (can be network share).
– It required having credential for validate target location verifying.
# Define source and destination paths $sourcePath = "C:\ExamplePath\Path" $destinationPath = "\\UNCPath\FolderPath" $username = "user_name_target_path" # Replace with actual username $password = "password_target_path" | ConvertTo-SecureString -AsPlainText -Force # Replace with actual password try { # Create a PSCredential object with the provided username and password $credential = New-Object System.Management.Automation.PSCredential($username, $password) # Ensure the network path is accessible before proceeding if (Test-Path $destinationPath) { # Fetch the latest file based on 'Date modified' $latestFile = Get-ChildItem -Path $sourcePath -File | Sort-Object LastWriteTime -Descending | Select-Object -First 1 if ($latestFile -ne $null) { # Construct the full destination path $destinationFilePath = Join-Path -Path $destinationPath -ChildPath $latestFile.Name # Map the network drive with the provided credential New-PSDrive -Name "NetworkShare" -PSProvider FileSystem -Root $destinationPath -Credential $credential # Copy the latest file to the destination Copy-Item -Path $latestFile.FullName -Destination "NetworkShare:\" -ErrorAction Stop # Clean up by removing the mapped network drive Remove-PSDrive -Name "NetworkShare" } else { Write-Host "No files found in the source directory." } } else { Write-Host "Destination path is not accessible: $destinationPath" } } catch { # Error handling Write-Host "An error occurred: $_" }
We can settings it to run daily with Task Scheduler in Windows environment.
Program/script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Add arguments (optional): -ExecutionPolicy Bypass -File “C:\LocalFolderPath\PS-Script-File.ps1”