How to load a function into the new Powershell.exe console

I have a function (function1) that requires sta mode. I would like to activate this function from poshconsole in non sta mode. 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 function1 not in the profile and I call

 powershell -sta -noprofile -command $command 

Is it possible to execute several commands with calling powershell.exe? Or can I pass customprofilepath?

+4
source share
3 answers

You can separate several 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'" 
+2
source

There are several ways to work with STA:

If you call powershell.exe (because it is clearly simpler), you can first load your script using a function, and then execute function1 'My arguments'

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

I tried to use the -file and -command together, but this does not work.

+1
source

If you use PowerShell Community Extensions , you can use Invoke-Apartment, for example:

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

Source: https://habr.com/ru/post/1302125/


All Articles