用Process调用PowerShell连接虚拟机后,部分PowerShell代码运行不了,而且不显示报错。
代码如下:
var p = new Process//基本配置
{
StartInfo = {
WorkingDirectory = Environment.CurrentDirectory,
UseShellExecute = false,
FileName = "PowerShell.exe",
CreateNoWindow = true,
Verb = "runAs",//以管理员身份启动没用
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
}
};
p.Start();
//定义连接虚拟机的凭据
p.StandardInput.WriteLine("$account = " + "\"administrator\"");
p.StandardInput.WriteLine("$password = '123'");
p.StandardInput.WriteLine("$secpwd = convertto-securestring $password -asplaintext -force");
p.StandardInput.WriteLine("$cred = new-object System.Management.Automation.PSCredential -argumentlist $account,$secpwd");
//连接虚拟机 192.168.11.104
p.StandardInput.WriteLine("Enter-PSSession -Credential $cred -computer 192.168.11.104");
//连接虚拟机后执行清除 C:\Windows\SoftwareDistribution\Download 的所有东西
p.StandardInput.WriteLine(@"Remove-item C:\Windows\SoftwareDistribution\Download -Recurse -Force -Confirm:$false");
p.StandardInput.Close();
String error = null;
String output = null;
while (!p.StandardOutput.EndOfStream)
{
output += p.StandardOutput.ReadToEnd();
error += p.StandardError.ReadToEnd();
}
Console.WriteLine("-----------------------------------------------------------------------------");
Console.WriteLine(error);//输出错误信息
Console.WriteLine("-----------------------------------------------------------------------------");
Console.WriteLine(output);//输出执行信息
Console.WriteLine("-----------------------------------------------------------------------------");
p.Close();
执行后:
虚拟机192.168.11.104 的C:\Windows\SoftwareDistribution\Download的东西还在
不用StandardInput.WriteLine执行指令后,手动输入可以执行删除指令:
执行后手动输入代码
如果不连接虚拟机可以执行代码并输出结果
并非权限问题,非管理员也可以运行这代码
有没有巨佬研究过为什么连接虚拟机后代码就不管用了