Keifer Bly
Keifer Bly

Reputation: 57

How to run a powershell command in c#

So I am attempting to change the creation date of a text file in C#. The user will type in thr creation date of the file, it will then change the text files creation date to what the user inputted. Trouble is it keeps adding a ' for some reason resulting in an error message, it is calling on Powershell to accomplish this:

    public partial class Form6 : Form
    {
        public Form6()
        {
            InitializeComponent();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string dir = textBox1.Text;

            PowerShell ps = PowerShell.Create();



          ps.AddCommand("Get-ChildItem c:\\encryptedmessagehere.txt | % {$_.CreationTime = '"+ dir + "'}");

            ps.Invoke();
        }
    }
}

Trouble is, after the "'}");, it automatically adds another ', incorrecting the powershell command to change the date. Is there a way to stop it from adding the ' at the end?

The returned error is:

System.Management.Automation.CommandNotFoundException HResult=0x80131501 Message=The term 'Get - ChildItem C:\encryptedmessagehere.txt | % {$_.CreationTime = '06/12/12 09:27:03 AM'} ' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Thank you.

Upvotes: 2

Views: 13712

Answers (2)

Michael
Michael

Reputation: 864

In case anyone wants to know, you need to install the following NuGet packages to use PowerShell in C#:

  • Microsoft.PowerShell.SDK
  • System.Management.Automation

That's how I was able to get Jack J Jun's answer to work.

Upvotes: 8

Jack J Jun- MSFT
Jack J Jun- MSFT

Reputation: 5986

First, you need to use Powershell.AddScript method instead of Powershell.AddCommand method.

Second, you can try the following Powershell code to change the creation time of the file.

(Get-ChildItem d:\Test\new.txt).CreationTime =  '2020/09/23'

Finally, you can try the following c# code example to call powershell code in c#.

private void button1_Click(object sender, EventArgs e)
        {
            string datetime= textBox1.Text;
            PowerShell ps = PowerShell.Create();
            string script = string.Format("(Get-ChildItem d:\\New.txt).CreationTime = '{0}'", datetime);
            ps.AddScript(script);
            ps.Invoke();
            MessageBox.Show("Test");
        }

Upvotes: 7

Related Questions