Search code examples
powershellnetwork-programmingscheduled-taskscopy-item

Powershell script to copy file to network runs manually, but not from Task Scheduler


I am running a script to copy a file from a local to network location. The script works if I call it myself via powershell, but not from Task Scheduler. I have looked at this and many other articles, but I cannot get it to work. Right now I can look at the task scheduler, "Last run result" and it says the task is currently running for a couple minutes before I stop it. When I end the task I don't even get an exception (code is in a try/catch)

I have the ServerLocation and ServerFullPath broken up because I was trying a few different examples.

The code is as follows (with the domain/username/password substituted):

Set-Variable ServerCredentials -option Constant -value "<domain>/<username>  <password>"
Set-Variable ServerLocation -option Constant -value "\\<domain>"
Set-Variable ServerFullPath -option Constant -value $ServerLocation"\path\path"

$latest = Get-ChildItem -Path .\ | Sort-Object LastWriteTime -Descending | Select-Object -First 1
net use $ServerFullPath /user:$ServerCredentials

Copy-Item .\$latest $ServerFullPath -Force

I am new to powershell, any thoughts on how to troubleshoot? Need any more information?


Solution

  • The answer to this lies in how "net use" works. Typing "net use" into cmd showed I already had a connection, and it seems already having a connection will make net use want to prompt, which is why it seemed my script was hanging. I tried deleting the connection with "Net use * /delete /y", just above the original net use, and that allowed the script to continue correctly. It then looked like:

    Net use * /delete /y
    net use $ServerFullPath /user:$ServerCredentialUser $ServerCredentialPassword
    

    The key here is the \y on the end, which will silently answer yes to the prompt.

    As an aside this link shows how to use the /delete param. I chose to use a * here, but it seems I could have deleted that specific connection.

    However this sparked something that maybe net use was prompting me in some way about the connection that was already there, so I changed the original line to:

    net use $ServerFullPath /user:$ServerCredentialUser $ServerCredentialPassword /y
    

    With the /y on the end it works just fine, and all is well :)