I'm trying to capture the Console warning that is outputted after running the Rename-Computer command. I'd tried to tie bits and piece from other Stack Overflow threads on output redirection, but I can't seem to get it to work.
What I'm trying to do is rename a remote computer into a variable. After the command successfully completes, take the warning "WARNING: The changes will take..." and have its string placed in the variable.
Invoke-Command -ComputerName $deviceName -ScriptBlock{param($name); Rename-Computer $name -DomainCredential (Get-Credential) | Out-String -InputObject $output ;Return $output} -ArgumentList $newDeviceName
I have tried the Invoke-Command inside a var and out to see if that changes anything. The reason I want the console message placed into the variable and not do redirection to a file is because I'm messing around with WPF GUI and want the warning printed to my GUI window.
CodePudding user response:
Assuming the output from Rename-Computer is going to the Warning stream, this is how you can capture it:
$output = Invoke-Command -ComputerName $deviceName -ScriptBlock{
param($name)
Rename-Computer $name -DomainCredential (Get-Credential) 3>&1
} -ArgumentList $newDeviceName
$output # => Should be the warning from Rename-Computer
Here is a simple example:
$capture = Write-Warning 'Hello World!' # doesn't work!
$capture = Write-Warning 'Hello World!' 3>&1 # works!
For more information, see about_Output Streams and about_Redirection.
