0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

schtasksでPowershellスクリプトを実行する(CLI)

Last updated at Posted at 2021-04-04

やりたいこと

Windows10にSSH接続して、リモートに置いてあるスクリプトを接続先で実行します。
リモートとはUNCパスで表す必要のある位置の事です。
例えば、\\10.0.0.2\cc\test.bat\\pcname\share\sample.ps1などを指します。

結論

Adminsに所属するユーザー権限で拒否されたので、system権限が要るのかと思った。
しかし、Admins所属ユーザーでかつ、そのユーザーがもつ最高権限で実行するように設定すれば良さそう。

手順

  1. sshで対象のWindowsのCLIに接続します。
  2. schtaskを使ってスケジュールタスクを準備&実行します。

使ったコード

main.ps1を実行したい。

UNC_Path_To_Here\cc\launch.cmd
@echo off
pushd %~dp0
del  %SystemDrive%\cc\cc.log
copy .\main.ps1 %temp%\
call pwsh -Noprofile -ExecutionPolicy Bypass -File %temp%/main.ps1
exit
UNC_Path_To_Here\cc\main.ps1
mkdir $env:SystemDrive\cc -force
whoami | out-file $env:SystemDrive\cc\cc.log -append
date | out-file $env:SystemDrive\cc\cc.log -append
$psversiontable | out-file $env:SystemDrive\cc\cc.log -append

上手くいった方法

schtasks /create /tn ThisIsTask /sc ONCE /tr "UNC_Path_To_Here\cc\launch.cmd" /ru IamContainAdministrators /rp "SecretPassword" /rl highest /f /st 16:23

失敗した例と理由

こちらの構文でスケジュールタスクを設定してみました。

schtasks /create /tn ThisIsTask /sc ONCE /tr "UNC_Path_To_Here\cc\launch.cmd" /ru SYSTEM /rl highest /f /st 16:23

接続先のローカルにおいてあるスクリプトならこれでいけます。
しかし、下記のコマンドで確認してみると、出来ないことが分かります。

 schtasks /query /tn gfreboot /v /fo list

この出力結果に実行結果が表示されている行があります。

Last Result:    -2147024891

Last Result、日本語だと、「前回の実行結果」になっていると思います。これが、16進数表記で0x80070005です。調べると、COMインターフェースの実行結果でHRESULT型で表されたE_ACCESSDENIED「アクセス拒否」というエラーだそうです。

なんの理由でアクセス拒否なのか分かりませんが、NT AUTHORITY\System「システム」の権限では弾かれるようです。

更に調査をして「システム権限が要らないんじゃない?」という結論にたどり着きました。「Administratorsに所属するアカウントでタスクを実行するようにし、そのタスクのRunLevelをHighestにすればよい」とのことです。これを実践したのが上記の「上手くいった方法

公式ドキュメント

Excelsior!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?