Tuesday, April 15, 2014

How to map a network drive using NEW-PSDRIVE in PowerShell and have the drive persist in Windows

#STORED CREDENTIAL CODE
#This code is by Edwin A Davidson
#This code is a fork of  's code
#located here: http://www.techrepublic.com/blog/data-center/powershell-code-to-store-user-credentials-encrypted-for-re-use/
###$AdminName = Read-Host "Enter your Admin AD username"
$AdminName = "username@domain.local"
$CredsFile = "$env:USERPROFILE\$AdminName-PowershellCreds.txt"
$FileExists = Test-Path $CredsFile
if  ($FileExists -eq $false) {
    Write-Host 'Credential file not found. Enter your password:' -ForegroundColor Red
    Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File $CredsFile
    $password = get-content $CredsFile | convertto-securestring
    $Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminName,$password}
else
    {Write-Host 'Using your stored credential file' -ForegroundColor Green
    $password = get-content $CredsFile | convertto-securestring
    $Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminName,$password}
sleep 2

Write-Host 'Connecting...'

echo $adminname
remove-psdrive -name bob > null
New-PSDrive -Name bob  -PSProvider FileSystem -Root \\192.168.224.31\d$ -Credential $Cred  
#even with -persist, this drive is gone once this PS1 completes, so...
#map the drive using the credentials we just used in NEW-PSDrive
net use b: /del
net use b: \\192.168.224.31\d$ /user:$AdminName
#END OF STORED CREDENTIAL CODE