Reputation: 1983
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 [email protected] -from [email protected] -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.
Upvotes: 2
Views: 4615
Reputation: 1503
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
}
Upvotes: 0
Reputation: 52689
As some possible work arounds how about:
Using net use /user parameter to authenticate access to the network path
[/USER:[dotted domain name\]username]
[/USER:[username@dotted domain name]
Upvotes: 2