Powershell result to c [Answered]
is it possible get a result from a powershell file after execution and store the result in a variable in c sharp? i have a powershell script that gives me an array and i want that array in c#
213 Replies
yeah i found that website to
but the problem is
they say "Create a System.Management.Automation.Powershell object" how do i do that. I'm knew to this so i'm sorry
Read the examples given
yeah
but look
i can't use create
so there is somthing wrong
You need to add NuGet package https://www.nuget.org/packages/System.Management.Automation
bruh my powehsell is glitching
i alraedey did that
sometimes its red and sometimes not
You have not imported the namespace
System.Management.Automation
like this?
No
ow ok
using?
✅
here you see red
and now good
how?
nothing changed
its changing every 2 sec
Probably because VSCode / Omnisharp
yeah vscode is glithcing as hell
If you're a beginner and you're on Windows, I highly recommend Visual Studio
which is different from Visual Studio Code
i'm not a real beginner, but i'm a beginner in c#
ohh serious?
but i'm used to program in vscode
If you're used to VSCode and you know dotnet CLI.
You should be fine.
But yeah, VSCode can be a little glitchy. Just something you need to live with I guess <:bing_shrug:583791581497393162>
oh ok thx
visual studio is so weird to
i open a folder and i see nothing
You should not open the folder
but the project itself
.csproj
or if a `.sln
file exists, then choose that over
*.csproj`i need to click on this right?
Make sure you install the workloads
yeah thats already done
Then press that
ok
Open that if no *.sln file exists
ok
bruh
press view
i cliked solution explorer
Now you can navigate it
just click on a file and start going
oh thx
i'm so noob in visual studio and c#
unbelievable
hahah
I did not notice the class you made is called PowerShell, lol.
I recommend renaming it as it can conflict with other classes called 'PowerShell'
i did that
ahh
Sweet!
does not exists
Right-click the project in solution explorer
press Manage Nuget packages
Browse for that nuget package, click it, then press install
good but he can't find Powerhsell
Class scope versus method scope
it can only be inside a method
ahh
he still can't find Powerhsell
hover over Powershell, click the lightbulb on the left.
What options do you have?
Did you install the package successfully?
yes but i used another version
Ah, that's why.
It is only available in version 7.0.0 and above
because i use .net core 6
and i can't use the latest version
how do i fix that
You can't?
bruh
wait what
you said i can't and than you said i can?
I asked if you couldn't
hence the questionmark
ah
i think i need to install .net core 7
thats the only solution
because .net core 6 can't install that version
There is a nugget package called CLI wrap use it to execute you ps script and get its output (read the docs for this option or watch nick chapssas video)
you serious?
Yep
omg
that would save my life maybe
https://youtu.be/Pt-0KM5SxmI
Here is the video where he will execute a cli command and read the output of the command directly from the C# program
Nick Chapsas
YouTube
Stop using the Process class for CLI interactions in .NET
Check out the ABP Framework here: https://bit.ly/3NGacLw
Check out my courses: https://nickchapsas.com
Become a Patreon and get source code access: https://www.patreon.com/nickchapsas
Hello everybody I'm Nick and in this video I will show you how you can control your machine's CLI in an elegant way in C#. .NET's built in Process class is a tot...
oh man if this works that will save my life
I hope it will wish you all the luck
it does not support .ps1 i think
I think you should put your ps script run command in the Cli command inside a c# app and get its stream via the pipe
huh
to run my script is just a
.\Script.ps1
But you're right i think this package doesn't support running ps scripts since they are not lunched like other scipts
uhu yes
But there should be some way to execute it as a cli
Like this command should work
powershell -command "your Command"
Or powershell -ExecutionPolicy Bypass -Command "your command"
https://www.youtube.com/watch?v=WrSZrGoPYyc and go to minute 20
IAmTimCorey
YouTube
Calling the Command Line in C# - Scripts, PowerShell, Automation, a...
The command line is an incredibly powerful tool to take advantage of in development. When you know how to use the command line, you can automate just about anything. This is why tools like Git, Docker, and even .NET are command-line first products. In this video, we are going to see how to build C# applications that can call command line applica...
i think its possible
Yep its possible I found the right command
You shoul use
powershell -file filename.ps1 in your cli command inside your C# code
just in my c# file?
you mean in the cliwrap?
i now got this
and get this message
so that is better
but i am still not getting the ouput
using CliWrap;
await Cli.Wrap("powershell").
WithArguments("-file C:\Users\okbb\Desktop\test.ps1").
WithStandardOutputPipe(PipeTarget.ToDelegate(Console.WriteLine)).
ExecuteAsync();
this worked for me and printed hello world from my script
i used the same as yours
but you send me a code and your file was written with ""
its supposed to be "\" right?
" \"
i mean
dubbel backslash
\
yep you have to use \
double \
ow ok
hahaha
but than it doesn"t work
first try to execute it like me to see if everything works
it asks me this when i try to run
to be honest idk why you getting it i don't have any experience with ASP i am even new to C# to be honest
ow ok hahaha
ahh wait
you are using a consoleapp
but i'm using ASP
or am i wrong?
yes am using console app
i will try it with a console app
maybe that will work?
the trick is to redirect the output of that command into a variable
and that idk how 😂
jep
if i can get that
that would be amazing
there is no different if i use console app or not
so i'm doing something wrong
the thing is
you are just doing a simple hello world
when i run my script
it is an array
okay i got something new after some research
Process p = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "powershell.exe";
startInfo.Arguments = "-file C:\Users\okbb\Desktop\test.ps1";
p.StartInfo = startInfo;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string output = p.StandardOutput.ReadToEnd();
Console.WriteLine("---------------");
Console.WriteLine(output);
Yeah but thats a process class?
how do i use that
can you send me your code?
i successfully stored the output in a string variable
i mean a screenshot of your code in your editor
are you serious?
crazy
use snipping tool of windows
it kinda worked
but i don't see otput
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
but i don't think storing this as array would be the right thing to do as this is a JSON response
ah yeah
but wait
what the diffrent between those two lines?
thx
Yoo FileName should recieve your command executer
or is that supposed to be powershell.exe?
ur
start.Arguments
is probably not treated like u expect itsince you are executing with powershell use powershell.exe as FileName
yes
ah ok
but when i use that
i don't get anyu output
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
this is the eroor
u probably have output in stderr, as ur arguments r treated like 7 arguments, not as 2
it stopped because of the space
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
damnn things escalated too fast
you mean double backdalsh
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
you maybe want to see my powershellf ile
bruih
thats wrong, it would be something like
start.Arguments = "--file \"C:\\some path\\script.ps1\"";
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
i can't follow anymore
so you mean that is it actually really easy?
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
yeah but you don't understand
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
that script is a twitter api script
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
that pulls information
i dk why you want to put this in array where the output is clearly a json
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
i used twiiter script for api yes
i mean
powerhsell script
you can basically create a class that represents your response and then deserialize it
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
i'm getting crazy
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
i hope he will send you the official twitter link 😂
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
the whole command would be
powershell.exe --file "C:\some path\script.ps1"
with being the --file "C:\some path\script.ps1"
the argument,
if u put the latter into a string literal in c#, u need to escape the backslashes and the the double quotes.
thus u end up with "--file \"C:\\some path\\script.ps1\""
as string literalwe had to do that so yaeh
executing a ps script from a supposed twitter script won't finish peacefully 😂
is it so weird to use powerhsell for twitter api?
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
ohh man i'm getting really crazy
huh
--file is supposed to be in the string
well, i didnt want to confuse further,
@"--file ""C:\some path\script.ps1""";
is shorter ofcyes @tebeco is right use the rest api and that's it but you can also go on with this problem as challenge but just use another sample script i don't trust the one you have
whats wtronnnggg?
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
-file not --file
yeah i can fix that
it is in the string, its the first argument, the double quotes within the string literal are to mark the whole path (including the whitespaces) as the second argument
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
naah, the folder name is
DevOps & Security
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
i made my own script
with my twitter development account
and than used this
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
it foking word
worked
thx everyone
because
that was some failed white space escaping to get the path inlcuding whitespaces as 2nd argument (https://discord.com/channels/143867839282020352/1041076192209539115/1041110135076032622)
EliasGPS#5554
Quoted by
<@!233139962277658624> from #Powershell result to c (click here)
React with ❌ to remove this embed.
last year i needed powerhsell to pull information from twitter with an api
so that why i used powerhsell
and now i need to make a new project
with c#
and if i can use tiwtter api and other stuff
than that will be ,ice
maybe one more question
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
but it worked now
so
is it possible to set this data in an array?
using CliWrap;
using CliWrap.Buffered;
using System.Diagnostics;
//Method 1 : using CLI Wrap lib
var result = await Cli.Wrap("powershell").
WithArguments("-file C:\\Users\\okbb\\Desktop\\test.ps1").
ExecuteBufferedAsync();
string outresult = result.StandardOutput.ToString();
Console.WriteLine("---------------");
Console.WriteLine(outresult);
//Method 2 : usig the built-in Process class
Process p = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "powershell.exe";
startInfo.Arguments = "-file C:\\Users\\okbb\\Desktop\\test.ps1";
p.StartInfo = startInfo;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string output = p.StandardOutput.ReadToEnd();
Console.WriteLine("---------------");
Console.WriteLine(output);
this can be done in two ways
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
tbh i would recommend starting to learn the c# basics first, u made quite simple mistakes.
and instead of ur script i would probably use a library like https://github.com/linvi/tweetinvi
GitHub
GitHub - linvi/tweetinvi: Tweetinvi, an intuitive Twitter C# librar...
Tweetinvi, an intuitive Twitter C# library for the REST and Stream API. It supports .NET, .NETCore, UAP (Xamarin)... - GitHub - linvi/tweetinvi: Tweetinvi, an intuitive Twitter C# library for the R...
yeah i'm a beginner c#
i alrady use that in my powerhsell script
it was a quit challenge i never redirected the stdout let alone running a ps script from C# thanks for it and i hope you got what you needed.
(u should also keep attention to stderr in such cases - or better avoid it all along ;p)
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
i think i'll take a deeper look into it tomorrow as it is 11.30 pm where i live i am looking like a zombie already
me too
but thx everyone
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
thx
np, assumed that already ;p
good luck on further progress, but i would really recommend just porting that script to c# and use it "natively" in ur program instead of in another process
i have no idea what you mean and how to start to it but i will try lol
well, instead of the powershell script which u invoke, simply write a method in ur program that does the job ;p
ahh
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
✅ This post has been marked as answered!