0
12

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 3 years have passed since last update.

PowerShell IEで自動ログイン

Last updated at Posted at 2020-05-30

#やりたいこと
毎日のようにアクセスするページにIDとPWを毎回入れるのが面倒なので、
簡単に自動ログインしたい

#前提
ホームページはHTMLのものが対象。
Flashのページはできない。(というかやり方がわからない)

#事前準備
ホームページのソースコードを表示して以下の項目を調べておく
1.ログインID入力BOXのID属性
2.PW入力BOXのID属性
3.ログインボタンのID属性(※)

ログインボタンにIDが付与されていない場合がある。
その場合は、name属性などを対象にする

#コード

login.ps1

##=======================================================
## パラメータ設定
##=======================================================
$user_id = "user"
$user_pw = "pw"
$url = "http://test.aspx"

##=======================================================
##事前設定
##=======================================================
#IE
$ie = New-Object -ComObject InternetExplorer.Application

##=======================================================
##スクリプト本体
##=======================================================
#--------------------------------
# IEを起動する
#--------------------------------
# IE起動
$ie.Visible = $true

# ウィンドウハンドル
$hwnd = $ie.HWND

#URLへアクセス(キャッシュ無効)
$ie.Navigate($url,4)

#待ち
While($ie.Busy){start-sleep -milliseconds 100}
$doc = $ie.document

#--------------------------------
# ID PW 入力
#--------------------------------
# ID入力(idがある場合、getElementByIDで指定)
$dom_userID=$doc.getElementByID("UserId")
$dom_userID.value=$user_id

# PW入力(idがある場合、getElementByIDで指定)
$dom_userPW=$doc.getElementByID("Password")
$dom_userPW.value=$user_pw

# ログインボタン(idがある場合、getElementByIDで指定)
$btn=$doc.getElementById("LoginButton")
$btn.click()


#実行方法
PowerShellの使い方はググれば出てくるが、.ps1ファイルはダブルクリックで一発実行ができない。
セキュリティポリシーがあるようでおまじないが必要である。
簡単に実行する方法はいくつかあるが以下がおすすめ。

同じフォルダにps1とbatを用意する
ファイル名は2つとも同じにすること(理由は後で述べます)
login.ps1
login.bat

bat(バッチファイル)は以下のように記載

login.bat
powershell -ExecutionPolicy RemoteSigned -File .\%~n0.ps1

#バッチファイル解説
##-ExecutionPolicy RemoteSigned
ローカルのps1の実行を許可
##%~n0
バッチファイルのファイル名を取得する。上記の場合は、"login"

バッチファイル自身の名前のps1ファイルを管理者権限で実行するバッチになります。
別のページにログインするスクリプトを作る場合はバッチファイルのファイル名だけ変えれば流用できます。

0
12
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
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?