2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ログイン時の処理をpowershellで書きたい(Windows)

2
Posted at

はじめに

ログイン時に行いたい処理があるとき,shell:startup フォルダにpowershellのスクリプト(やそのショートカット)を置くことがあると思います。

私の場合は,GPG4Winでssh鍵の管理をしていまして,以下の作業をログイン時に行っています:

  • gpg-agentを立ち上げる
  • wsl-ssh-pageant を立ち上げる

そのままだと,ログイン時にコンソールウィンドウが一瞬立ち上がってしまい,ウィンドウのフォーカスが奪われてちょっとストレスです。

この記事は,コンソールウィンドウを立ち上げないでpowershellスクリプトを実行するためのものです。

考え方

コンソールウィンドウを表示しないためには,いくつかの方法があります:

  1. VBScriptでWscript.Shellを作り,runメソッドにvbHideを指定する
  2. conhost.exeのheadlessオプション

VBScriptは将来廃止される方向なので,2の方法で行きます。
conhostをheadlessオプション付きで呼び出すショートカットを shell:startup に置けばよい,ですね。

設定方法

プロファイルフォルダにbin/フォルダを作り,startup.ps1 を置きます。
そのうえで,以下のスクリプトを実行します。

$bin = $Env:USERPROFILE + "\bin"
$startupPath = $bin + "\startup.ps1"

$shellFolders = $(Get-ItemProperty 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders')
$shortcutPath = $shellFolders.Startup + "\startup.lnk"

$scriptShell = New-Object -ComObject WScript.Shell
$Shortcut = $scriptShell.CreateShortcut($shortcutPath)
$shortcut.TargetPath = "C:\Windows\System32\conhost.exe"
$shortcut.Arguments = ("--headless pwsh -NoProfile -ExecutionPolicy Bypass -File " + $startupPath)
$shortcut.Save()

スクリプトは,startup.ps1とショートカットのパスを取得し,ショートカットを作成しているだけです。私はpowershell 7系を使いたいのでpwshを起動していますが,Windowsに標準添付のものをつかうなら powershell にすればよいです。

参考にさせていただいたWebページ

この記事は,以下の内容を組み合わせただけ...です。記事に残してくださることありがたいです。

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?