是首选Powershell -sta(公寓状态)吗? [英] Is Powershell -sta (apartment state) preferred?

查看:131
本文介绍了是首选Powershell -sta(公寓状态)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去的几个月中,我一直在研究Powershell(2.0),并且很乐意使用它来对工作中的某些过程进行现代化和标准化,主要是基于DOS的过程.由于工作的性质,一次执行大约100次相同脚本的执行.

I've been dabbling in Powershell (2.0) for the past several months and would love to use it to modernize and standardize some of the processes at work - mostly DOS based processes. Because of the nature of the work, there could be around 100 executions of the same script(s) going at once.

首先-以这种方式使用Powershell是否安全?我已经将-STA视为执行选项-是同时执行大量相同脚本时使用Powershell的首选方法,还是仅在绝对必要时才使用的东西?在搜索中,我并没有真正想到我何时应使用公寓状态?"的答案.我相信,即使不是我打算做的所有脚本,大部分也不会被线程化.

First--Is Powershell "safe" to use in this manner? I have seen -STA as an execution option - is that the preferred method of working with Powershell when executing a good number of the same script simultaneously, or is that something that is only used when absolutely necessary? In my searching, I haven't really come up with an answer for "When should I use apartment state?" I believe most if not all of the scripting I intend to do will not be threaded.

在此先感谢任何可以了解Powershell公寓状态的人!

Thanks in advance for anyone who can shed light on Powershell apartment state!

推荐答案

在PSv2中,控制台主机作为MTA运行,而ISE作为STA运行.在PSv3中,控制台默认为STA .

In PSv2, the console host runs as MTA, and the ISE runs as STA. In PSv3 the console defaults to STA.

您可以通过以下方式查看您的公寓状态:

You can see what your apartment state is with this:

[System.Threading.Thread]::CurrentThread.GetApartmentState()

您唯一需要使用STA的地方是在.NET中使用某些类处理使用它的COM对象时,例如System.Windows.Forms.Clipboard.

The only time you need to use STA is when using certain classes in .NET that deal with COM objects that use it e.g. System.Windows.Forms.Clipboard.

我知道有两种方法可以更改为STA:

There are two ways I know of to change to STA:

powershell.exe -Sta -File MyScript.ps1

$ps = [PowerShell]::Create()
$rs = [RunSpaceFactory]::CreateRunspace()
$rs.ApartmentState = "STA"
$rs.ThreadOptions = "ReuseThread"
$rs.Open()
$ps.Runspace = $rs
$ps.AddScript( { ([System.Threading.Thread]::CurrentThread.GetApartmentState()) } ).Invoke()

所以问题实际上是,为什么PSv2控制台是MTA而不是STA?当我想知道PS团队为何做出这样的决定时,我通常会参考Bruce Payette的《 PowerShell in Action》一书.不幸的是,它没有说明原因.它只是说有些COM对象需要STA,如果您的脚本不起作用,请尝试将其重新运行为STA.

So the question really is why is the PSv2 console MTA instead of STA? When I want to know why the PS team made decisions like this I usually refer to Bruce Payette's PowerShell in Action book. Unfortunately it didn't say why. It just said there are some COM objects that require STA and if your script doesn't work try re-running it as STA.

这篇关于是首选Powershell -sta(公寓状态)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆