PowerShell Scripting – Copy Files to Network Drive with Task Schedule

drivenetworkingpowershellscripting

I have powershell script that is copying files from local drive to network mapped drive. Everything works fine when i run this script via powershell but when i run this script with task scheduler it doesnt work.
I have created also simple script with one line to create file

New-Item -Path "Z:\DBBackups\" -Name testfile -Value "test123" -ItemType file -force

This script works via powershell with path to mapped network drive, and works with task scheduler when path is in local drive but doesnt work when path is network drive.

Task scheduler settings:
Action: Start a program

Program/script: powershell.exe

Add arguments: -ExecutionPolicy Bypass -File "E:\t.ps1"

Account to run task i set to Administrator which have rights to network disk also is set to run script when user is not logged on, dont store password and with highest privilleges

What can i do to use task scheduler with script that is using network drive?

Best Answer

You didn't specify if you are in a Domain or a Workgroup. The main issue you have is that you're running the script as Administrator which is not the same "Administrator" account on the network share.

If this is a Workgroup computer then this will not work. The only work around you can use is to have a script map your drive letter using plain text credentials. Ridiculously insecure, but if you lock down the remote account and only give it write permissions to the folder you can limit your exposure.

If this is an active directory domain then you're in luck. You need to change the scheduled task and run it under a Service Account. In this case the Administrator account does not have access to network resources and since it is not the same account on the remote server it cannot authenticate to the remote share. The Service Account should be a domain user/group managed service account. You will need to grant access to this account on the remote share and at the NTFS level.

Like Peter Hahndorf already suggested, you should change the -Path argument to use the network path of your remote share and not a drive letter. The drive letter is unique to each user if it is a mapped drive and is also unavailable to the Administrator account if you mapped it under your login.

ripvlan made a very good suggestion about signing your script too. Not only does it keep you from having to change your execution policy but it also prevents someone else from putting extra/malicious code into your script and having it executed without your knowledge. Once a script is signed any changes to that script will require it to be resigned before you can use it again.