2

The lines below work fine from a Powershell prompt, but fail from a scheduled task.

$pass = gc C:\secrets\shhh.txt | convertTo-secureString
$Cred = new-object -typeName System.management.automation.psCredential -argumentlist "domain\domainUser",$pass

$path = "\\server\share\folder"
$j = start-job {gci -path $args[0]} -cred $Cred -argumentList $path | wait-job | receive-job

$body = $j | out-string
$error | out-file C:\temp\err.txt
send-mailMessage -to me@domain.tld -from server@domain.tld -subject halp -smtpserver mailserver.domain.tld -body $body

In c:\temp\err.txt the Windows 2008R2 Scheduled Task leaves a breadcrumb:

[localhost] The background process exited abnormally.
    + CategoryInfo          : OpenError: (localhost:String) [], PSRemotingTransportException
    + FullyQualifiedErrorId : 2101,PSSessionStateBroken

...which brings us to this Microsoft bug report. The report mentions a workaround with localhost loopback remoting, which sounds kinda dirty. Should I go there?

Is there a better solution? Maybe with one of the *session cmdlets or invoke-command? The scheduled task's Start in value is set, but maybe the background process uses some variable in some bad way, like so?

No luck yet calling powershell.exe with –version 2 or with -command "& {bigKlugeyScriptblock}" syntax.

edit: I'm trying to avoid creating a new domain account to run the task. The task can't run as domainUser from $cred, because that account should not have permissions on localhost.

noam
  • 1,914
  • 2
  • 20
  • 26

2 Answers2

2

As some possible work arounds how about:

  1. Put alternate credentials on the scheduled task itself
  2. Using the runas command to start powershell.exe as a different user
  3. Using net use /user parameter to authenticate access to the network path

    [/USER:[dotted domain name\]username]
    [/USER:[username@dotted domain name] 
    
Andy Arismendi
  • 50,577
  • 16
  • 107
  • 124
  • Thanks. 1) see edit 2) Promising. Reading up on runas /savecred and cmdkey.exe and will report back. – noam Mar 14 '13 at 23:39
  • Work-around #1 is good enough here after all. I'm okay granting 'Log on as a batch job' to $cred in Local Security Policy, and that privilege seems to be enough to run the Scheduled Task. – noam Mar 15 '13 at 19:36
  • ...or [should I be okay with that](http://serverfault.com/questions/494605/windows-security-can-user-read-local-files-with-only-log-on-as-a-batch-job)? – noam Apr 04 '13 at 21:46
0

This code allows you to run a scriptblock locally on the same server, but you must be running powershell as an administrator or you will get access denied error.

$s = New-PSSession -ComputerName localhost -Credential $credential
try
{
    Invoke-Command -Session $s -ScriptBlock {"hello from $env:USERNAME"}
} finally {
    $s | Remove-PSSession
}
Justin
  • 1,303
  • 15
  • 30