如何使用C#调用PowerShell w32tm resync命令?

时间:2015-11-04 15:57:17

标签: c# powershell

我想在远程设备上调用w32tm resync并确定它是否成功。这是我现在正在尝试的没有运气。我的代码中有明显的错误吗?

   static void Main(string[] args)
    {
        using (PowerShell PowerShellInstance = PowerShell.Create())
        {
            //// use "AddScript" to add the contents of a script file to the end of the execution pipeline.
            //// use "AddCommand" to add individual commands/cmdlets to the end of the execution pipeline.

            //Create password variable
            PowerShellInstance.AddScript("$password = ConvertTo-SecureString \"mypassword\" -AsPlainText -Force;");

            //Create Credential Object
            PowerShellInstance.AddScript("$cred = New-Object System.Management.Automation.PSCredential (\"mycomputer\\Administrator\",$password);");
            PowerShellInstance.AddScript("Invoke-Command -ComputerName minwinpc -Credential $cred -ScriptBlock {w32tm /resync /force;}");

            Collection<PSObject> PSOutput = PowerShellInstance.Invoke();

            foreach (PSObject outputItem in PSOutput)
            {
                if (outputItem != null)
                {
                    Console.WriteLine(outputItem.BaseObject.GetType().FullName);
                    Console.WriteLine(outputItem.BaseObject.ToString() + "\n");
                }
            }
            Console.WriteLine("DONE");
            Console.ReadLine();
        }


    }

0 个答案:

没有答案