Monday, September 15, 2014

Working with Network drive via PowerShell(2.0, 3.0 & 4.0)


In Windows PowerShell 3.0 & 4.0, you can use New-PSDrive to access the file system location that can be a remote or on a local computer.
$pass = $password | ConvertTo-SecureString -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PsCredential($user_name,$pass)
New-PSDrive -name CSV-PATH -Root $path -Credential $cred -PSProvider filesystem 
$path = $path + "\" + "file.csv"; 

if(Test-Path $path){
   Write-Host "File found." 
}
Remove-PSDrive -Name CSV-PATH; 

On the other hand,  PowerSehll 2.0. doesnot support New-PSDrive cmdlet. In that case you can use one of the following two ways to access a network drive for reading, creating, updating and deleting a file;
$net.mapnetworkdrive($drive, $path, $true, $username, $password)
$path = $path + "\" + "file.csv"; 
Remove-item $path;
$net.RemoveNetworkDrive($drive)

$uncServer = "\\Servername";
        net use $uncServer $password /USER:$username
$path = $path + "\" + "file.csv";
Remove-item $path; 
net use $uncServer /delete

I hope this post will help someone..Cheers..J

No comments:

Post a Comment