1

別のユーザーとしてコマンドを実行し、結果を返すこの関数があります。

$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」が挿入されました。次の出力が得られました。

out: 真のドメイン\テスト

スクリプトをデバッグして$result、変数に「True」の痕跡が見つからない場合。

何が問題ですか ?ありがとう

4

1 に答える 1