Windows – Reconnecting to a Mapped Drive after Server Restart from within PowerShell Script

powershellwindows

I have a PowerShell v1 script that connects to a remote server via a mapped drive and moves files back and forth the remote server is identified by drive number "M" and also by UNC path REMOTESERVER\DATA:

(M:) \\REMOTESERVER\DATA

When the remote server reboots, I think that I am screwed because now the mapped drive will be inaccessible by the script.

How is this situation handled programmatically from within a PowerShell script?

Is there a way to reconnect to the mapped drive by writing some PowerShell code?

The issue is not when the mapped drive actually disappears, it is that after reboot, authentication is needed and Windows apparently will not remember that.

Just curious how this is accomplished?

Best Answer

There are a couple of ways. First, you could map the drive on the server using the net use command with the /persistent switch for the drive to remap at logon. Next, specifically in powershell you could map the drive using the new-psdrive cmdlet and just refer to the drive that way, you wouldn't even need a drive letter.

If you go with the second option I would either make sure whatever context the script is running under has permissions to the share, or if that's not possible then there is a way where you can store the credentials needed encrypted in a text file so that they can be imported by the script when needed, but as a word of caution the encryption is reversible, in case someone who is crafty and willing enough gets ahold of your script.

http://technet.microsoft.com/en-us/library/hh849829.aspx

http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/net_use.mspx?mfr=true