Powershell - 包含代码的不同方法?

时间:2016-06-17 13:24:45

标签: powershell scripting include

我有3x脚本:

  • C:\ Powershell的\ Test1.ps1: WRITE-HOST "My Name is" $MyInvocation.MyCommand.Name . "C:\Powershell\Test2.ps1"
  • C:\ Powershell的\ Test2.ps1: WRITE-HOST "My Name is" $MyInvocation.MyCommand.Name . "C:\Powershell\Test3.ps1"
  • C:\ Powershell的\ Test3.ps1: WRITE-HOST "My Name is" $MyInvocation.MyCommand.Name

这是输出: PS C:\Powershell> .\Test1.ps1 My Name is Test1.ps1 My Name is Test2.ps1 My Name is Test3.ps1

我希望Test1.ps1能够在其自身内包含代码,而不是将它们作为脚本调用。

如果可能,这是我想要的那种输出: PS C:\Powershell> .\Test1.ps1 My Name is Test1.ps1 My Name is Test1.ps1 My Name is Test1.ps1

这可能吗?调用原始的Test1脚本,所以这应该是整个脚本的名称,不管之后调用的是什么?

2 个答案:

答案 0 :(得分:0)

我猜你可以使用Get-Content cmdlet。尝试这样的事情:

WRITE-HOST "My Name is $($MyInvocation.MyCommand.Name) `n`n $(Get-Content $($MyInvocation.MyCommand.Name))"

答案 1 :(得分:0)

您可以执行以下操作来阅读脚本的内容:

foreach ($File in (Get-Item -Path C:\PowerShell\* -Filter '*.ps1' | Select -ExpandProperty FullName))
{
    Write-Output "File: $File"
    Get-Content "$File"
}

输出如下:

PS C:\> foreach ($File in (Get-Item -Path C:\PowerShell\* -Filter '*.ps1' | Select -ExpandProperty FullName))
{
    Write-Output "File: $File"
    Get-Content "$File"
}
File: C:\PowerShell\test.ps1
test1 contents
File: C:\PowerShell\test2.ps1
test2 contents
File: C:\PowerShell\test3.ps1
test3 contents