Powershell函数返回不良结果

时间:2018-10-16 08:29:55

标签: windows shell powershell

我有这个功能,可以以另一个用户的身份运行命令并返回结果。

$OutputEncoding = [ System.Text.Encoding]::UTF8   
write-host (get-date -format s) " Beginning script..."
function getCreds()
{
    $Username = 'domain\user'
    $Password = 'test'
    $pass = ConvertTo-SecureString -AsPlainText $Password -Force
    $Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $UserName, $pass
    return $Credential;
}
function executeAsCryptUser($cmd){

write-host "cmd:"$cmd
$creds=getCreds
#Use System.Diagnostics to start the process as UserB
$ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo
#With FileName we're basically telling powershell to run another powershell process
$ProcessInfo.FileName = "powershell.exe"
#CreateNoWindow helps avoiding a second window to appear whilst the process runs
$ProcessInfo.CreateNoWindow = $true
#Note the line below contains the Working Directory where the script will start from
$ProcessInfo.WorkingDirectory = $env:windir
$ProcessInfo.RedirectStandardError = $true 
$ProcessInfo.RedirectStandardOutput = $true 
$ProcessInfo.UseShellExecute = $false
#The line below is basically the command you want to run and it's passed as text, as an argument
$ProcessInfo.Arguments = $cmd
#The next 3 lines are the credential for UserB, as you can see, we can't just pass $Credential
$ProcessInfo.Username = $creds.GetNetworkCredential().username
$ProcessInfo.Domain = $creds.GetNetworkCredential().Domain
$ProcessInfo.Password = $creds.Password
#Finally start the process and wait for it to finish
$Process = New-Object System.Diagnostics.Process 
$Process.StartInfo = $ProcessInfo 
$Process.Start() 
$Process.WaitForExit() 
#Grab the output
$GetProcessResult = $Process.StandardOutput.ReadToEnd().ToString()
Write-host "Potential Error:"+ $Process.StandardError.ReadToEnd().ToString()
$result=$GetProcessResult.Trim()
write-Host "Debug output:"$result

return $result
}

$pop=executeAsCryptUser "whoami"
write-host "out:" $pop

当我运行它时,它可以工作,但是我在返回变量中注入了“ True”。我得到以下输出:

  

退出:真实域\测试

如果我调试脚本并查看$result,但在变量中找不到“ True”的踪迹。

出什么问题了? 谢谢

1 个答案:

答案 0 :(得分:4)

您的问题是您正在将两个值写入输出流,该值用于在函数之间传输值(在管道中)。

这些值从何而来:

  # Below return "True" to the output-stream
  $Process.Start()
  ...
  # Below appends the content of "result" and return from the function
  return $result

阅读此link有关流的信息。简而言之:除非将结果存储在变量中,否则命令的每个返回值都会写入输出流。

我认为您需要更改

$Process.Start()

$Process.Start() | Out-Null

以上行将丢弃True返回值。或者,您可以将结果存储在变量中并保持未使用状态,例如:

$rv = $Process.Start()

还要注意,PowerShells return语句与例如C#之一。

您的行:

return $result

等效于:

# Append content to output stream
$result
# return from the function
return

阅读此link,了解有关退货的更多信息。

希望有帮助。