How to run a powershell command in c#

0

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.

c#
string
visual-studio
powershell
asked on Stack Overflow Sep 22, 2020 by Keifer Bly • edited Sep 22, 2020 by Keifer Bly

1 Answer

0

First, you need to use Powersheel.AddScript method instead of Powersheel.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");
        }
answered on Stack Overflow Sep 23, 2020 by Jack J Jun - MSFT

User contributions licensed under CC BY-SA 3.0