超まとめ
powershellがSTA/MTA環境にかかわらずSTAで実行させるためのコード例です。
説明
Powershell v2.0ではデフォルトがMTAであるため、STAなCOMを使用しようとするとSTAで起動し直す必要があります。
それが面倒なので、スクリプト側で強制的にSTAで実行するようにしてみました。
$onStartUp = [Threading.Thread]::CurrentThread.GetApartmentState()
Write-Host "on start up: $onStartUp"
$myScriptName = & {$MyInvocation.ScriptName}
Write-Host "my script name: $myScriptName"
if( ([Threading.Thread]::CurrentThread.GetApartmentState()) -eq "MTA"){
"re-run"
powershell -sta -File $myScriptName
}else{
#ここにコードを書く
}
備考
powershell v3.0からはstaがデフォルトになったようです。
Excellent posts from you, man. I’ve figured out your idea and you’re simply quite great.
I love what you have here, really like what you’re saying and also the way by which you
say it. You make it enjoyable. I cant wait to read a lot more from you.
This is genuinely a wonderful website.