gpt4 book ai didi

windows - powershell 函数返回错误结果

转载 作者:可可西里 更新时间:2023-11-01 11:15:31 27 4
gpt4 key购买 nike

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

$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

当我运行它时它起作用了,但是我在返回变量中注入(inject)了一个“True”。我得到以下输出:

out: True domain\test

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

问题是什么?谢谢

最佳答案

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

值从何而来:

  # 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() |出空

上一行丢弃了 True 返回值。作为替代方案,您可以将结果存储在一个变量中并保持未使用状态,例如:

$rv = $Process.Start()

另请注意,PowerShells return 语句与例如C#之一。

你的线路:

返回 $result

相当于:

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

阅读此 link有关返回的更多信息。

希望对您有所帮助。

关于windows - powershell 函数返回错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52831143/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com