Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

powershell - How to Write-Verbose from Invoke-Command?

In powershell

Write-Verbose and the -Verbose flag are used to provide verbose information when commands are run in verbose mode. I am running some scripts remotely and would like to capture the verbose output output. However, Invoke-Command seems to not capture the verbose channel.

PS:> Invoke-Command -ComputerName MY-COMPUTERNAME -Verbose { Write-Verbose "blah" }
PS:>

How do I capture verbose output when running remote scripts?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Best thing I think you could do is create a function that has [CmdletBinding()] so it supports the -verbose switch. Then you would be able to capture the verbose state of the local function using the local $VerbosePreference and pass it along in the invoke command. This will only work in Powershell 3.0 and higher, since you will need to use the $Using scope modifier.

Function write-blah{
[CmdletBinding()]
Param()
Invoke-Command -ComputerName MY-COMPUTERNAME  {$VerbosePreference=$Using:VerbosePreference; Write-Verbose "blah" }
}

Then you would call your function like this.

Write-Blah -verbose

In testing this has worked for me. I believe your function must support parameters, hence the empty Param() block.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...