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?
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?Consider not using drive letters. Powershell, even in 2.0, will let you use UNC paths extensively when working with the file system. So you can basically address the locations directly, without PSDrive or drive letter. Then you don't have to map anything, and you don't need to unmap them.
Then just do your file manipulation with relative paths. You can also assign the server name and folder path to variables so that you can use
"$server\$folderpath\"
in place of a drive letter.I found the answer and it's so silly..
This works when ran from a Scheduled Task by SYSTEM.. Just needed to add the &, shows my lack of PS skills.. oh boy