19

I am really fond of python's capability to do things like this:

if __name__ == '__main__':
    #setup testing code here
    #or setup a call a function with parameters and human format the output
    #etc...

This is nice because I can treat a Python script file as something that can be called from the command line but it remains available for me to import its functions and classes into a separate python script file easily without triggering the default "run from the command line behavior".

Does Powershell have a similar facility that I could exploit? And if it doesn't how should I be organizing my library of function files so that i can easily execute some of them while I am developing them?

4

4 に答える 4

7

$MyInvocation.Invocationスクリプトの開始方法に関する情報があります。

If ($MyInvocation.InvocationName -eq '&') {
    "Called using operator: '$($MyInvocation.InvocationName)'"
} ElseIf ($MyInvocation.InvocationName -eq '.') {
    "Dot sourced: '$($MyInvocation.InvocationName)'"
} ElseIf ((Resolve-Path -Path $MyInvocation.InvocationName).ProviderPath -eq $MyInvocation.MyCommand.Path) {
    "Called using path: '$($MyInvocation.InvocationName)'"
}
于 2011-04-07T14:26:47.193 に答える
6

$MyInvocation現在のコンテキストと呼び出し元のコンテキストに関する多くの情報があります。おそらく、これを使用して、スクリプトがドットソース (インポート) されているか、スクリプトとして実行されているかを検出できます。

スクリプトは関数のように機能paramします。ファイル内の最初の非共通/空白として使用して、パラメータを定義します。開始するスクリプトをドットソースするとどうなるかは明確ではありません (別の組み合わせを試す必要があります) param

モジュールは、コードを直接実行したり、関数、変数などをエクスポートしたり、パラメータを取得したりできます。たぶん$MyInvocation、モジュールで2つのケースを検出できるようになるでしょう。

編集:追加:

$MyInvocation.Line現在のスクリプトまたは関数を実行するために使用されるコマンド ラインが含まれます。そのLineプロパティには、実行に使用されるスクリプト テキストがあります。ドット ソースを使用する場合、これは " ." で始まりますが、スクリプトとして実行する場合はそうではありません (明らかに、ピリオドの周りに可変の空白を許可するために正規表現の一致を使用する場合)。

関数として実行されるスクリプト内

于 2011-01-14T17:38:21.797 に答える