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

Similar Messages

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

  • Run Powershell Script from Server

    I am new to MDT so please forgive me.  I am looking for a way for the MDT server to run a script locally after a server has been deployed.  I saw you can do something similar where you use remoting in the task sequence.  That is not
    allowed or enabled in my environment.  Is there any way for the MDT server to know it is done then it runs a script?

    The unattend file has several locations that scripts could be run from, either in the specialize pass or oobeSystem pass. 
    http://technet.microsoft.com/en-us/library/cc748874(v=ws.10).aspx -- this also gives you some demos on how to create your own unattend, though most basic settings are handled by
    MDT.
    You could also look into utilizing the run and runonce keys -
    http://msdn.microsoft.com/en-us/library/aa376977%28v=vs.85%29.aspx

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

  • Run powershell script from context menu

    Hi guys!
    I do not know if what I'm going to
    ask you is achievable.
    This is what I want:
    when I click with the right mouse button
    a file, possibly with certain extensions,
    the context menu appears, and
    here I would to create an
    object that can run the script that I have created
    and assign as an argument the selected file.
    It would also be necessary that such an object is
    similar to the"send to" button.
    Browsing the net I had found the
    script to create such an object, however,
    I have no idea on how to implement it
    and then how to run my script.
    Thanks

    Hi jrv!
    Initially, I will try to follow your suggestion but I'd prefer to use some automation, possibly related to powershell as required, because i must do this thing on many computers.
    Thanks
    A
    Y((ou would do that with Group Policy as it is just a registry update.
    ¯\_(ツ)_/¯

  • Issue with running powershell script in pssessions

    Hi Everyone,
    I am trying to run powershell script from remote machine using below commands
    C:\Users\user>"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
    -command "$s= New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri
    http://Exchservername/PowerShell/ -Authentication Kerberos ; Import-PSsession $s; "C:\Failback.ps1"
    and Below is the failback.ps1.
    $mbxs = Get-MailboxDatabase | Sort Name
    ForEach($mbx in $mbxs)
    $MBdb=$mbx.Name $ServerHosting=$mbx.Server.Name
    if($mbx.activationPreference.value -eq 1)
    If ($ServerHosting -ne $ActivationPreference.Key.Name) 
    Move-ActiveMailboxDatabase $MBdb -ActivateOnServer $ActivationPreference.Key.Name -confirm:$False 
    Below is what i am getting.

    What is your question?  Are you pointing out the yellow text?  This is normal, and appears every time EMS is opened.
    I should also point out that Microsoft provides a script to re-balance databases, if that's what you're trying to accomplish:
    You can use the RedistributeActiveDatabases.ps1 script to balance the active mailbox databases copies across a DAG. This script moves databases between their copies in an attempt to have an equal number of mounted databases on each server in DAG. If required,
    the script also attempts to balance active databases across sites.
    https://technet.microsoft.com/en-us/library/dd335158(v=exchg.141).aspx
    Mike Crowley | MVP
    My Blog --
    Baseline Technologies

  • Opening Excel Workbook Fails when run from Scheduled Task on Windows Server 2008 Rw

    Hi,
    I have a little vbs script that instantiates the Excel.Application object and then opens a work book to perform some tasks on it. The script runs fine when run from the command line. When I attempt to run it as a scheduled task (it is supposed to update
    data that is pulled from a SQL Server at regular intervals), it fails with the following error:
    Microsoft Office Excel cannot access the file 'c:\test\SampleWorkbook.xlsm'. There are several possible reasons: .....
    The file does exist. The path reported in the error is correct. The account under which the task is running is the same account I use to run it from the command line. User Account Control is not enabled, and the task is set up to run with highest privileges.
    When I run the same script through the Task Scheduler from a Windows Server 2003 machine, it works without issue.
    I was just wondering if somebody on this forum has run into a similar issue in connection with Windows Server 2008 R2 and figured out what the magic trick is to make it work. I'm sure it is rights related, but I haven't quite figured out what which rights
    are missing.
    Thanks in advance for any advice you may have.

    This is truly killing me ... trying to get it working on Windows Server 2012 without success.
    I desperately need to automate running Excel macros in a "headless" environment, that is non-interactive, non-GUI, etc.
    I can get it to work using Excel.Application COM, either via VBScript or Powershell, successfully on many other Windows systems  in our environment - Windows Server 2008 R2, Windows 7 (32-bit), etc.,  -BUT-
    The two servers we built out for running our automation process are Windows Server 2012 (SE) - and it just refuses to run on the 2012 servers - it gives the messages below from VBScript and PowerShell, respectively- 
    I have tried uninstalling and re-installing several different versions of Microsoft Excel (2007 Standard, 2010 Standard, 2010 Professional Plus, 32-bit vs. 64-bit, etc.), but it makes no difference.
    Would be extremely grateful if any one out there has had any success in running Excel automation on Server 2012 in a non-interactive environment that they could share.
    ( I have tried adding the "%windir%\syswow64\config\systemprofile\desktop"
    folder, which did fix the issue for me when testing on Windows Server 2008 R2, but sadly did not resolve it on Windows Server 2012 )
    [VBScript error msg]
    Z:\TestExcelMacro.vbs(35, 1) Microsoft Office Excel: Microsoft Office Excel cannot
    access the file 'Z:\TestExcelMacro.xlsm'. There are several possible reasons:
    • The file name or path does not exist.
    • The file is being used by another program.
    • The workbook you are trying to save has the same name as a currently open work
    [Powershell error msg]
    Exception calling "Add" with "0" argument(s): "Microsoft Office Excel cannot open or save any more documents because th
    ere is not enough available memory or disk space.
     To make more memory available, close workbooks or programs you no longer need.
     To free disk space, delete files you no longer need from the disk you are saving to."
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : ComMethodTargetInvocation
    You cannot call a method on a null-valued expression.
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : InvokeMethodOnNull

  • How to run Powershell script (function) through Windows Task Schduler ??

    Hello All,
    i have Powershell script which is created as a function. I have to give parameters to run the script. And it is working fine. Now i want to run this script through windows task scheduler but it is not working. I dont know how to call powershell function
    through task scheduler.
    From command line i run it like this:
    . c:\script\Get-ServiceStatusReport.ps1
    dir function:get-service*
    Get-ServiceStatusReport -ComputerList C:\script\server.txt -includeService "Exchange","W32Time" -To [email protected] -From [email protected] -SMTPMail mail01.xxx.gov.pk
    In windows Task scheduler I am giving this: it runs but i dont receive any output :
    Program/Script:
    C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
    Parameter:
    -file ". 'Get-ServiceStatusReport.ps1 -ComputerList C:\script\server.txt -includeService  "Exchange","W32Time" -To [email protected] -From [email protected] -SMTPMail  mail01.xxx.gov.pk'"
    Please HELP !!!

    Thanks for the reply:
    The script is already saved as Get-ServiceStatusReport.ps1 .
    On powershell it does not run like .\Get-ServiceStatusReport.ps1 (parameter).
    But i have to call it as function:
    Like this:
    Get-ServiceStatusReport -ComputerList C:\script\server.txt -includeService "Exchange","W32Time" -To [email protected] -From [email protected] -SMTPMail mail01.xxx.gov.pk
    As you said:
    I tried to run it like this:
    Program/Script:
    C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
    Parameter:
    -file "c:\script\Get-ServiceStatusReport.ps1 -ComputerList C:\script\server.txt -includeService  "Exchange","W32Time" -To [email protected] -From [email protected] -SMTPMail  mail01.xxx.gov.pk'"
    But its not working , on scheduler its giving error: (0xFFFD0000)
    Please HELP !!!
    WHOLE SCRIPT:
    function Get-ServiceStatusReport
    param(
    [String]$ComputerList,[String[]]$includeService,[String]$To,[String]$From,[string]$SMTPMail
    $script:list = $ComputerList
    $ServiceFileName= "c:\ServiceFileName.htm"
    New-Item -ItemType file $ServiceFilename -Force
    # Function to write the HTML Header to the file
    Function writeHtmlHeader
    param($fileName)
    $date = ( get-date ).ToString('yyyy/MM/dd')
    Add-Content $fileName "<html>"
    Add-Content $fileName "<head>"
    Add-Content $fileName "<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>"
    Add-Content $fileName '<title>Service Status Report </title>'
    add-content $fileName '<STYLE TYPE="text/css">'
    add-content $fileName "<!--"
    add-content $fileName "td {"
    add-content $fileName "font-family: Tahoma;"
    add-content $fileName "font-size: 11px;"
    add-content $fileName "border-top: 1px solid #999999;"
    add-content $fileName "border-right: 1px solid #999999;"
    add-content $fileName "border-bottom: 1px solid #999999;"
    add-content $fileName "border-left: 1px solid #999999;"
    add-content $fileName "padding-top: 0px;"
    add-content $fileName "padding-right: 0px;"
    add-content $fileName "padding-bottom: 0px;"
    add-content $fileName "padding-left: 0px;"
    add-content $fileName "}"
    add-content $fileName "body {"
    add-content $fileName "margin-left: 5px;"
    add-content $fileName "margin-top: 5px;"
    add-content $fileName "margin-right: 0px;"
    add-content $fileName "margin-bottom: 10px;"
    add-content $fileName ""
    add-content $fileName "table {"
    add-content $fileName "border: thin solid #000000;"
    add-content $fileName "}"
    add-content $fileName "-->"
    add-content $fileName "</style>"
    Add-Content $fileName "</head>"
    Add-Content $fileName "<body>"
    add-content $fileName "<table width='100%'>"
    add-content $fileName "<tr bgcolor='#CCCCCC'>"
    add-content $fileName "<td colspan='4' height='25' align='center'>"
    add-content $fileName "<font face='tahoma' color='#003399' size='4'><strong>Service Stauts Report - $date</strong></font>"
    add-content $fileName "</td>"
    add-content $fileName "</tr>"
    add-content $fileName "</table>"
    # Function to write the HTML Header to the file
    Function writeTableHeader
    param($fileName)
    Add-Content $fileName "<tr bgcolor=#CCCCCC>"
    Add-Content $fileName "<td width='10%' align='center'>ServerName</td>"
    Add-Content $fileName "<td width='50%' align='center'>Service Name</td>"
    Add-Content $fileName "<td width='10%' align='center'>status</td>"
    Add-Content $fileName "</tr>"
    Function writeHtmlFooter
    param($fileName)
    Add-Content $fileName "</body>"
    Add-Content $fileName "</html>"
    Function writeDiskInfo
    param($filename,$Servername,$name,$Status)
    if( $status -eq "Stopped")
    Add-Content $fileName "<tr>"
    Add-Content $fileName "<td bgcolor='#FF0000' align=left ><b>$servername</td>"
    Add-Content $fileName "<td bgcolor='#FF0000' align=left ><b>$name</td>"
    Add-Content $fileName "<td bgcolor='#FF0000' align=left ><b>$Status</td>"
    Add-Content $fileName "</tr>"
    else
    Add-Content $fileName "<tr>"
    Add-Content $fileName "<td >$servername</td>"
    Add-Content $fileName "<td >$name</td>"
    Add-Content $fileName "<td >$Status</td>"
    Add-Content $fileName "</tr>"
    writeHtmlHeader $ServiceFileName
    Add-Content $ServiceFileName "<table width='100%'><tbody>"
    Add-Content $ServiceFileName "<tr bgcolor='#CCCCCC'>"
    Add-Content $ServiceFileName "<td width='100%' align='center' colSpan=3><font face='tahoma' color='#003399' size='2'><strong> Service Details</strong></font></td>"
    Add-Content $ServiceFileName "</tr>"
    writeTableHeader $ServiceFileName
    #Change value of the following parameter as needed
    $InlcudeArray=@()
    #List of programs to exclude
    #$InlcudeArray = $inlcudeService
    Foreach($ServerName in (Get-Content $script:list))
    $service = Get-Service -ComputerName $servername
    if ($Service -ne $NULL)
    foreach ($item in $service)
    #$item.DisplayName
    Foreach($include in $includeService)
    write-host $inlcude
    if(($item.serviceName).Contains($include) -eq $TRUE)
    Write-Host $item.MachineName $item.name $item.Status
    writeDiskInfo $ServiceFileName $item.MachineName $item.name $item.Status
    Add-Content $ServiceFileName "</table>"
    writeHtmlFooter $ServiceFileName
    function Validate-IsEmail ([string]$Email)
    return $Email -match "^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$"
    Function sendEmail
    param($from,$to,$subject,$smtphost,$htmlFileName)
    [string]$receipients="$to"
    $body = Get-Content $htmlFileName
    $body = New-Object System.Net.Mail.MailMessage $from, $receipients, $subject, $body
    $body.isBodyhtml = $true
    $smtpServer = $MailServer
    $smtp = new-object Net.Mail.SmtpClient($smtphost)
    $validfrom= Validate-IsEmail $from
    if($validfrom -eq $TRUE)
    $validTo= Validate-IsEmail $to
    if($validTo -eq $TRUE)
    $smtp.UseDefaultCredentials = $true;
    $smtp.Send($body)
    write-output "Email Sent!!"
    else
    write-output "Invalid entries, Try again!!"
    $date = ( get-date ).ToString('yyyy/MM/dd')
    sendEmail -from $From -to $to -subject "Service Status - $Date" -smtphost $SMTPMail -htmlfilename $ServiceFilename

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

  • Passing parameters with spaces to SCCM Run PowerShell Script task

    I am working on an OS deployment task sequence in SCCM 2012 R2 with several Run PowerShell Script tasks.  Most of them run fine, but I am having trouble with the one I need to pass parameters to.
    The parameters I need to pass are:
    -ComputerOU "ou=All Workstations,dc=contoso,dc=com" -GroupDN "cn=Group1,ou=All Groups,dc=contoso,dc=com"
    I have that line (with actual DNs) entered in Parameters of the task.
    But when the script runs on the target machine, the values of the parameters in the script are truncated at the spaces.  $ComputerOU is set to "ou=All" and $GroupDN is set to "cn=Group1,ou=all"
    What syntax should I be using the Parameters field of the Task in order to properly pass PowerShell parameter string values that include spaces?
    Tim Curwick
    MadWithPowerShell.com

    Thank you, TC, but I am not calling the parameters from within PowerShell.
    The parameters are in the settings of a task sequence task to be used by the task to launch a script.  The syntax I am using would be correct for use within PowerShell or from a command line or batch script, but SCCM appears to be doing some parsing
    before or while it is passing them to the script, possibly dropping the quotes which causes mishandling of the spaces in the string values.
    Historically, it is always challenging to give one application parameters to pass to another application, and the required syntax can get quite tricky when the two application handle quotes or spaces differently, or when the parent application wants to parse
    something intended to be passed on as is to the child application.
    I'm sure someone has already figured out what the syntax needs to be for doing this with an SCCM 'Run PowerShell Script" task, it's just one of those issues that is hard to Google effectively.
    Any other ideas?
    Tim Curwick
    MadWithPowerShell.com

  • Script runs exponentially slower as scheduled task

    I have a script that I've run a few times before using Citrix snapins. It runs just fine in the console, generally taking around 20 minutes. When I try to run it as a scheduled task, it never completes.
    The script is as follows:
    $time1 = get-date
    Add-PSSnapIn Citrix.Common.Commands
    Add-PSSnapin Citrix.XenApp.Commands
    $_csv = @()
    $_csv_header = """Date"",""Sessions"",""IdleSessions"",""ForcedDCSEssions"""
    $_csv += $_csv_header
    $count = 0
    $idlesessions = get-xasession -Full | where {$_.browsername -eq "IDM Search" -and $_.state -ne "Listening" -and $_.state -ne "Disconnected" -and $_.SessionName -ne "Console" -and ($_.currenttime - $_.Lastinputtime).minutes -gt 15}
    $sessions = get-xasession -Full | where {$_.browsername -eq "IDM Search" -and $_.state -ne "Listening" -and $_.state -ne "Disconnected" -and $_.SessionName -ne "Console"}
    if ($sessions.count -gt 400)
    foreach($idlesession in $idlesessions){
    stop-xasession -SessionId $idlesession.sessionid -ServerName $idlesession.servername
    $count++
    $sessioncount = $sessions.count
    $idlecount = $idlesessions.count
    $date = get-date
    $_csv += """$date"",""$sessioncount"",""$idlecount"",""$count"""
    $time2 = get-date
    $time3 = $time2 - $time1
    $duration = $time3.TotalMinutes
    $_csv += """$duration"""
    $date = get-date -format 'dd.MM.yyyy.hh.mm'
    $_csv | out-file c:\powershell\logs\ImageDC$date.csv -Encoding ASCII
    The Task Scheduler settings are as follows:
    General tab: It runs with local and domain admin privs whether the user is logged in or not
    Triggers tab: It begins at 7:55 AM every morning, repeating every 30 minutes for 12 hours (enabled is checked)
    Actions tab: Start Program  = %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe      Add arguments = –noninteractive -nologo -noprofile -noexit C:\powershell\ScheduledIDMDisconnect.ps1      start in =  
     c:\powershell
    Conditions tab: Only two things checked are "Start the task only if the computer is on AC power" and "Stop if the computer switches to battery power" (those are the defaults, IIRC)
    Settings tab: "Allow task to be run on demand" is checked. "Stop the task if it runs longer than (4 hours)" is checked. "If the running task does not end when requested, force it to stop" is checked. "If the task is already
    running, then the following rule applies: (Run a new instance in parallel)" is at the bottom.
    Can anyone offer any insight? Thanks!
    [email protected]

    Hi,
    Why the -NonInteractive, -NoLogo, -NoProfile, and -NoExit switches? I generally only use -File to point at the script file.
    You might also need to check 'Run with highest privileges'.
    Don't retire TechNet! -
    (Don't give up yet - 13,085+ strong and growing)
    I used all those switches because that's what was "in place" as a standard where I am. I already had "run with highest privileges" checked, but switching to just -file + file location seems to have it running as intended now? I'm
    at least getting log files in the specified directory.
    Thanks!
    [email protected]

  • Run Powershell Script task sequence

    Hi,
    Anyone have good documentation on how to use the Run PowerShell Script task sequence ?
    Thanks

    If you are just interested in running a powershell command without creating a package, you can do this with the the Command line step by using this format in the command line:
    PowerShell -ExecutionPolicy bypass -Command "& {your powershell commands}"
    Here is an example of a multiline command to increase the agents cache size. Notice the ";"'s which are used to delineate a new line.
    PowerShell -ExecutionPolicy bypass -Command "& {$UIResourceM gr = New-Object -ComObject UIResource.UIResourceMgr;$Cache = $UIResourceMgr.GetC acheInfo();$Cache.TotalSize = "20480"}"

  • Need to run powershell script in a bat file

    I have a ps1 file with the following:
    Get-ADUser -Filter * -SearchBase "ou=<HOSPOU>,ou=Domain Users and Groups,dc=<hospdomain>,dc=local" -Properties Description,EmailAddress| Select-Object -Property Name,SamAccountName,Description,EmailAddress|Export-Csv "\\<server>\home2$\information
    services\IS STAFF\Documentation\AD Info\smcusers.csv";
    I have a bat file:
    @ECHO OFF
    SET ThisScriptsDirectory=%~dp0
    SET PowerShellScriptPath=%ThisScriptsDirectory%smcusers.ps1
    %windir%\system32\WindowsPowerShell\v1.0\powershell.exe -noexit -command import-module ActiveDirectory "%PowerShellScriptPath%";
    But while it launches powershell with the AD module, It apparently cannot read the ps1 file.
    I get:
    H:\>C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -noexit -command i
    mport-module ActiveDirectory "H:\smcusers.ps1";
    Import-Module : A positional parameter cannot be found that accepts argument 'H
    :\smcusers.ps1'.
    At line:1 char:14
    + import-module <<<<  ActiveDirectory H:\smcusers.ps1;
        + CategoryInfo          : InvalidArgument: (:) [Import-Module], ParameterB
       indingException
        + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell
       .Commands.ImportModuleCommand
    I have tried to modify the parameters 
    %windir%\system32\WindowsPowerShell\v1.0\powershell.exe -noexit -command import-module ActiveDirectory -File "%PowerShellScriptPath%";
    Still no luck.
    I need to be able to run this as a scheduled task.
    Karon W

    Apparently I don't know where to put everything.
    I have a single line:
    %windir%\system32\WindowsPowerShell\v1.0\powershell.exe -noexit import-module ActiveDirectory; -Command {Get-ADUser -Filter * -SearchBase "ou=Shannon Memorial,ou=Domain Users and Groups,dc=shannonhealth,dc=local" -Properties Description,EmailAddress|Select-Object
    -Property Name,SamAccountName,Description,EmailAddress|Export-Csv "\\svr-resource2\home2$\information services\IS STAFF\Documentation\AD Info\smcusers.csv"}
    This is the response:
    H:\>C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -noexit import-mod
    ule ActiveDirectory; -Command {Get-ADUser -Filter * -SearchBase "ou=Shannon Memo
    rial,ou=Domain Users and Groups,dc=shannonhealth,dc=local" -Properties Descripti
    on,EmailAddress  | Select-Object -Property Name,SamAccountName,Description,Email
    Address  | Export-Csv "\\svr-resource2\home2$\information services\IS STAFF\Docu
    mentation\AD Info\smcusers.csv"}
    'Select-Object' is not recognized as an internal or external command,
    operable program or batch file.
    I modified to 2 lines:
    %windir%\system32\WindowsPowerShell\v1.0\powershell.exe -noexit import-module ActiveDirectory;
    Get-ADUser -Filter * -SearchBase "ou=Shannon Memorial,ou=Domain Users and Groups,dc=shannonhealth,dc=local" -Properties Description,EmailAddress|Select-Object -Property Name,SamAccountName,Description,EmailAddress|Export-Csv "\\svr-resource2\home2$\information
    services\IS STAFF\Documentation\AD Info\smcusers.csv"
    This is the response:
    H:\>C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -noexit import-mod
    ule ActiveDirectory;
    PS H:\> exit ************I had to type*****************
    H:\>Get-ADUser -Filter * -SearchBase "ou=Shannon Memorial,ou=Domain Users and Gr
    oups,dc=shannonhealth,dc=local" -Properties Description,EmailAddress  | Select-O
    bject -Property Name,SamAccountName,Description,EmailAddress  | Export-Csv "\\sv
    r-resource2\home2$\information services\IS STAFF\Documentation\AD Info\smcusers.
    csv"
    'Get-ADUser' is not recognized as an internal or external command,
    operable program or batch file.
    If I paste the command in before I type exit, it works. 
    If I paste:
    %windir%\system32\WindowsPowerShell\v1.0\powershell.exe -noexit import-module ActiveDirectory;
    I am put in the ad powereshell
    Then I paste:
    Get-ADUser -Filter * -SearchBase "ou=Shannon Memorial,ou=Domain Users and Groups,dc=shannonhealth,dc=local" -Properties Description,EmailAddress|Select-Object -Property Name,SamAccountName,Description,EmailAddress|Export-Csv "\\svr-resource2\home2$\information
    services\IS STAFF\Documentation\AD Info\smcusers.csv"
    and I get the expected output.
    What do I need to have in the bat file so the 2nd line of the script will run? and where does it go?
    Karon W

  • 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

  • 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

Maybe you are looking for

  • Session scope and request scope

    Hi, I've a manage bean in session scope and within this bean I've a reference of another object (class person) . My question is, do i have to register this class in my faces-config-xml and if yes which scope should it have? session or request? Or it

  • Can I upgrade IPhoto 6.0.6 to IPhoto 11' on a Mac OS 10.4.1?

    Can I upgrade IPhoto 6.0.6 to Iphoto 11' on my Mac OS 10.4.1 ?

  • Firmware update

    After update my N96 to v11.101.098.1 I cannot change the "Date and Hour" of my mobile and problem to connect to my pc via nokia Nseries pc suite my product code is 0567380 Did someone get a same problem or problems after update the firmware ? Thanks

  • Weird Display Issue...

    Hey, my MacBook Pro has been working perfectly except for an issue in the display. On occasion, I will be using it and then the screen will randomly go black as if it was going to sleep but if I move the mouse it doesn't come back. I have to press do

  • Is OS X Mavericks v 10.9 for a MacBook Pro?

    I received an "update notice" re: OSX Maverick v 10.9 on my MacBook Pro.  When I tried to download the update, it said it was not compatible with my system.  So, is this "update" for desktops or laptops too?