Powershell: Creating and disconnecting a network map drive with the SYSTEM user

mappeddrivepowershell

I need to map a network drive with the SYSTEM user, I created a PS1 which is ran by a Scheduled Task, the first part maps the drive succesfully:

$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive("y:", "\\SAN_SERVER\folder1", $false, "domain\service_user", "password")

After the mapping, a bunch of stuff is happening, copying files, etc

At the end of the script the mapped drive need to be disconnected:

& 'D:\Scripts\PsExec64.exe' -s cmd /c "net use y: /delete /yes"

This command works if I run it manually from my user account (I need to start PS as admin), however it does not work from the script in the Scheduled Task, I'm using PsExec64.exe because I found out that since the network drive was mapped with domain\user, it can only be disconnected with domain/service_user unless we use PsExec64.exe, is there a way to disconnect a drive using different credintials?

Best Answer

I'll assume for the moment that you have compatibility/legacy reasons for not using the native New-PSDrive cmdlet from your Powershell script.

So then since you're already using the legacy MapNetworkDrive from WScript.Network, why are you using net use with psexec instead of just using its partner, RemoveNetworkDrive?