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\

Similar Messages

  • 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

  • Sending scripts to the command line

    Is there a function I can use to send a script to the command line and capture what it sends to the standard output? For example, if I'm writing a java program that I want to execute adder.exe and store the output of adder.exe (which is just sent to standard output) in an array, how would I go about doing that?

    You might check out the methods in java.lang.Process.

  • Dumb question- how do I get to the command line without X running?

    Hi,
    As per the title please... I need to rerun Xorg -configure, but cannot for the life of me figure out how to shut down X and get to a command line
    Thanks

    Bes wrote:
    Ctl alt and backspace just takes me out to the login screen.. from there I can't get to the terminal without X running.
    Ctrl Alt F5 gets me to the command line, but I can't kill the X server
    Thanks though
    so with ctrl+alt+f5 you're at the console
    log in if you need to, then
    ps ax | grep gdm
    4441 ? Ss 0:00 /usr/sbin/gdm-binary
    4442 ? S 0:00 /usr/sbin/gdm-binary
    4444 tty7 SLs+ 3:38 /usr/bin/Xorg :0 -audit 0 -auth /var/lib/gdm/:0.Xauth
    6633 pts/0 S+ 0:00 grep gdm
    kill 4444
    the above example assumes gdm is your login manager so substitute whatever you're using, and you can kill the other instances of gdm (in my example processes 4441 and 4442 but don't waste your time on the grep process 6633
    now redo your X config
    (actually you could run this from a terminal from within X and it should have the same effect of dropping you back to console
    Last edited by tj (2008-04-20 09:36:15)

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

  • How to run .cmd file from a Powershell script

    Hi,
    I would like to know how I run commands from a powershell script? how to use the invoke-command?
    This powershell script doesnt work for me
    Invoke-Command C:\setup.cmd -ArgumentList install-setupforced

    To run a batch file from powershell, just type its name with arguments. I'd recommend explicitly including the .CMD file type and, if it is located in the current folder, powershell rules require you to explicitly say so, i.e.:
       ./mybatch.cmd inputfile.txt outputfile.txt
    To run a single cmd.exe command, just prefix it with cmd.exe /c as Mike says:
        cmd.exe /c color 48
    to run a series of "&"- separated cmd.exe commands you need to enclose the complete command string in double quotes:
        cmd.exe /c "color 37 & dir"
    Beyond that it can get complicated due to various characters that are special to powershell and those special to cmd.exe. If you need to run a series of cmd.exe commands, your best short term bet is to put them in a batch file. The best long-term bet is
    to move more completely to the powershell way of doing things...
    Al Dunbar -- remember to 'mark or propose as answer' or 'vote as helpful' as appropriate.

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

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

  • 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

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

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

  • Is there a way to switch between workspaces in Spaces from the command line?  I want to write a script to set up certain applications in certain workspaces (without having to do it manually each time)...

    Is there a way to switch between workspaces in Spaces from the comnand line?  I use several workspaces from Spaces, each workspace having a certain number of fixed applications running.  Rather than set all this up each time I log on, I'd like to write a script from the command line (I use gawk) to automate this. Currently I have a gawk script that, given a directory, opens a few xterms whose working directory is the given directory, and opens "preview" applied to a certain file in that directory.  However, at present I have to manually move an xterm through each workspace and run my gawk script in each workspace (applied to each directory that I'm working on).
    There must be a better way...

    Addendum: Can this be done via:   open -a Spaces --args xxx  , where xxx is some set of arguments (or something like this)?

  • Run javascript (not in a jsx file) from the command line extendscript

    Hi all,
    I was wondering if anyone knew how to run javascript from the command line in Extendscript (meaning Extendscript would be the target application). I know about the -run command line flag in which allows you to run a .jsx script from the command line but what I'm looking for similar syntax to run a script directly without needing to put it in a file. For example I have tried (obviously unsuccessfully):
    C:\Program Files (x86)\Adobe\Adobe ExtendScript Toolkit CC\ExtendScript Toolkit.exe -run "alert('Hello World');"
    Thanks!

    You might be looking for something like this: javascript - Is it possible to execute JSX scripts from outside ExtendScript? - Stack Overflow
    Although that one is about executing JSX files, the solutions given (Applescript as well as COM/VBScript) can be adapted to simply run a javascript code snippet rather than JSX file because the solutions simply call the Adobe app's Applescript/COM API to "execute javascript" (actually execute ExtendScript technically), and in the solution, they using includes to pull in the JSX file. You'd simply replace the include with actual javascript code snippet inserted in.
    Though this would then require you to run a VBScript, Applescript, or other script (that calls the COM/Applescript API) rather than the ESTK command line option.

  • How to execute SAPGUI script from the command line?

    I have created a script and would like to execute it from the command line. There must be some flag that goes with SAPGUI.EXE. Any help appreciated.
    Thanks,
    Jeff

    Hi Jeff,
    the best way to do this is to run the script using the Windows Script Host, for example like this:
    cscript myscript.vbs
    This will execute the script which in turn can access SAP GUI. You may however have to make sure the script attaches to the correct session.
    Best regards,
    Christian

Maybe you are looking for

  • XML Serialization Error- While testing BAPI turned Web service

    I have a requirement to create sales order in SAP R/3 from an e-commerce site. I went through many forums suggesting "exposing FMs into Web Service". I wrapped BAPI_SALESORDER_CREATEFROMDAT2 and BAPI_TRANSACTION_COMMIT into one FM and exposed as Web

  • Change history of the customer master

    Hi Gurus, need help. We have a customer requirement where a customer was assigned to multiple sales areas before, but the customer assignment to one of the sales areas is deleted. Where is the place where we can see the relavant change history for th

  • Undeliverable mail question

    hi, What does this dsn mean? And could it be spam? the subject is "Undeliverable mail" Message body: Failed to deliver to '[email protected]' SMTP module(domain yyyyy.com) reports: yyyyy.com: no response Two attachments came along with the message. O

  • Regarding the query about BI tools

    hi, I'm going to learn BI tool.could u please suggest me about BI tools and its scope for next 2 years in marketing level. thanks

  • Error in Objects implementation?

    Please help us! Simple example: CREATE TYPE PARENT_T AS OBJECT( ID NUMBER(1) )NOT FINAL; CREATE TYPE CHAILD_1_T UNDER PARENT_T ( NAME VARCHAR2(20) CREATE TYPE CHAILD_2_T UNDER PARENT_T ( NAME CHAR(4) CREATE TYPE CHAILD_3_T UNDER PARENT_T ( NUMB NUMBE