开发者

How to Load Function in new Powershell.exe Console

I have a function (function1) which requires sta mode. I'd like tocall this function from a non sta mode开发者_Go百科 poshconsole. This works when i have function1 in my Profile

$command = "function1 'MyArguments'"
powershell -sta -command $command

But how can i do this when i have the function1 not in the profile and i call

powershell -sta -noprofile -command $command

Can i execute multiple commands with a powershell.exe call? Or can i handover a customprofilepath?


You can separate multiple commands with a semicolon (;) for example, dot source your script containing your function, then call the function:

powershell -sta -noprofile -command ". c:\functions.ps1 ; function1 'MyArguments'"


There are some ways how to deal with STA:

  • Single Threaded Apartment in PowerShell V1
  • Asynchronicity in PowerShell
  • Thread.ApartmentState and PowerShell Execution Thread

In case you will call powershell.exe (because it is obviously easier), you can first load your script with the function and then execute function1 'My arguments'

powershell -sta -noprofile -command '<pathToYourScript>.ps1; function1 args'

I tried to use -file parameter and -command argument together, but that doesn't work.


If you are running the PowerShell Community Extensions you can use Invoke-Apartment e.g.:

PS> Invoke-Apartment -Apartment STA `
                     -Expr {[Threading.Thread]::CurrentThread.ApartmentState}
STA
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜