I'm trying to use PowerShell from C# to create a new file on desktop. In the terminal you would do:
cd desktop
$null >> newfile.txt
So I'm trying to do this in C# to mimic the previous statements:
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript("cd desktop; $null >> newfile.txt");
PowerShellInstance.Invoke();
}
This runs without any exceptions but the file isn't created on the desktop. Can anyone point out what I'm doing wrong with the AddScript
?
EDIT
It looks like the problem comes from using cd and then the create in sequence.
I was able to get it working by doing
PowerShellInstance.AddScript("$null >> C:\\users\\me\\Desktop\\newfile.txt");
If anyone knows how to do a cd command followed by another please let me know.
To me it looks like the command cd desktop
itself is not working. If you open a powershell console then he default path it opens up in is C:\Users\user_name\
and most probably from c# it's not opening with that path rather instead is opening with the working directory being the debug folder of your current project; [as commented by @Nived]
There is no issue with your current code. Just change the script statement to below and it should work fine
cd C:\Users\user_name\desktop; $null >> newfile.txt
With that your C# code should be something like
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript(@"cd C:\Users\user_name\desktop; $null >> newfile.txt");
PowerShellInstance.Invoke();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With