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 Vuppala

Hi 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

Similar Messages

  • 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.

  • 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?
    Thanks

    If 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.

  • 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
    Steve

    Rename 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\

  • Can we execute an idoc script from a custom service?

    Is it possible to execute an idoc script while executing a custom service?
    -Pratap

    There are several ways to execute iDocScript from Java, but in this quick example we will use a PageMerger object. There are several ways to get ahold of a PageMerger object. If you are executing in a context where a service object is readily available you may be able to get a PageMerger object reference with code like this:
    PageMerger pm = m_service.m_pageMerger;
    If that doesn't work for you I would try something like:
    PageMerger pm = new PageMerger(databinder, executioncontext);
    Now that you have your merger object you can execute all kinds of iDocScript code, an example of which might be:
    pm.evaluateScript("<$lc(\"wwMyString\")$>");

  • Can I run a shell script from the services menu?, part II

    Remember this?
    It is now possible.

    Doesn't look like there is a direct way to do it.
    The services are all Bundles, which is easy
    enough to fake -- just copy one from /Library/Services
    to ~/Services and modify the plist. Put your shell
    script in Contents/MacOS/ and identify it in the
    plist under CFBundleExecutable and hope for the
    best
    Where it gets sticky is CFBundlePackageType (APPL
    for Application, FMWK for FrameWork, BNDL for
    'loadable bundle', whatever that is] and NSServices.
    CFBundlePackageType should pose no problem if Services
    use the OS loader and handles file magic [and '#!' of
    course].
    NSServices specifies a named port that the app
    listens on, the data type it receives, and so forth.
    This looks a bit harder to fake. I'd bet Applescript
    has the functionality, and there may be some
    command-line hooks to backend that, or it may be
    possible to netcat your way through it.
    But it doesn't look trivial
    Property List Key Reference
    Anyways, tried it with a quick script that echoes to a
    file, and haven't figured out how to refresh the
    Services menu to get it to appear. Probably have
    to NetInfo it or something ridiculous; doesn't appear
    to watch the FS.
    [ Edited by Apple Discussions Moderator; href URL ]

  • Can I run a shell script from the Services menu?

    This would be kind of cool.
    Is there a simple way to do this?

    Doesn't look like there is a direct way to do it.
    The services are all Bundles, which is easy
    enough to fake -- just copy one from /Library/Services
    to ~/Services and modify the plist. Put your shell
    script in Contents/MacOS/ and identify it in the
    plist under CFBundleExecutable and hope for the
    best
    Where it gets sticky is CFBundlePackageType (APPL
    for Application, FMWK for FrameWork, BNDL for
    'loadable bundle', whatever that is] and NSServices.
    CFBundlePackageType should pose no problem if Services
    use the OS loader and handles file magic [and '#!' of
    course].
    NSServices specifies a named port that the app
    listens on, the data type it receives, and so forth.
    This looks a bit harder to fake. I'd bet Applescript
    has the functionality, and there may be some
    command-line hooks to backend that, or it may be
    possible to netcat your way through it.
    But it doesn't look trivial
    Property List Key Reference
    Anyways, tried it with a quick script that echoes to a
    file, and haven't figured out how to refresh the
    Services menu to get it to appear. Probably have
    to NetInfo it or something ridiculous; doesn't appear
    to watch the FS.
    [ Edited by Apple Discussions Moderator; href URL ]

  • Executing a powershell script for checking duplicate users while creating a AD user throug ADUC console.

    Hi,
    I have a text file in which some SamAccountNames are present.I need to check the file while creating a new users through ADUC console.If a username that is going to create through ADUC console is present in the file, then it should prompt a message
    that the user is already present in the text file.
    Is there any possibility of contacting the powershell script from the ADUC console.If so, then while creating a new user through ADUC console, what is the proceedure for executing that powershell script.
    please provide me the approriate solutions.
    Thanks
    Prasanthi k

    Run the below Powershell Script for users are exist or not in AD. Later you can create the users.
    #Find Users exist in AD or Not?
    #Biswajit Biswas
    $users = get-content c:\users.txt
    foreach ($user in $users) {
    $User = Get-ADUser -Filter {(samaccountname -eq $user)}
    If ($user -eq $Null) {"User does not exist in AD ($user)" }
    Else {"User found in AD ($user)"}
    Active Directory Users attributes-Powershell
    http://gallery.technet.microsoft.com/scriptcenter/Getting-Users-ALL-7417b71d
    Regards~Biswajit
    Disclaimer: This posting is provided & with no warranties or guarantees and confers no rights.
    MCP 2003,MCSA 2003, MCSA:M 2003, CCNA, MCTS, Enterprise Admin
    MY BLOG
    Domain Controllers inventory-Quest Powershell
    Generate Report for Bulk Servers-LastBootUpTime,SerialNumber,InstallDate
    Generate a Report for installed Hotfix for Bulk Servers

  • 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.
    Mark

    To 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

  • Context Menu to Execute a powershell script within selected directory.

    Hi,
    I'm trying to run a powershell script from a context menu, I've been able to create a context menu, however, when I attempt to run the script it will only run at the default location. What I'd like to do is right-click a folder then click "Do Script"
    and have it run the script with the location set to the directory I right clicked.
    So for clarities sake, if I right click C:\example then when the script runs it should recognize .\ as C:\example
    This is what I currently have in my registry entry. However it's shouting about how there is no parameter for Set-Location that matches -File, I can see that it's taking the Set-Location command, then it's trying to see if -File will is a perameter for it,
    but I' trying to use -File for the powershell command. Anyone have any ideas for that?
    PowerShell -Command "Set-Location -LiteralPath '%V'" -File C:\script\Test.ps1
    Any ideas? I'm wondering if there is something in Powershell like how Bash has something like this to do commands inline
    $ > Command -parameter <arg> && Command -parameter <arg>

    To setup a script to launch in a men from within a context menu you must create a the following.
    Create the following keys:
    HKEY_CLASSES_ROOT\Directory\Shell\<Script Name>
    HKEY_CLASSES_ROOT\Directory\Shell\<Script Name>\command
    Within <Script Name> change the (Default) value to the words you want to have as a context menu example, "Launch Script Here".
    Within the command Key change the (Default) value to
    PowerShell.exe -File "C:\Script_location\script_name.ps1" "%v"
    PowerShell.exe is executed with the -File flag followed by the scripts exact location and "%v " is a variable pointing to the location that was selected.

  • Cannot execute an AE script from Python 2.7

    I'm trying to execute an AE script from Python and it doesn't appear that the script argument is passing correctly, or the the script won't run for some reason. I'm using Windows 7 with Python 2.7.
    If I use cmd.exe or powershell and try
    afterfx -r D:\pipeline\tests\tactic_ae\hello.jsx
    I get my "hello world" alert in the AE UI.
    However, if I try executing in Python:
    subprocess.call(["afterfx","-r","D:\pipeline\tests\tactic_ae\hello.jsx"])
    The AE UI takes focus but no alert appears. The really strange part is if I try to do something invalid like remove the -r flag:
    subprocess.call(["afterfx","D:\pipeline\tests\tactic_ae\hello.jsx"])
    I get an AE error:
    After Error Can't import file "hello.jsx": unsupported filetype or extension
    It does seem like Python is passing the arguments or the error above wouldn't be generated, but why won't the script run and display the alert? Thanks!

    I've personally been unsuccessful in trying to attempt this, but I am also not too command line savvy. There may be a creative workaround out there somewhere though.

  • 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.
     

  • SQL Server upgradation Issue : 2012 to 2014. A job step received an error at line 1 in a PowerShell script. The corresponding line is 'set-executionpolicy RemoteSigned -scope process -Force'. Correct the script and reschedule the job.

    Message
    Executed as user: CORPTST\XXXXX. A job step received an error at line 1 in a PowerShell script. The corresponding line is 'set-executionpolicy RemoteSigned -scope process -Force'. Correct the script and reschedule the job. The error information returned
    by PowerShell is: 'Security error.  '.  Process Exit Code -1.  The step failed.
    I receive this error during the sql server job 'syspolicy_purge_history' execution  when sql server got upgraded form SQL Server 2008 to 2014.

    Hi Vishnu,
    According to the error message, it also occurs in SQL Server 2012.  Here is a feedback about the error in the link below.
    https://connect.microsoft.com/SQLServer/feedback/details/754063/sql-server-2012-syspolicy-purge-history-job-step-3-fails-with-security-error
    To resolve this issue, please change the value of the following registry key from ‘RemoteSigned’ to ‘Unrestricted’. For more details, you can review this similar
    blog.
    HKLM\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps120\ExecutionPolicy
    Thanks,
    Lydia Zhang

  • Executing a shell script from a jsp page

    Hi,
    I'm facing a problem while executing a shell script from a jsp page.
    I'm using Runtime.exec() function.
    It's working fine for single statement scripts.But if the script consists of any database processing and some other processing statements,it's not returning the correct exit status of the process.
    Will u please help me in this.
    If there is any other ways to execute a shell script from a jsp page other than Runtime.exec() like RMI etc,.If so let me know.
    Thanks in advance.

    Hello,
    It's hard to help you but what you can do is listening to the outputs of your script, you should read the output stream and error stream and send them to the default console.
    Check this excellent article : http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4
    Best regards,
    Olivier.

  • 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 - Microsoft

    If 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.

Maybe you are looking for