Running powershell script with customer parameters as a scheduled task

tfl wrote:I guess I don't get why you are wanting thisMy regular tasks run,. and take data from data files. Want your batch to get processed today? Then add it to the queue file by 5:00 PM.. The task runs at 5:01 and works with whatever data is available. And if the file is empty, nothing happens each night. If you want to pass parameters like this, then why bother with a scheduled task? You'd need to remove the old one and add the new one each time. Which is extra work and complexity, especially if the task at hand is in any way 'dangerous' if run twice with the same data (ie you forget to change the task or remove it).I'm using a scheduled task to trigger the script, I'm using the "on event" trigger and then calling the script as an action. The method I was using before (calling via a bat file with the event Id hard coded into that"...

Hi all,Having one of those hair pulling issues where something should work but for some reason its blindly refusing not to!I've created this script that is a bit of an extension to the email on eventID for task scheduled. It basically pulls out the various information from the actual event and fires off an email to our alerting team to investigate etc.That all works great, but what I'm now trying to do is get it to accept a custom parameter so the actual event ID its looking for doesn't have to be hard coded and can be passed to it via the commandline etc. I've got it all setup and work great but for the life of me can't get it to work correctly when set as a scheduled task. This is what the command basically looks like:powershell -executionpolicy bypass -command "& 'pathtofile\script.ps1' -evtid 8004"The latter part is the customer...
This topic first appeared in the Spiceworks Community

Similar Messages

  • What is the best way to run a powershell script with parameters in the Task Scheduler?

    Hello, 
    Want to run the following from a scheduled task in the Task Scheduler on a server.  What is the best approach?
    .\pscript.ps1 -csvfile "\\Srv1\Share\File.txt"
    Thanks for your help! SdeDot

    Hi,
    To run a powershell script with parameters in the Task Scheduler:
    Program: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
    Add argument (optional): -Command "& c:\scripts\test.ps1 -par1 2 -par2 3"
    Hope the below two articles be helpful for you:
    Schedule PowerShell Scripts that Require Input Values
    https://blogs.technet.com/b/heyscriptingguy/archive/2011/01/12/schedule-powershell-scripts-that-require-input-values.aspx
    How to Schedule a PowerShell Script
    http://dmitrysotnikov.wordpress.com/2011/02/03/how-to-schedule-a-powershell-script/
    Regards,
    Yan Li
    Regards, Yan Li

  • 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

  • Run a powershell script with domain credentials during task sequence

    I have a powershell script that adds the computer it is run on to a security group.  If I log onto the computer with a domain account it works perfectly.  However, if it is run while logged on as the local admin account it fails with an error message
    that says the domain either doesn't exist or cannot be reached.
    This is a problem because when a computer is being imaged the process runs with the local admin account.  Is there a way to run this script with domain credentials in the task sequence?
    Thanks,
    Andy

    How are you running the Powershell script? If you use a Run Command Line step, you can specify an account to run as. Something like "powershell %scriptroot%\psscript.ps1" where the psscript.ps1 is located in your Scripts folder in your deployment
    share.
    -Nick O.

  • 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

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

  • Which is better approach to manage sharepoint online - PowerShell Script with CSOM or Console Application with CSOM?

    Which is better approach to manage sharepoint online - PowerShell Script with CSOM or Console Application with CSOM?
    change in sharepoint scripts not require compilation but anything else?

    Yes, PowerShell is great, since you can quick change your code without compilation.
    SP admin can write ps scripts without specific tools like Visual Studio.
    With powershell you can use cmdlets,
    which could remove a lot of code, for example restarting a service.
    [custom.development]

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

  • PowerShell logon script with function parameters

    Hi,
    I've made file, something.ps1, that has to functions: Set-Something and Remove-Something. Unless necessary I will not explain what they do (though the names should provide the gist of it).
    These functions can be run successfully with the commands.
    Set-Something -Path "C:\Path\To\Somtehing"Remove-Something -Path "C:\Path\To\Somtehing"
    I'm trying to implement these as logon and logof in GPO. What i set for example in logon is:
    Tab: PowerShell
    Name: "C:\Scripts\something.ps1"
    Parameters: "Set-Something -Path 'C:\Path\To\Something'"
    This does not work. Why?
    PS: I can get it to work with adding the following to the end of the script, and run it without parameters at login.
    Set-Something -Path 'C:\Path\To\Something'
    But that isn't what I'm trying to do, because that means I will have to create one script for logon and one for logoff. I wish I want to run the same script, but different functions at logon and logoff.

    Hi,
    Check the following points,
    - Check the availability of your PowerShell scripts in the netlogon share - \\Server\NETLOGON
    - Check whether the GPO is linked to the OU containing users, because GPO with logon script need to assigned for scope with users, where as  GPO with startup script need to be assigned for scope with computers.
    - To confirm whether GPO settings are applied - run gpresult from command prompt.
    - To force the GPO settings - run gpupdate /force from command prompt.
    - Then logoff and login again to check the status.
    Regards,
    Gopi
    JiJi
    Technologies

  • 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

  • SCCM 2012 application run Powershell script and return codes

    Hi,
    I created an new application (imported as MSI) in SCCM 2012R2. After import I changed the deployment type installation program to run a Powershell script: powershell.exe -ExecutionPolicy Unrestricted -File "Install FactSet 2013 5I.ps1
    My goal is to close some processes before installing the MSI. This works. But on a failure the application program also return code 0 (AppEnforce.log). Is it possible to pass the MSI return codes to SCCM.
    Maybe anyone had the same or idea's to solve this? Thanks in advance.
    Regards,
    Peter
    Powershell script code:
    $ExitCode=0
    Function
    Stop-RunningApplication{
    Param(
    [parameter(Mandatory
    =$true)]
    [string]$ProcessName#
    Specify process names separated by commas
    # Split multiple processes on a comma and join with the regex operator '|' to perform "or" match against
    multiple applications
    $processName=$processName-split(",")
    -join("|")
    $process=Get-Process|Where{
    $_.ProcessName
    -match$processName}
    |Stop-Process-Force
    #Stop running processes
    Stop-RunningApplication
    -ProcessName"excel,outlook,fdsw32,marquee,POWERPNT,WINWORD"
    #Install FactSet 2013 5I
    $ExitCode
    =(Start-Process".\FactSet_Setup_2013_5I_x644.msi"'/qn
    FACTSET_CLOSE_PROCESSES=1 /l*v C:\Temp\InstFac20135I.log'-Wait-Passthru).ExitCode
    Environment]::Exit($ExitCode)
    Peter vd Bosch

    It's really hard to tell from the code above because of the way it's listed, but are sure that even executes? I see at least one stray curly brace and a stray square bracket.
    For the Start-Process cmdlet, have you tried without the -passthru parameter?
    Also, using the actual parameters will make the code much more readable instead of relying on position.
    Jason | http://blog.configmgrftw.com | @jasonsandys

  • Get-Item: Cannot find path ' ' because it does not exist. While running Powershell script.

    I am trying to run a PowerShell script to upload files into a SharePoint site in an Azure environment...the script works fine on my local machine, but every time I run it in Azure (remotely), I get errors. Here is what my simple script looks like...
    if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
    Write-Host "Loading Sharepoint Module "
    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
    Add-PSSnapin -Name Microsoft.SharePoint.PowerShell
    if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell) -eq $null )
    Write-Host "Failed to load sharepoint snap-in. Could not proceed further, Aborting ..."
    Exit
    #Script settings
    $webUrl = "http://sampleWebUrl"
    $docLibraryName = "My Documents"
    $docLibraryUrlName = "My%20Documents"
    $localFolderPath = get-childitem "C:\Upload\Test Upload\My Documents\" -recurse
    $contentType = "ContenttType1"
    #Open web and library
    $web = Get-SPWeb $webUrl
    write-host "Web:" $web
    $docLibrary = $web.Lists[$docLibraryName]
    write-host "docLibrary:" $docLibrary
    $files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles()
    write-host "files:" $files
    If ($contentType = "ContenttType1")
    #Open file
    $fileStream = ([System.IO.FileInfo] (Get-Item $file.FullName)).OpenRead()
    # Gather the file name
    $FileName = $File.Name
    #remove file extension
    $NewName = [IO.Path]::GetFileNameWithoutExtension($FileName)
    #split the file name by the "-" character
    $FileNameArray = $NewName.split("_")
    $check = $FileNameArray.Length
    #Add file
    $folder = $web.getfolder($docLibrary.rootFolder.URL)
    write-host "Copying file " $file.Name " to " $folder.ServerRelativeUrl "..."
    $spFile = $folder.Files.Add($folder.Url + "/" + $file.Name, [System.IO.Stream]$fileStream, $true)
    $spItem = $spFile.Item
    write-host "Success"
    write-host "SP File:" $spFile
    write-host "SP Item" $spItem
    #populate columns
    $spItem["Column1"] = $FileNameArray[0]
    $spItem["Column2"] = $FileNameArray[1]
    $spItem.Update()
    $fileStream.Close();
    Again, I can run this on my local machine and it works just fine, but when I attempt to run it on the Azure environment I get this error...
    Get-Item : Cannot find path 'C:\powershellscripts\12653_B7045.PDF' because it does not exist.
    At C:\PowerShellScripts\Upload-FilesIntoSharePointTester.ps1:32 char:42
    +     $files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles()
    +                                          ~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : ObjectNotFound: (C:\powershellscripts\12653_B7045.PDF:String) [Get-Item], ItemNotFoundException
        + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand
    What strikes me first is the fact that the file its looking for is in the "C:\Upload\Test Upload\My Documents\" directory, but the error keeps saying "C:\powershellscripts\" which is where my script resides and not the files I want to
    upload into SharePoint. When I step through the code, all the variables are holding the correct values. The $localFolderPath shows the name of files that I am attempting to upload, so it recognizes them. But once I step through this particular line of code,
    the error occurs...
    $files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles()
    Is this an error caused because I am remoting into the Azure environment? Has anyone dealt with this issue before? I would really appreciate the help. Thanks
    Update: quick thing I noticed is that these two lines of code are returning null values. Again, is this handled differently in Azure or remotely? I ask cause this is the way I know how to do this, locally.
    $docLibrary = $web.Lists[$docLibraryName]
    $files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles()

    "...square brackets are wildcard characters in Windows PowerShell..."
    When you use cd without a parameter it uses the -Path parameter. In this case you'll have to escape the square brackets so they are not considered wildcards. Each of the commands in the first example does the exact same thing.
    cd 'Learn PowerShell `[Do Whatever`]'
    cd -Path 'Learn PowerShell `[Do Whatever`]'
    cd (or Set-Location) also has a literal path parameter (-LiteralPath) that does not require using an escape character (`) before each of the brackets. Hope this helps.
    cd -LiteralPath 'Learn PowerShell [Do Whatever]'

  • Update a filed value with powershell script with ordery by and where condition

    Hi
    I have below powershell script to update list columns but  how i update a field value with ordery by a column and where condition
    below is the part of my script
    $list = $web.Lists[$listName]
    $items = $list.items
    $internal_counter = 1
    #Go through all items
    foreach($item in $items)
    if($item["CourtNO"] -eq $null)
    #if($item["CourtNo"] -eq '1')
    $item["CaseNo"] = $internal_counter
    #how to add a column ordery by Title
    # and where Title field value from 1 to 10
    $internal_counter++
    adil

    Hi,
    You mean that you only need to update all items with Title field value in range 1..10 and order by them before run the loop statement update?
    If so, use CAML query to get the items only match the condition.
    #Build Query
    $spQuery = New-Object Microsoft.SharePoint.SPQuery
    $query = '<Where><And><Gte><FieldRef Name="Title" /><Value Type="Text">0</Value></Gte><Lte><FieldRef Name="Title" /><Value Type="Text">10</Value></Lte></And></Where><OrderBy><FieldRef
    Name="Title"/></OrderBy>'
    $spQuery.Query = $query
    $spQuery.RowLimit = $list.ItemCount
    $items = $list.GetItems($spQuery)
    Hope this help!
    /Hai
    Visit my blog: My Blog | Visit my forum:
    SharePoint Community for Vietnamese |
    Bamboo Solution Corporation

  • 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

  • Running PowerShell Script to automate the installation of IIS feature - Add-WindowsFeature error, help please

    I'm just learning PS scripting and Chef Programming, so I'm sure I'm missing something simple. I'm trying to run a recipe that is using PS as the interpreter. I've ensured I'm running PS in 64 bit with admin privileges, and have Imported the ServerManager
    module. I even added a line to my script to have it run that first, but am still receiving an error in my script. I'm running this on a VM of Server 2008R2
    Script:
    powershell_script 'Install IIS' do
      code "Import-Module ServerManager -passthru"
      code "Add-WindowsFeature Web-Server"
      guard_interpreter :powershell_script
      not_if "(Get-WindowsFeature -Name Web-Server).Installed"
    end
    Error:
    PS C:\Users\Administrator\chef-repo> chef-apply webserver.rb
    Recipe: (chef-apply cookbook)::(chef-apply recipe)
      * powershell_script[Install IIS] action run
        ================================================================================
        Error executing action `run` on resource 'powershell_script[Install IIS]'
        ================================================================================
        Mixlib::ShellOut::ShellCommandFailed
        Expected process to exit with [0], but received '1'
        ---- Begin output of "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat
    None -File "C:/Users/ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1" ----
        STDOUT:
        STDERR: The term 'Add-WindowsFeature' 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.
        ---- End output of "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat No
    ne -File "C:/Users/ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1" ----
        Ran "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat None -File "C:/Us
    ers/ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1" returned 1
        Resource Declaration:
        # In webserver.rb
          1: powershell_script 'Install IIS' do
          2:   code "Import-Module ServerManager -passthru"
          3:   code "Add-WindowsFeature Web-Server"
          4:   guard_interpreter :powershell_script
          5:   not_if "(Get-WindowsFeature -Name Web-Server).Installed"
          6: end
        Compiled Resource:
        # Declared in webserver.rb:1:in `run_chef_recipe'
        powershell_script("Install IIS") do
          action "run"
          retries 0
          retry_delay 2
          guard_interpreter :powershell_script
          command "\"powershell.exe\" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat None -Fi
    le \"C:/Users/ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1\""
          backup 5
          returns 0
          code "Add-WindowsFeature Web-Server"
          interpreter "powershell.exe"
          cookbook_name "(chef-apply cookbook)"
          recipe_name "(chef-apply recipe)"
          not_if "(Get-WindowsFeature -Name Web-Server).Installed"
        end
    [2014-12-24T10:29:56-08:00] FATAL: Stacktrace dumped to C:/chef/cache/chef-stacktrace.out
    [2014-12-24T10:29:56-08:00] FATAL: Mixlib::ShellOut::ShellCommandFailed: powershell_script[Install IIS] ((chef-apply coo
    kbook)::(chef-apply recipe) line 1) had an error: Mixlib::ShellOut::ShellCommandFailed: Expected process to exit with [0
    ], but received '1'
    ---- Begin output of "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat None
     -File "C:/Users/ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1" ----
    STDOUT:
    STDERR: The term 'Add-WindowsFeature' is not recognized as the name of a cmdlet, function, script file, or operable prog
    ram. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
    ---- End output of "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat None -
    File "C:/Users/ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1" ----
    Ran "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat None -File "C:/Users/
    ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1" returned 1

    Hi There,
    We have a application named Microsoft SCOM. That as well requires ISS to be installed. I tried this long back and it worked in powershell. Below is the powershell script i used to install IIS and some specific features from it. Hope it helps in altering
    it and making one of your own script.
    1.  Launch the PowerShell command
    prompt
     Run this command
    Import-Module ServerManager
    3. Press Enter
    4. Run this
    command
    Add-WindowsFeature NET-Framework-Core,Web-Metabase,Web-WMI,Web-Static-Content,Web-Default-Doc,Web-Dir-Browsing,Web-Http-Errors,Web-Asp-Net,Web-Net-Ext,Web-ISAPI-Ext,Web-ISAPI-Filter,Web-Filtering,Web-Windows-Auth,
    Web-Mgmt-Console –restart
    Gautam.75801

Maybe you are looking for

  • I've lost all track rankings, last played etc data, how do I get it back!?

    I accidentally deleted some iTunes related files, but restored them from the recycle bin. My whole iTunes library had disappeared but I managed to restore that, however, all the track rankings, last played, play count data is missing. A real pity as

  • Scrap quantity to be minus from yield qty. in the confirmstion(co11)

    i have problem in confirmation of production order. suppose i have production order of 15 qtys.with four operation to be confirmed (co11). operation qty.yield srcap qty. 0010 1 5 0 0020 14 1 0030 14 0 now, in 0020 operation i have 14 yield & 1 srcap

  • Cannot run InDesign CS or Photoshop CS after install

    I have installed photoshop cs and InDesign CS onto my iMac on Mac OS X 10.3.9. They have installed fully and I have entered the serial numbers in and they have been authorised. The folder then appears in my HD:Applications as normal. However, when I

  • Ne peux être installer le logiciel est déjà installé sur la machine

    Bonjour, Je un gros soucis j'ai désinstallé un kit de connexion pour une clé 3g Au moment que j'ai revoulu le réinstaller il me met le messge suivant ne peux être installer le logiciel est déjà installé sur la machine. J'ai beau chercher dans tout le

  • SEPA y Norma 43

    Hola a todos, con la implantación de SEPA, me surge una duda, que espero podáis ayudarme a aclarar. La implementación de SEPA supondrá la armonización de las cuentas bancarias, que se identificarán a partir de ahora con el código internacional IBAN,