从ps1文件

时间:2016-01-17 16:41:32

标签: powershell object powershell-v4.0

我发誓我已经看到了一个示例,说明如何“导入”.ps1(是的,故意不是.ps m 1)文件的内容。我的目标是在$变量中封装.ps1文件的内容,其中函数甚至可以在函数外部声明变量。所以,如果我有以下内容:

# ps1 file
Function myFunc {

  [CmdletBinding()]
  Param(...)

  # Function stuff

}

我想做这样的事情:

$newObject = New-Object (New-Module -ScriptBlock (%GET_CONTENT_FROM_PS1_FILE%))
$newObject.myFunc()
# etc.

这可能吗?

1 个答案:

答案 0 :(得分:0)

PetSerAl's comment中精彩的例子,你已经走上了正确的道路:

Baby (metal cover by Leo Moracchioli).mp3 fed to mPlayer
undefined
STDOUT: MPlayer2 2.0-728-g2c378c7-4+b1 (C) 2000-2012 MPlayer Team
Cannot open file '/root/.mplayer/input.conf': No such file or directory
Failed to open /root/.mplayer/input.conf.
Cannot open file '/etc/mplayer/input.conf': No such file or directory
Failed to open /etc/mplayer/input.conf.

Playing /home/danlevi/Documents/NodeServer/music/Bad Blood (metal cover by Leo Moracchioli).mp3.
Detected file format: MP2/3 (MPEG audio layer 2/3) (libavformat)
[mp3 @ 0xb62803a0]max_analyze_duration 5000000 reached
[lavf] stream 0: audio (mp3), -aid 0
Clip info:
 major_brand: dash
 minor_version: 0
 compatible_brands: iso6mp41
 creation_time: 2015-09-29 08:04:29
 encoder: Lavf54.20.4
Load subtitles in /home/danlevi/Documents/NodeServer/music/
Selected audio codec: MPEG 1.0/2.0/2.5 layers I, II, III [mpg123]
AUDIO: 44100 Hz, 2 ch, s16le, 128.0 kbit/9.07% (ratio: 16000->176400)
AO: [pulse] 44100Hz 2ch s16le (2 bytes per sample)
Video: no video
Starting playback...


MPlayer interrupted by signal 15 in module: unknown

Exiting... (Quit)

A:   9.1 (09.0) of 281.8 (04:41.7)  0.2% 

A:   9.1 (09.0) of 281.8 (04:41.7)  0.2% 

耶!问题是,这只导出函数,而不是任何变量。

您可以做的是将PS> $newObject=New-Module -ScriptBlock (Get-Command .\Test.ps1).ScriptBlock -AsCustomObject PS> $newObject.myFunc Script : OverloadDefinitions : {System.Object myFunc();} MemberType : ScriptMethod TypeNameOfValue : System.Object Value : System.Object myFunc(); Name : myFunc IsInstance : True 添加到ScriptBlock参数:

Export-ModuleMember

现在,变量$ps1ScriptBlock = Get-Content .\Test.ps1 -Raw $exportCommand = 'Export-ModuleMember -Function * -Variable *' $moduleScriptBlock = [scriptblock]::Create(@($ps1ScriptBlock,$exportCommand) -join "`r`n") $moduleObject = New-Module -ScriptBlock $moduleScriptBlock -AsCustomObject 将可以访问:

$myVar