【问题标题】:Powershell - Different method of including code?Powershell - 包含代码的不同方法?
【发布时间】:2016-06-17 13:24:45
【问题描述】:

我有 3 个脚本:

  • 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 脚本被调用,所以这应该是整个脚本的名称,不管它之后调用什么?

【问题讨论】:

  • 您基本上希望$MyInvocation.MyCommand.Name 包含与文件本身不同的脚本文件?你为什么要这么做?
  • $MyInvocation 不会在多个文件中保持一致。也许您可以使用另一个脚本来连接Test1.ps1Test2.ps1Test3.ps1?然后它们都将在相同的上下文中运行。

标签: powershell scripting include


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2012-12-22
      • 2011-09-10
      • 2018-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-05
      • 2015-09-28
      相关资源
      最近更新 更多