I’m having some inconsitant issues with processing “net use” output from within a script.
Background: I have a script which reads in a list of servers, then attaches to them, reads some data, then detaches and moves to the next. There is a dot-sourced file, functions.ps1, which contians the function ConnectToTarget(). The offending part of the code is:
function ConnectToTarget() ... LogMessage "Connecting to server as `"$($credential.UserName)`"" "" | & net use "\\$($computer.DnsName)" "/u:$($credential.UserName)" $credential.GetNetworkCredential().Password /n 2>&1 | foreach { # # Remove embedded newline chars from the output that shows up sometimes # DebugMessage "`$_.ToString() =`"$($_.ToString().Replace("`r`n","[\r\n]"))`"" $CommandOutput = $_.ToString().Replace("`r`n","") DebugMessage "`$CommandOutput =`"$CommandOutput`"" if ($CommandOutput -ne "") { # # Keep the most recent message in case we need to save it in the computer object # $LastNativeOutput = "netuse: $CommandOutput" DebugMessage "`$LastNativeOutput =`"$LastNativeOutput`"" LogNativeOutput $LastNativeOutput } } DebugMessage "`$LASTEXITCODE = $LASTEXITCODE" if ($LASTEXITCODE -ne 0) { DebugMessage "Setting connection status to Failed" $Computer.ErrorMessage = $LastNativeOutput if ([string]::IsNullOrEmpty($Computer.ErrorMessage)) { $Computer.ErrorMessage = "netuse: Unknown error. LASTEXITCODE = $LASTEXITCODE" } $computer.ConnectionStatus = "Failed" }
I have one server in the list which generates the following output to the log:
Connecting to server as “XXXXXXXXXX”
$LASTEXITCODE = 2
Setting connection status to Failed
Exiting functions::ConnectToTarget()
*** netuse: Unknown error. LASTEXITCODE = 2
Here, I’m not seeing any of the “net use” output in the foreach. However, if I run the (virtually) same code interactively, it works as expected:
$a = @()
$comp = “Not-Important”
“” | & net use “\$comp” “/u:XXXXXXXX” XXXXXXXX /n 2>&1 | foreach {
#
# Remove embedded newline chars from the output that shows up sometimes
#
write-host “$_.ToString() =
”$($_.ToString().Replace(“r
n”,“[\r\n]”))"" $CommandOutput = $_.ToString().Replace("
rn","") write-host "
$CommandOutput ="$CommandOutput
""
if ($CommandOutput -ne “”)
{
#
# Keep the most recent message in case we need to save it in the computer object
#
$LastNativeOutput = “netuse: $CommandOutput”
write-host “$LastNativeOutput =
”$LastNativeOutput`“”
}
}
$.ToString() = “System error 1789 has occurred.”
$CommandOutput = “System error 1789 has occurred.”
$LastNativeOutput = “netuse: System error 1789 has occurred.”
$.ToString() = “[\r\n]The trust relationship between this workstation and the primary domain failed.[\r\n][\r\n]”
$CommandOutput = “The trust relationship between this workstation and the primary domain failed.”
$LastNativeOutput = “netuse: The trust relationship between this workstation and the primary domain failed.”
Any thoughts as to why the same code behaves differnetly in a script vs. when run interactively?