Can I query to PowerShell scripts from Power Query ?
Can I query to PowerShell scripts from Power Query ?
I want to use PowerShell result for Data Visualization in Excel.
Like importing from web, odata, hdinsight, etc,
I want to import result of PowerShell script.
PowerShell can do a lot of system management.
Regards,
Yoshihiro Kawabata
This is not possible today and is not something that's likely to be implemented. The combination of being able to easily share queries and being able to easily launch external scripts that can do anything supported by the current user's permissions is
something of a security nightmare.
Similar Messages
-
Can we execute a Powershell script from the Javascript?
Hi,
I have a certain requirement to add a Custom ribbon button in document library and there was a powershell script to be run for the selected item in the library.
I have struck with executing a Powershell script from the javascript function.
Can anyone please suggest me if this was achievable
Thanks, Swaroop VuppalaHi Swaroop,
To execute server side code in a custom ribbon button script, using application page is a common way to do this, besides, you can also use a page dialog, which is similar with application page but display as model dialog, another way is javascript
_dopostback and delegate control, the following article contains detailed information about this, please refer to it for more information:
Invoke server side code on SharePoint ribbon click:
http://sharepointnadeem.blogspot.in/2012/07/invoke-server-side-code-on-sharepoint.html
Thanks,
Qiao Wei
TechNet Community Support -
Run PowerShell script from C# writing to input pipe
Hello,
I am trying to run a PowerShell script from C# (I have no control over what's in the script). The script may have a prompt like "Press enter to continue". So my goal is:
1. Get text output from the script (easy, many examples available)
3. If output contains "Press enter to continue", write a blank line to the running script's pipe to make it finish its job and quit
4. If output does contain that prompt, just let it exit by itself without sending any input
Note that commands in this PS script also try to get at script's file path, so I can't read script from file and pass it as text. It has to be executed as a script so it knows where it's located.
I have done this with .exes and batch files before. All you do in that case is process.StandardInput.WriteLine() which "types" enter into the input stream of script you are trying to control. But this does not work with Power Shell. How do I do this?
I have tried using PS object model like so:
using (Pipeline pipeline = runspace.CreatePipeline())
Command command = new Command(scriptPS, true, true);
pipeline.Commands.Add(command);
pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
pipeline.Input.Write("\n");
Collection<PSObject> psresults = pipeline.Invoke(); //...
But I get an error because the script prompts:
"A command that prompts the user failed because the host program or the command type does not support user interaction. Try a host program that supports user interaction, such as the Windows PowerShell Console or Windows PowerShell ISE, and remove prompt-related
commands from command types that do not support user interaction, such as Windows PowerShell workflows."
I also tried using Process, and running PowerShell with -File switch to execute the script, then write to StandardInput with C#. I get no errors then, but the input is ignored and doesn't make it to PowerShell.
Please help!No man, what kind of answer is that? You should have left it unanswered rather than waste people's time like this. I already seen those links before I posted my question. They address the issue of specifying script parameters, but not
writing to the input pipe.
Fortunately I did figure this out by writing a custom script host for PowerShell. Anyone interested can read about this in detail on MSDN (fortunately simple material with samples you can copy paste as I did, so this solution takes little time to implement).
Implement PSHost interface. Nothing special here, just paste directly from MSDN sample and modify their SetShouldExit function definition to contain just a "return;". Here's the relevant link:
http://msdn.microsoft.com/en-us/library/windows/desktop/ee706559(v=vs.85).aspx
Implement PSHostUserInterface interface. This is the ticket to solving this problem
(see below). Here's the MSDN link:
http://msdn.microsoft.com/en-us/library/windows/desktop/ee706584(v=vs.85).aspx
Implement PSHostRawUserInterface. This may not be required (not sure) but I did anyway. Nearly a direct paste from MSDN:
http://msdn.microsoft.com/en-us/library/windows/desktop/ee706601(v=vs.85).aspx
So, there are two PSHostUserInterface function implementations that are of particular interest. First is Prompt (read header comment to see why):
/// <summary>
/// When script attempts to get user input, we override it and give it input programmatically,
/// by looking up within promptInput's dictionary<string,string> or lineInput array.
/// PromptInput dictionary is mapped by input prompt (for example, return "" in response to "Press ENTER to continue")
/// LineInput is a regular array, and each time the script wants to prompt for input we return the next line in that array;
/// this works much like piping inputs from a regular text file in DOS command line.
/// </summary>
/// <param name="caption">The caption or title of the prompt.</param>
/// <param name="message">The text of the prompt.</param>
/// <param name="descriptions">A collection of FieldDescription objects that
/// describe each field of the prompt.</param>
/// <returns>Throws a NotImplementedException exception.</returns>
public override Dictionary<string, PSObject> Prompt(string caption, string message, System.Collections.ObjectModel.Collection<FieldDescription> descriptions)
Dictionary<string, PSObject> ret = new Dictionary<string, PSObject>();
foreach (FieldDescription desc in descriptions)
if (this.promptInput.Count != 0)
ret[desc.Name] = new PSObject(this.promptInput[desc.Name] + "\r\n");
else if (this.lineInput != null && this.currentLineInput >= 0 && this.currentLineInput < this.lineInput.Length)
ret[desc.Name] = new PSObject(this.lineInput[this.currentLineInput++] + "\r\n");
else
if (desc.DefaultValue == null)
ret[desc.Name] = new PSObject("\r\n");
else
ret[desc.Name] = new PSObject(desc.DefaultValue);
return ret;
Next is PromptForChoice. Here I opted to always return the default choice, but you could rewrite it to read from somewhere to "simulate" reading from input pipe just like the function above:
public override int PromptForChoice(string caption, string message, System.Collections.ObjectModel.Collection<ChoiceDescription> choices, int defaultChoice)
return defaultChoice;
Last but not least, here's a ReadLine implementation (again read header comment):
/// <summary>
/// If the LineInput is set, "read" the next line from line input string array, incrementing line pointer/// </summary>
/// <returns>The characters that are entered by the user.</returns>
public override string ReadLine()
if (this.lineInput != null && this.currentLineInput >= 0 && this.currentLineInput < this.lineInput.Length)
return this.lineInput[this.currentLineInput++];
else
return Console.ReadLine();
Both are exposed as properties:
/// <summary>
/// Gets or sets the input pipe override
/// </summary>
public string Input
get
return string.Join("\n", this.lineInput);
set
if (value != null)
this.lineInput = value.Split('\n');
this.currentLineInput = 0;
else
this.lineInput = null;
/// <summary>
/// Gets or sets input pipe override for named prompts
/// </summary>
public Dictionary<string, string> PromptInput
get
return this.promptInput;
set
this.promptInput = value;
And finally, here's how the whole shebang is used:
/// <summary>
/// Runs a powershell script, with input pipe arguments
/// </summary>
/// <param name="script">Path of the script to execute, or script text</param>
/// <param name="inline">Whether or not to execute script text directly, or execute script from path</param>
/// <param name="unrestricted">Whether or not to set unrestricted execution policy</param>
/// <param name="parameters">Parameters to pass to the script command line</param>
/// <param name="inputOverride">Input to pass into the script's input pipe</param>
/// <param name="inputOverrideName">Input to pass into the script's input pipe, to each prompt by label</param>
/// <returns>Output lines</returns>
public static string PowerShell(string script, bool inline, bool unrestricted = false, Dictionary<string, string> parameters = null, string inputOverride = null, Dictionary<string, string> inputOverrideByName = null)
string output = null;
ScriptHost host = new ScriptHost();
(host.UI as ScriptHostUserInterface).Input = inputOverride;
(host.UI as ScriptHostUserInterface).PromptInput = inputOverrideByName;
using (Runspace runspace = RunspaceFactory.CreateRunspace(host))
runspace.Open();
if (unrestricted)
RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace);
runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
using (Pipeline pipeline = runspace.CreatePipeline())
if (inline)
pipeline.Commands.AddScript(script);
else
Command command = new Command(script, true, true);
foreach (KeyValuePair<string, string> param in parameters)
command.Parameters.Add(param.Key, param.Value);
pipeline.Commands.Add(command);
pipeline.Commands.Add("Out-String");
pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
Collection<PSObject> psresults = pipeline.Invoke();
var sb = new StringBuilder();
foreach (PSObject obj in psresults)
sb.AppendLine(obj.ToString());
output = sb.ToString();
pipeline.Dispose();
runspace.Close();
return (host.UI as ScriptHostUserInterface).Output + "\r\n" + output;
As you can see, I also did some magic with the .Output property. That just accumulates lines of text output by the script in every WriteXXX function implemented in your custom PSHostUserInterface. The end result of all this, is that if you have a script
that has prompts, choices or reads from standard input, you can execute the script within the context of your custom script host written as above, to control precisely what strings are passed to it in response to prompts.
-
Does Forefront Endpoint Protection 2010 block powershell scripts from running?
Hi all,
I have a task that runs a Powershell script on a set schedule on a particular machine. It has failed to run and I thought 1 of the potential reasons would be that FEP 2010 blocks the Powershell script from being run. Does FEP 2010 do that? If so, where can I find the setting to allow Powershell scripts (or VB scripts or Java scripts) to be run by my task?
Thanks for your help in advance.
Howard Lee - MicrosoftIf the script detect as malicious , FEP will block it, otherwise it won't block normal and safe PowerShell scripts. You may take a look at event viewer and see whether it being blocked or detect as malicious code by FEP or not.
-
Execute a powershell script from a windows store apps
Hello Everybody !
I'd like to launch a powershell script from a windows store apps.
In fact the purpose is install a windows store apps from an other windows store apps.
Any ideas?
ThanksIf it's a sideloaded LOB application, you can do this using a brokered component:
http://blogs.msdn.com/b/wsdevsol/archive/2014/04/14/cheat-sheet-for-using-brokered-windows-runtime-components-for-side-loaded-windows-store-apps.aspx
Matt Small - Microsoft Escalation Engineer - Forum Moderator
If my reply answers your question, please mark this post as answered.
NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined
objects and unknown namespaces. -
Run Powershell script from Scheduled Task as "NT Authority \ SYSTEM"
Hello, dear Colleagues.
Cannot make Powershell script from Scheduled Task as "NT Authority \ System"
Action: Start a program -
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command "C:\script.ps1"
The matter is that script is working, moreover if to run Task with Domain Account it works too.
Checked Run with highest privileges, changed "Configure for" field, tried different arguments (-noprofile, -noexit, -executionpolicy bypass, -command, -file,") - no luck.
Didn't you try to make it work with SYSTEM account?
Thanks.Hi fapq,
Try this link task schedulers
Note
To identify tasks that run with system permissions, use a verbose query (/query/v). In a verbose query display of a system-run task, the Run As User field has a value of NT AUTHORITY\SYSTEM and
the Logon Mode field has a value of Background only.
Naveen Basati -
Can any one tell me how can i call a shell script from pl/sql
i like to call shell script from pl/sql procedure.
can any one suggest how can i do thisHave you not mastered in asking the same kind of question ?
First do write a script...
no one will spoon feed you.
How can i call a shell script from procedure
How to call Shell Script from pl/sql block
-Sk -
How can i call a shell script from procedure
I have a shell script.now i am i a situation to call that shell script from one of my procedures and need to get a value from that script.
can u suggest me that how can a call the shell script from pl/sql?Is the same question you asked here
How to call Shell Script from pl/sql block
-SK -
Execute powershell script from ssis?
Hi,
I was trying to use the execute process task to kick off a powershell script. However, nothing happens when I run in debug (the component turns yellow and stays yellow). Any idea if what I am trying to do is possible and the proper way to configure
it?
btw, I am using powershell for the remoting capabilites. I need to execute a bat file on a remote server which runs a process in a legacy program.
Update: When I name the ps1 script file in the executable window, it opens it in notepad. This would be like the default if you double clicked the file.
MarkTo run a PowerShell Script from SSIS package. Add a "Execute Process Task" in SSIS and use the following command text.
This works just great, plus the "-ExecutionPolicy ByPass" switch will take care of any server script policies.
C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe
-ExecutionPolicy ByPass -command ". 'L:\Powershell_Script\Script1.ps1' 'param1' 'param2'"
Regards
Deepak -
Calling powershell script from a batch file
Hello All,
I have a batch script that calls a powershell script. Before calling the script I set the execution policy to unrestricted, but when it gets to the line that calls the batch script i still get the confirmation in the command window: "Do you want to
perform this operation" I then have to press Y for the PS script to run and then my batch script finishes.
Does anyone know the setting I need to change in order to suppress the confirmation?
Note: this is Windows 8, see code below
set THIS_DIR=%~dp0
powershell Set-ExecutionPolicy unrestricted
powershell %THIS_DIR%MyScript.ps1 "param1"I may sound like a jerk but you really want to look at PowerShell.exe /?
PowerShell[.exe] [-PSConsoleFile <file> | -Version <version>]
[-NoLogo] [-NoExit] [-Sta] [-Mta] [-NoProfile] [-NonInteractive]
[-InputFormat {Text | XML}] [-OutputFormat {Text | XML}]
[-WindowStyle <style>] [-EncodedCommand <Base64EncodedCommand>]
[-File <filePath> <args>] [-ExecutionPolicy <ExecutionPolicy>]
[-Command { - | <script-block> [-args <arg-array>]
| <string> [<CommandParameters>] } ]
PowerShell[.exe] -Help | -? | /?
-PSConsoleFile
Loads the specified Windows PowerShell console file. To create a console
file, use Export-Console in Windows PowerShell.
-Version
Starts the specified version of Windows PowerShell.
Enter a version number with the parameter, such as "-version 2.0".
-NoLogo
Hides the copyright banner at startup.
-NoExit
Does not exit after running startup commands.
-Sta
Starts the shell using a single-threaded apartment.
Single-threaded apartment (STA) is the default.
-Mta
Start the shell using a multithreaded apartment.
-NoProfile
Does not load the Windows PowerShell profile.
-NonInteractive
Does not present an interactive prompt to the user.
-InputFormat
Describes the format of data sent to Windows PowerShell. Valid values are
"Text" (text strings) or "XML" (serialized CLIXML format).
-OutputFormat
Determines how output from Windows PowerShell is formatted. Valid values
are "Text" (text strings) or "XML" (serialized CLIXML format).
-WindowStyle
Sets the window style to Normal, Minimized, Maximized or Hidden.
-EncodedCommand
Accepts a base-64-encoded string version of a command. Use this parameter
to submit commands to Windows PowerShell that require complex quotation
marks or curly braces.
-File
Runs the specified script in the local scope ("dot-sourced"), so that the
functions and variables that the script creates are available in the
current session. Enter the script file path and any parameters.
File must be the last parameter in the command, because all characters
typed after the File parameter name are interpreted
as the script file path followed by the script parameters.
-ExecutionPolicy
Sets the default execution policy for the current session and saves it
in the $env:PSExecutionPolicyPreference environment variable.
This parameter does not change the Windows PowerShell execution policy
that is set in the registry.
-Command
Executes the specified commands (and any parameters) as though they were
typed at the Windows PowerShell command prompt, and then exits, unless
NoExit is specified. The value of Command can be "-", a string. or a
script block.
If the value of Command is "-", the command text is read from standard
input.
If the value of Command is a script block, the script block must be enclosed
in braces ({}). You can specify a script block only when running PowerShell.exe
in Windows PowerShell. The results of the script block are returned to the
parent shell as deserialized XML objects, not live objects.
If the value of Command is a string, Command must be the last parameter
in the command , because any characters typed after the command are
interpreted as the command arguments.
To write a string that runs a Windows PowerShell command, use the format:
"& {<command>}"
where the quotation marks indicate a string and the invoke operator (&)
causes the command to be executed.
-Help, -?, /?
Shows this message. If you are typing a PowerShell.exe command in Windows
PowerShell, prepend the command parameters with a hyphen (-), not a forward
slash (/). You can use either a hyphen or forward slash in Cmd.exe.
Hope that helps! Jason -
Executing powershell script from remote computer using RSAT
Hi.
I want to execute powershell script on AD server from remote computer (in the same domain). I installed and tested RSAT - it is working fine. But i cant execute PS from c# code.
ps.Commands.AddCommand("Import-Module").AddArgument("ActiveDirectory");
ps.Invoke();
ps.Commands.AddCommand("Get-ADOrganizationalUnit -Filter 'Name -like \"*\"'");
var res = ps.Invoke();
And i get exception:
An unhandled exception of type 'System.Management.Automation.CommandNotFoundException' occurred in System.Management.Automation.dll
Additional information: The term 'Get-SBNamespace' 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.Hi
CapitanPlanet
For the
CommandNotFoundException, it means the command cannot be found.
On the other hand, your issue is about the PowerShell, if you still have the issue, I suggest that you should post it in the
PowerShell forum for efficient response.
Here are some useful information, please check
Powershell
commands from C# not working (System.Management.Automation.CommandNotFoundException)
Powershell, Service Bus For Windows Server Programmatically: Command found, module could not be loaded
https://msdn.microsoft.com/en-us/library/dn282152.aspx
Best regards,
Kristin
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
Calling Powershell Script from a vRA Blueprint
Hi all,
Need your help! I have a use case where I need to provide user a dropdown list in the Blueprint so that they can select a project number. The project numbers are dynamic and can be exported to a .csv file and I can then write a PS script to capture that. I’m just not sure on how to present that data in the vRA Blueprint as the list is always changing? Is there a way to create a custom Control Type in Property Dictionary say “DropDownListFromPowerShell” OR any other solution to address this use case? Any advice will be greatly appreciated.
Thank you,
Tonyyou cant do that in IaaS. you would need to use ASD to do those custom server side look ups in your forms.
-
Run PowerShell Script from a Event Receiver
Hi,
Just looking around on the net for some documentation for running a PowerShell script via an Event Receiver. We want to be able to make changes to the script and not change anything in the ER.
Sadly using a workflow isn't an option here.
Looking for websites that give some examples really, or if anyone has done this.
Regards
If this is helpful please mark it so. Also if this solved your problem mark as answer.Hi TemPart:
string cmdArg = “C:\\Scripts\\test.ps1″;
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(cmdArg);
Collection [PSObject] results = pipeline.Invoke(); // please Update [] bracket with less then and greater then bracket
runspace.Close();
Had to modify this slightly:
string cmdArg = “Powershell.exe -file C:\\Scripts\\test.ps1″;
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(cmdArg);
Collection [PSObject] results = pipeline.Invoke(); // please Update [] bracket with less then and greater then bracket
runspace.Close();
If this is helpful please mark it so. Also if this solved your problem mark as answer. -
Can i call unix shell script from B2B callout.
Hi,
We had a requirement to invoke a unix shell script from B2B callout implemented class. Here is the code in implementation class:
public void execute(CalloutContext context,List input,List output)
throws CalloutDomainException, CalloutSystemException {
try {
CalloutMessage cmIn = (CalloutMessage)input.get(0);
FileOutputStream fos = null;
String inputFile = "/home/orasoad/digitalsign/input/test.txt";
String outputFile = "/home/orasoad/digitalsign/output/test.txt.gpg";
File outFile = new File(inputFile);
String str =cmIn.getBodyAsString();
fos = new FileOutputStream(outFile);
Writer out = new OutputStreamWriter(fos);
out.write(str);
out.close();
String shellFile = "/home/orasoad/digitalsign/dg.sh";
String cmd[] = new String[] { shellFile, inputFile, outputFile };
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(cmd);
int i = pr.waitFor();
BufferedReader br = new BufferedReader(new InputStreamReader(pr.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
CalloutMessage cmOut = new CalloutMessage(sb.toString());
output.add(cmOut);
} catch (Exception e) {
throw new CalloutDomainException(e);
We were able to execute the unix shell script from standalone java class with same code. But some how it is not working as expected while invoking the B2B java callout.
Is it possible to invoke unix shell script from B2B callout?
Please give inputs.
Regards,Though it's not a good idea to invoke shell scripts from java callout but technically it will work.
But some how it is not working as expected while invoking the B2B java callout.What is not working as expected? Any error in the log (server-diagnostic.log or server.out)?
Regards,
Anuj -
Running a function from a powershell script from the command line
Rather than creating several scripts each with one function, I have one script with has several functions.... I would like to call the script and select the function i want to use from the command line.
so far, if i change directory to that of the script i can call the function by doing this:
cd c:\myscripts
. .\mytestscript.ps1; myfunction
this works fine.... i have also tried, what I would like to achieve is calling it like this
c:\myscripts\mytestscript.ps1; myfunction
however, i am trying to run this as part of an MDT task sequence, my command line looks like this and using the ; myfunction at the end doesn't work.
powershell.exe -ExecutionPolicy Bypass %SCRIPTROOT%\CustomScripts\mytestscript.ps1; myfunction
how can i adapt my command line so that it will successfully call the function within my script?
thanks
SteveRename the file from ps1 to psm1 and create a powershell module that contain multiple functions. A module will autoload like the built-in modules.
Placement of the psm1 file is important for Powershell to find and autoload it.
The file name and folder name must be the same, for example MyModule.psm1 should be in the folder:
user\documents\windowspowershell\modules\mymodule
Windows PowerShell Modules
http://msdn.microsoft.com/en-us/library/dd878324(v=vs.85).aspx
PS C:\> get-childItem env:PSModulePath
Name Value
PSModulePath C:\Users\User\Documents\WindowsPowerShell\Modules;C:\Windows\system32\WindowsPowerShell\v1.0\Modules\
Maybe you are looking for
-
How to Install "Adobe Reader 11" in "Silent Mode"?
Hi, how can i install adobe reader (AdbeRdr11000_de_DE.exe) in Silent (quiet) mode? I already tried following parameters: AdbeRdr11000_de_DE.exe /q /aAll /l /msi /norestart ALLUSERS=1 EULA_ACCEPT=YES Unfortunatly without success. Best Regards Marco
-
Need help in security model !!
Hi All, I am new to the security api-s provided by java. Can anyone tell me how I can define policy and security context in java. Is there any api for that?? Let me tell u , what exactly I need. I want to implement Role Based Access Control in my app
-
How do i get rid of a double e ine the top left hand corner of my iphone
how do i get rid of the double e in the top left hand corner of my iphone
-
JUST BOUGHT A PDF TO WORD DOWNLOAD BUT IT IS NOT WORKING?
-
Error when moving an object around the art board (Video)
So I have a grouped object which I was about to move into place when I started getting this odd error, including a error message. Here is a video of the issue: http://youtu.be/8o1E_oF5D0I Error message: Can't move the objects. The requested transform