リモート Powershell スクリプト スケジュールされたタスク

リモート Powershell スクリプト スケジュールされたタスク

Powershell スクリプトをスケジュールされたタスクとして実行する際に問題が発生しています。スクリプトは 2 つの Hyper-V ホストにリモートでログインし、レプリケーション ステータスを照会して、結果を電子メールで返します。Powershell ISE で手動で実行するか、スクリプトを直接実行すると、スクリプトは正常に動作しますが、スケジュールされたタスクとして実行すると、タスクが実行状態で停止し、結果が得られません。

スクリプトを、ローカル フォルダーにテキスト ファイルを書き込むだけのスクリプトに置き換えて、スケジュールされたタスクの設定が正しく機能していることを確認しました。そのため、これは問題ではありません。また、スクリプトを手動で実行するときに、タスクが実行されるのと同じユーザーとしてログインしているので、これは問題ではありません。何が足りないのでしょうか?

これが私のスクリプトです:

$array = @("host1.domain.com", "host2.domain.com")

for ($i=0; $i -lt $array.length; $i++) {

     $pass = cat C:\Scripts\Creds.txt | convertto-securestring
     $mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist "username",$pass

Invoke-Command -ComputerName $array[$i] -Credential $mycred -FilePath "C:\Scripts\Check_VMReplication.ps1"
}

スクリプトは同じフォルダー内の別のスクリプトを呼び出します。

$hstname = Hostname
$Replication = Get-VMReplication
$MessageFail = $hstname + ' Replication Alert'
$SmtpServer = 'smtp.server.com'

hostname > C:\Scripts\iveremoted.txt

for ($i=0; $i -lt $Replication.length; $i++) {

        $MessageBody = $hstname+ " has reported a replication status of " + $Replication.health[$i] + ' for server ' + $Replication.name[$i]
        $FailMessageSubject = $Replication.name[$i] + " Replication Alert"
        if ($Replication.health[$i] -ne 'Normal') {

         send-mailmessage -to "[email protected]>" -from '[email protected]' -subject $MessageFail  -body $MessageBody -smtpServer $SmtpServer
    }
    else{
        send-mailmessage -to "[email protected]" -from '[email protected]' -subject 'Everything's OK'  -body $MessageBody -smtpServer $SmtpServer
    }

}

iveremoted.txt ファイルがリモート マシンに書き込まれないため、スクリプトはログオンできないようです。

私が見逃したものについて何か考えはありますか?

答え1

理由は分かりませんが、Check_VMReplication.ps1コードを実行すると、

Invoke-Command  -Credential $mycred -ScriptBlock {CODE GOES HERE} 

2 番目のスクリプト ファイルの代わりに、問題なく実行されます。そのようにするしかないと思います。

関連情報