I have been switching many of scripts from using command-line operations over to PowerShell in recent weeks and one of the operations I had been doing earlier was using the "net use" command to map drives to remote shares on servers before copying them over using Robocopy.
However, I did not really need to use the "net use" command since it was just part of a background process and the drive letter could be deleted immediately after the copy operation was completed so I began searching for PowerShell alternatives.
I found just such an alternative using the "New-PSDrive" command:
https://technet.microsoft.com/en-us/library/hh849829.aspx
https://technet.microsoft.com/en-us/library/ee176915.aspx
Once I understood exactly how to use this PowerShell cmdlet, I was able to compose the following PowerShell script:
However, I did not really need to use the "net use" command since it was just part of a background process and the drive letter could be deleted immediately after the copy operation was completed so I began searching for PowerShell alternatives.
I found just such an alternative using the "New-PSDrive" command:
https://technet.microsoft.com/en-us/library/hh849829.aspx
https://technet.microsoft.com/en-us/library/ee176915.aspx
Once I understood exactly how to use this PowerShell cmdlet, I was able to compose the following PowerShell script:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[CmdletBinding()] | |
Param | |
( | |
[Parameter(Mandatory=$true,Position=1)] | |
$Source = "C:\Downloads", | |
[Parameter(Mandatory=$true)] | |
$Dest = "\\myserver\c$\myfolder", | |
[Parameter(Mandatory=$true)] | |
$DriveLetter = "J", | |
[Parameter(Mandatory=$true)] | |
$Username = "administrator", | |
[Parameter(Mandatory=$true)] | |
$Password = "Complex_Passw0rd" | |
) | |
Clear-Host | |
$SecurePassword = ConvertTo-SecureString $Password -AsPlainText -Force | |
$mycreds = New-Object System.Management.Automation.PSCredential($Username, $SecurePassword) | |
#Format the drive letter so that it is a proper destination path | |
$DriveLetterPath = "{0}:" -f $DriveLetter | |
Write-Host "This is the drive letter path $DriveLetterPath" | |
if (! (Test-Path $DriveLetterPath)) | |
{ | |
Write-Host "Mapping the Drive Letter in PowerShell" | |
New-PSDrive -Name $DriveLetter -PSProvider FileSystem -Root $Dest -Credential $mycreds -Persist | Out-Null | |
Write-Host "Copying the files over to the remotely mapped drive letter" | |
Copy-Item -Path "$Source\*" -Destination $DriveLetterPath -Recurse | |
#Remove the mapped PowerShell Drive | |
Remove-PSDrive $DriveLetter -PSProvider FileSystem -Force | |
}#if | |
No comments:
Post a Comment