I am trying to run a PowerShell script via a Windows 2012 server scheduled task. Script contents are below. The task connects to a list of servers, creates new-psdrive (with separate credentials), and copies files from all servers to the new psdrive (a network share). The scheduled task will run successfully only the first time. After manually starting the task again, the error below is received. I think I may have a double-hop issue (CredSSP) or scope issue. Is this a double-hop issue or should I use $global or $using scope with the new-psdrive credentials? What am I overlooking?
Window Task Scheduler details:
General Tab > Run only when user is logged on is selected
Actions Tab: PowerShell –NoExit C:\Users\myprofile\testfile.ps1
Error Received after (1) successful run:
A specified logon session does not exist. It may already have been terminated
-
CategoryInfo : InvalidOperation: (MyNewPSDrive:PSDriveInfo) [New-PSDrive], Win32Exception
-
FullyQualifiedErrorId : CouldNotMapNetworkDrive,Microsoft.PowerShell.Commands.NewPSDriveCommand
-
PSComputerName : RemoteServerName
$servers = @' server2012-3 server2012-4 server2012-5 '@ -split "`n" $scripblock1 = { # Credentials used to access network share. Password will be removed once this issue is resolved. $pass = ConvertTo-SecureString -String 'testpassword' -AsPlainText -Force $username = 'testusername' #$cred = New-Object System.Management.Automation.PSCredential('testusername','testpassword') $cred = New-Object -TypeName PSCredential($username,$pass) New-PSDrive -Root \\ipaddress\placeholder -Name Place -PSProvider FileSystem -Credential $cred New-Item -ItemType Directory -Path Place:\$env:COMPUTERNAME\Logs copy-item -Path $env:USERPROFILE\DateFile.txt -Destination Place:\$env:COMPUTERNAME\Logs } $session = New-PSSession -ComputerName $servers Invoke-Command -Session $session -ScriptBlock $scripblock1 Get-PSSession | Remove-PSSession