4

使用的 Powershell 版本:3.0

大家好,

我正在尝试创建一个新的 Powershell 管道并在其中执行一个脚本,然后将它产生的输出获取到一个输出变量中,但是我无法从对象内部(从执行的脚本)中获得任何输出。这样做的重点是我不必管理 $Error 对象,我打算将其用于错误检测。下面是一个示例:

$ps = [Powershell]::Create()

$File = ".\Test2.ps1"
$SortedParams = "-Name blah -Key foo"
$RootDirectory = Get-Location
$ExecutionDirectory = "$RootDirectory\Test3"

$ps.AddCommand("Set-Location").AddParameter("Path", "$ExecutionDirectory")
write-host "COMMAND 1: " $ps.Commands.Commands.Item(0).CommandText

$ps.AddScript("$File $SortedParams")
write-host "COMMAND 2: " $ps.Commands.Commands.Item(1).CommandText

$output = $ps.Invoke()

write-host $output

我应该提到我正在尝试使用以下 3 种方法在执行的脚本中产生输出:

  • 写主机
  • 写输出
  • Write-Verbose(使用 $ps.Streams.Verbose 尝试获取输出,但没有)

非常感谢您提供的任何建议或提示!

4

4 回答 4

2

除非您觉得有特殊需要以您正在做的方式做事,否则您可能想考虑使用 PowerShell 后台作业。

后台作业允许您在单独的 PowerShell 实例中运行 PowerShell 命令,然后将这些作业的输出收集到一个变量中(如果您想要这样做)。

查看 about_Jobs 帮助主题以获取更多信息。

这是一个简单的例子:

$job = Start-Job -ScriptBlock { "Hello World!" }
$ret = Receive-Job $job -Wait -AutoRemoveJob

# value of $ret will be "Hello World!"
于 2013-08-16T18:44:42.713 回答
0

您可以使用 Invoke-Expression cmdlet 调用另一个脚本并使用 -OutVariable 参数捕获其输出。我建议使用 Out-Null 以便数据不会两次填充到控制台,请随时删除该管道命令。这是一个例子:

Invoke-Expression -Command "c:\EventLog.ps1" -OutVariable $data | Out-Null

Write-Host $data

这是我在上面示例中使用的示例脚本的代码:

Param($ComputerName = ".")

Get-EventLog -ComputerName $ComputerName -Log application -EntryType Error | 
    Group-Object -Property source | 
    Sort-Object -Property Count -Descending | 
    Format-Table Count, Name -AutoSize
于 2013-08-16T18:37:11.797 回答
0

检查您的错误流是否有错误:

$ps.Streams.Error

这对我有用:

$ps = [Powershell]::Create()
cd 'C:\Users\Andy\Documents'
$File = ".\Test2.ps1"
$SortedParams = "-Name blah -Key foo"
$RootDirectory = Get-Location
$ExecutionDirectory = "$RootDirectory\Test3"
$ps.AddCommand("Set-Location").AddParameter("Path", "$ExecutionDirectory") | Out-Null
$ps.AddScript("$File $SortedParams") | Out-Null
$output = $ps.Invoke()
write-host $output

这显示了我的设置:

显示文件组织:

Command: 

tree.com /F /A $ExecutionDirectory

Output: 

C:\USERS\ANDY\DOCUMENTS\TEST3
    Test2.ps1

显示脚本内容:

Command:

cat "$ExecutionDirectory\Test2.ps1"

Output: 

param (
    $Name,
    $Key
)
$Name
$Key
于 2013-08-20T06:23:44.120 回答
0

我正在使用 Invoke-Expression,这是唯一适合我的解决方案:

测试2.ps

Invoke-Expression .\test1.ps1 | Tee-Object -Variable msg | Out-Null
write-host "Return: $msg"</code>

和test1.ps:

$hola="Testing"
$hola

称呼:

C:\Test>powershell -ExecutionPolicy unrestricted -file test2.ps1
Return: Testing
于 2015-03-11T20:03:11.230 回答