Author Posts

April 10, 2017 at 11:27 am

I created a simple PowerShell script that maps a shared folder, copies a file from the shared folder and closes the share.
The script should be executed on a Windows Server 2008 R2 server.
It looks like:

#
net use u: \\192.168.1.10\myshare /user:myusername mypassword  /persistent:no  >> Null
Copy-Item -Path "u:\myfile1.txt" -Destination "c:\myfolder" -force
net use u: /delete >> Null
#

If I execute it interactively it works fine.
If I schedule it as a scheduled task it does nothing.
So my questions are:
– What is the right way to map a shared folder from inside a scheduled task? I saw several pages in the web reporting problems, but I was unable to locate a Solution
– Given a PowerShell script scheduled as a scheduled task, how can I see the possible error messages while executing it?
Regards
marius

April 10, 2017 at 1:57 pm

I copy files to an external share using this:

New-PSDrive -name J -Root \\myserver\E$\dirname -Credential (Import-Clixml "$credfile") -PSProvider filesystem
Copy-Item $xmlpath -Destination J:\
Remove-PSDrive J

April 10, 2017 at 2:13 pm

# To schedule a PowerShell script:

$ScriptPath = 'C:\scripts\ping-report-v3.ps1'
$TaskName   = 'PingReport'
$TaskRun    = "powershell.exe -NoLogo -NonInteractive -WindowStyle Hidden -Command ""$ScriptPath""" 

# Example: Hourly starting at 9 AM
SCHTASKS.EXE /Create /S $Env:COMPUTERNAME /RU SYSTEM /TN $TaskName /TR $TaskRun /SC HOURLY /ST 09:00 /RL HIGHEST /F 
break

# Example: Weekly on Sundays at 2 AM
SCHTASKS.EXE /Create /S $Env:COMPUTERNAME /RU SYSTEM /SC WEEKLY /D SUN /TN $TaskName /TR $TaskRun /ST 02:00 /RL HIGHEST /F 
break

# Example: Daily at 7 AM
SCHTASKS.EXE /Create /S $Env:COMPUTERNAME /RU SYSTEM /SC DAILY /TN $TaskName /TR $TaskRun /ST 07:00 /RL HIGHEST /F 
break

# Run now:
SCHTASKS /Run /TN "\$TaskName"
break