Help using SMLets in workflow powershell script

Hello,
I have written a powershell script in a workflow to help me perform a process. The idea is this: We have an extended Incident class and a custom RMA class, users will sometimes need to launch an RMA from an incident, but never an incident from an RMA or
an RMA by itself. Therefore, source cardinality I assume is 1 and target cardinality is 2 (unlimited). The RMA NEEDS TO BE ASSOCIATED (related) to the ID # of the Incident Request. So, if you click on the Incident and go to related items, you should see the
RMA id # there, and when you go to the related items of the RMA, you should see the appropriate IR # there. The workflow is launched by trigger: when an object of the RMA class is created.
The workflow contains the following powershell script:
# Load the SMlets module
Import-Module SMlets
# Get Date
$date = ((Get-Date).AddDays(-1));
# Set ClassName
$ClassName = Get-SCSMClass -Name Flexity.RMA.Class;
# Get the RMA Class
$RMAClass = Get-SCSMObject -Class $ClassName | where{$_.CreatedDate -gt $date};
# Set DisplayName, Title and Description to RMAx
foreach ($RMA in $RMAClass)
 {$RMANumber = $RMA.RMA_ID; $RMA | Set-SCSMObject -PropertyHashtable @{"DisplayName"  =  $RMANumber; “Title” =  $RMANumber; ”Description” =  $RMANumber;  
So I can get the RMA objects created, and properly name them so they show up as RMA{#} but still have not figured out how to get the parent incident and relate it to the appropriate RMA #... Any help would be greatly appreciated!!!!!

@Anders
For Service Manager 2010, numbers larger than 1 in a cardinality statement are evaluated as “unlimited” when an MP is imported into Service Manager. This means that MaxCardenality=“2” is the same as MaxCardenality=“2147483647”. Has this changed from 2010
to 2012?
@Thomas
You are indeed correct but I didn't receive any response in there from my last post so I thought it was dead by now. I have also progressed MUCH further from when I had posted that question, so I figured I should just make it a new topic as the topic of
the question has become much more specific. I will link this post in there to be used as reference.
I actually ended up figuring this out, let me know what you guys think and if it can be optimized in any way, or if you see any error checking I should add in somewhere.
Thank you all for your help, especially with your detailed responses Thomas
My original idea was to have a workflow and that workflow got launched when an object of the RMA class was created, regardless of HOW it was launched through console task or custom control or whatever. However, I ended up using a console task, which when clicked
launches my script :)
Code:
# Creates a variable called IncidentID and points Incident # to it for use within the script
Param([string]$IncidentID)
# Load the SMlets module
Import-Module SMlets
# Get the Incident Class
$IncClass = Get-SCSMClass -Name System.WorkItem.Incident$
# Get the RMA Class
$RMAClass = Get-SCSMClass -Name flexity.RMA.class
# Build the Filter String
$FilterStr = "ID -eq " + $IncidentID
# Find the Incident we need to link to an RMA
$Inc = Get-SCSMObject -Class $IncClass -Filter $FilterStr
$RMAIncText = ["Linked to Incident " + $Inc.ID + ""]
$RMADescription = $RMAIncText
New-SCSMObject -Class $RMAClass -PropertyHashtable (@{Title = $Inc.Title; Description = $RMADescription})
# Find the new RMA to be linked
$FilterStr = "Description -eq '$RMADescription'"
$RMA = Get-SCSMObject -Class $RMAClass -Filter $FilterStr
#Set RMA Number Variable
$RMANumber = $RMA.RMA_ID;
#Clean up DisplayName, Title and Description 
$RMA | Set-SCSMObject -PropertyHashtable @{"DisplayName"  =  $RMANumber; "Title" =  $RMANumber; "Description" =  $RMANumber;   }
# Create the relationship between the two items
$RWIClass = Get-SCSMRelationshipClass -Name System.WorkItemRelatesToWorkItem$
New-SCSMRelationshipObject -Relationship $RWIClass -Source $Inc -Target $RMA -Bulk
New-SCSMRelationshipObject -Relationship $RWIClass -Source $RMA -Target $Inc -Bulk
# Unload the SMlets module
Remove-Module SMlets

Similar Messages

  • Using Echo Command in PowerShell Script for Configuration Item

    Hello All,
    Before you tell me to post my PowerShell question to the PowerShell Forum, please know that the PowerShell portion of my task works just fine. It is the SCCM portion of my task that keeps failing, so that is why I am here. To give some background...
    There are two servers in our SCCM test environment. Both the SCCM server and SQL DB server are 2012, patched and updated.
    Test servers in my Device Collection being used for running Baselines and Reports against are 2008R2 and 2012, patched and updated.
    I have created a Configuration Item that checks to see if the FTP Server Role Feature has been installed on a 2008 or 2012 server. To do the check, I am using the following PowerShell script:
    (get-windowsfeature -Name Web-Ftp-Server).Installed
    When I log into my 2008R2 and 2012 test servers, and run this command directly on the server, it will return a "True" if the FTP Server Role Feature is installed on either server, and a "False" if it is not installed. Basically,
    it works as advertised.
    When I setup my Configuration Item and then deploy my Baseline, or run a report against my device collection of test servers, SCCM will return a correct response (True or False) for the 2012 test server, but throws the following error for the 2008R2
    server:
    0x87df00329 application requirement evaluation or detection failed
    Google searches for this have not been very helpful.
    Now, when I created the Configuration Item and referenced PowerShell, the configuration screen has the following note:
    "Specify the script to find and return the value to be assessed for compliance on client devices. Use the echo command to return the script value to Configuration Manager."
    Since I did not include an echo command in my PowerShell script above, I figured that was my problem, so I did the following:
    Logging onto both of my test servers (2008R2 & 2012) I was able to successfully run the following PowerShell commands and get the expected responses of True or False:
    (get-windowsfeature -Name Web-Ftp-Server).Installed | echo
    (get-windowsfeature -Name Web-Ftp-Server).Installed | write-output (http://technet.microsoft.com/en-us/library/hh849921.aspx)
    (get-windowsfeature -Name Web-Ftp-Server).Installed | write-host (http://technet.microsoft.com/en-us/library/ee177031.aspx)
    However, when I use any of these PowerShell commands in my Configuration Item, NEITHER of my test servers returns a response to the SCCM server.
    When I check the report, both servers show as "Unknown" and when I click on the number 2 (as in 2 servers unknown), the following report page (List of unknown assets for a configuration baseline) has absolutely no data/information at all.
    So...I am at a loss.
    SCCM tells me to use an echo command to return a script value to Configuration Manager. The PowerShell scripts above, with the various echo related commands, work just fine on the servers themselves, but they return no information when run via SCCM.
    What am I missing?
    Any help will be appreciated.
    Thanks in advance for your time.

    Sorry for my ignorance, but I don't understand. (I forgot to mention that I am new at both PowerShell and SCCM.)
    After I change the PowerShell script to add the echo/write-output/write-host cmdlet, I open the ConFig Item and "Clear" the PowerShell script and then re-add it. When I do that, it correctly shows the change in the ConFig Item.
    Next I open the Baseline, then open the ConFig Item within the Baseline to make sure the change is reflected there as well, which it is.
    I then deploy the Baseline to my Device Collection. After that, I run a report against the Baseline and Device Collection and it returns the "Unknown" result.
    If I open the PowerShell script and remove the echo/write-output/write-host cmdlet, then go through the rest of the process of updating and reporting, the result it returns changes, showing one server in compliance and the other server out of compliance,
    which leads me to think that all changes have taken correctly.
    Does that sound right? If I manually deploy the Baseline, is that the same as the client retrieving policies from the management point?
    Sorry to be so thick but I'm learning as I go.
    Thanks again for your help.

  • How to use UDL file in Powershell script?

    Hello Scripting Guys,
    I have a VBScript that works great for connecting to an Oracle DB using a .UDL file. Here is the important part of the script:
    Set dataconnect = CreateObject("ADODB.Connection")
    Path= "File name=C:\UDLs\TEST.udl"
    dataconnect.ConnectionString = Path
    dataconnect.open
    Set oCmd = CreateObject("ADODB.Command")
    oCmd.ActiveConnection = dataconnect
    oCmd.CommandText = "SYSTEM.JOB.INSERT_JOB"
    oCmd.CommandType = 4
    set oParam = oCmd.CreateParameter("job_name_val")
    oParam.type = 200
    oParam.direction = 1
    oParam.size = 255
    oParam.value = job_name
    oCmd.Parameters.Append oParam
    set oParam = oCmd.CreateParameter("description")
    oParam.type = 200
    oParam.direction = 1
    oParam.size = 4000
    oParam.value = descrip
    oCmd.Parameters.Append oParam
    set oParam = oCmd.CreateParameter("status_val")
    oParam.type = 200
    oParam.direction = 1
    oParam.size = 50
    oParam.value = status
    oCmd.Parameters.Append oParam
    oCmd.Execute
    As you can see, it creates "ADODB.Connection" and "ADODB.Command" objects. Everything works as intended here.
    Now, I'm trying to convert this VBScript to a Powershell script.
    Here's what I have so far with my PowerShell Script (non-working, but no errors):
    $job_name = $args[0]
    $status = $args[1]
    $descrip = $args[2]
    write-host "Job Name = " $job_name
    write-host "Status = " $status
    write-host "Description = " $descrip
    #Create an object of type: ADODB class: Connection
    $objConn = New-Object -com "ADODB.Connection"
    #Create Connection String
    $connString = "File name=C:\UDLs\TEST.udl"
    #Open the connection
    $objConn.open($connString)
    #Command Object
    $oCmd = New-Object -com "ADODB.Command"
    #Assign DB connection To Command
    $oCmd.ActiveConnection = $objConn
    #Set Command text
    $oCmd.CommandText = "SYSTEM.JOB.INSERT_JOB"
    #Set Command Type
    $oCmd.CommandType = 4
    #Create parameter list For Command
    #Job name Parameter
    $oParam1 = $oCmd.CreateParameter("job_name_val")
    $oParam1.type = 200
    $oParam1.direction = 1
    $oParam1.size = 255
    $oParam1.value = $job_name
    #Append parameter list
    $oCmd.Parameters.Append($oParam1)
    #Description Parameter
    $oParam2 = $oCmd.CreateParameter("description")
    $oParam2.type = 200
    $oParam2.direction = 1
    $oParam2.size = 4000
    $oParam2.value = $descrip
    #Append parameter list
    $oCmd.Parameters.Append($oParam2)
    #Status Parameter
    $oParam3 = $oCmd.CreateParameter("status_val")
    $oParam3.type = 200
    $oParam3.direction = 1
    $oParam3.size = 50
    $oParam3.value = $status
    #Append parameter list
    $oCmd.Parameters.Append($oParam3)
    #Command Execution
    $oCmdX = $oCmd.Execute
    write-host $oCmdX
    #Cleanup
    #Set parameters = To NULL
    $oParam1 = $null
    $oParam2 = $null
    $oParam3 = $null
    #Set Command = To NULL
    $oCmd = $null
    #Close DB object
    $objConn.Close()
    So, not too many changes with the syntax, but it doesn't actually send the ADODB Command to the Database. I have also tried hardcoding the connection string, but no luck there either. Am I not using the right syntax with the Command object? I am fairly new
    to both of these languages, so I appreciate any help/suggestions you can offer!
    Thank you,
    Brian

    Thanks JRV.
    I am now getting this error (at least some feedback from Powershell now):
    Exception calling "Open" with "1" argument(s): "[Microsoft][ODBC Driver Manager
    ] Data source name not found and no default driver specified"
    At C:\temp\JobMon.ps1:21 char:14
    + $objConn.open <<<< ($connString)
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ComMethodTargetInvocation
    The thing is, it shouldn't be using a Microsoft driver. It should be using the Oracle Client driver (which I have installed and tested successfully using TNSPing).
    Do I need to declare some sort of "using System.Data.OracleClient namespace" like in C++? How would I do that in Powershell?
    Thanks again,
    Brian

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

  • Is it possible to catch a PowerShell script output when an exit code is setted?

    Hi,
    i'm using TEO 2.1.2 with the hotfixes from 1 to 12 already installed and i have a problem using the "Execute Windows PowerShell Script" in reading the output of a PowerShell script if an exit code is expressly setted . For example if i try to execute a script like:
    the output given by the activity is only 0 (like the exit code).
    This is a problem if i use a script with multiple exit codes corrisponding to different kind of situations and different outputs like the following:
    if($flag -eq "0")
       Write-output "Hello"
       exit 0
    elseif ($flag -eq "1")
       Write-output "Error 1"
       exit 1
    else
      Write-output "Error 2"
      exit 2
    or if i call an executable which exit codes i want to identify by a readable description.
    Anyone knows a way to solve this issue?
    Thanks a lot,
    bye.
    Giulio

    Thanks Shaun,
    i was already looking toward this kind of approch, but i was also curious if there was a different way of doing this.
    Anyway just a little annotation about your line of code, in Tidal 2.1.2 at least, Write-host doesn't work right, echo or Write-Output are fine but Write-host seems to be ignored. To the following script:
    the output is
    Maybe i'm missing something. Regarding an upgrade, as a devoloper i'd really like to try the improvement of the new version but this is not a decision I can make.
    Thank you,
    bye.
    Giulio

  • Error with SMLets in an Orchestrator called PowerShell Scripts

    Hi!
    This is likely so simple I am overlooking the problem but...
    I have a "Run .Net Script" activity in an Orchestrator 2012 SP1 Runbook.  It calls SMLets.  The issue is it runs in the PowerShell ISE on the Runbook server without issue.  It runs in the Runbook Tester just fine.  But if I
    call the runbook with the PowerShell script, it errors out on the first call the a SMLets provide cmdlet.
    A Few Detail:
    We loaded the latest SMLets from CodePlex.  We can use the cmdlets in both the 32-bit and 64-bit environments.
    The very first line of the PowerShell script is: Import-Module SMLets
    The first SM cmdlet is: $class = Get-SCSMClass System.WorkItem.Activity.ReviewActivity$
    The Runbook Containing the PowerShell Script:
    And lastly, the Event of the error thrown:
    In trying to make this work we have tried to run the script remotely on the SCSM server (New-PSSession and Invoke-Command).  Failures due to rights on the SCSM server. 
    My opinion is the issue is a rights issue but we cannot find the difference between any of the accounts testing/debugging and the Orchestrator Runbook Service account.  I can run the PowerShell and the Runbook Tester when logged on as the
    Orchestrator Runbook Service account.  It works until I have to call the runbook with the PowerShell Activity.  It just like my Account.  We've even set the account on the security tab of the Invoke Runbook Activity.
    Is there something I've overlooked?  Something in the install of the SMLets, maybe? A clue?  Help?
    If nothing else, thank you for letting me voice my issue onto the 'Net.  Maybe someone else has been down this road and can tell me where the off-ramp is.  ;-)
    Ray Watters,
    Chicago, IL

    Hi,
    also make sure that your PS scriptruns with Windows PowerShell (x86) (32bit)
    http://www.sc-orchestrator.eu/index.php/scoblog/64-using-64bit-powershell-cmdlets-in-the-run-net-script-activity-from-orchestrator
    or with PowerShell V2
    http://www.sc-orchestrator.eu/index.php/scoblog/102-running-powershell-30-with-the-run-net-script-activity
    Regards,
    Stefan
    www.sc-orchestrator.eu ,
    Blog sc-orchestrator.eu

  • Workflow does not start when PowerShell Script is run from Task Scheduler

    I have a PS script that updates an item in a SP2010 list so that a workflow will be started.  When I run the PS script manually from the PS window on the server it resides, the script runs flawlessly.  If I set a scheduled task on the same server
    to run the script with the same credentials as are being used in the PS window, the script runs, updated the info on the list, but DOES NOT start the workflow.  As we know, SPD workflows cannot be started by anonymous or system accounts.  It is as
    if the task scheduler adds a bit of information that makes the SP2010 list think the information was updated by one of these accounts even though the field in the list for the item being updated shows the correct account.
    HELP!!!
    D

    Hi,
    The issue might be related to the script or schedule task settings your configured. You’d better check the settings.
    For example, which option do you set to run the scheduled task? You may select “Run whether user is logged on or not” instead of “run only when user is logged on” as shown in this article:
    http://blog.pointbeyond.com/2010/04/23/run-powershell-script-using-windows-server-2008-task-scheduler/
    Hope it helps.
    Best Regards,
    Sally Tang

  • PowerShell Scripting help to combine two scripts

    I have a script that helps automate virtual server builds.  The script creates a specification document which is used to perform the actual builds.
    # Spec-And-Build.ps1 - Loops through a directory and performs an
    # end to end specification generation and build on each request in that directory
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)]
        [string]$RequestDir,
        [Parameter(Mandatory=$true)]
        [string]$SpecDir,
        [Parameter(Mandatory=$false)]
        [pscredential]$Credential_CPR,
        [Parameter(Mandatory=$false)]
        [pscredential]$Credential_VDC,
        [Parameter(Mandatory=$false)]
        [pscredential]$Credential_Admin
    if (!$Credential_CPR) {
        $Credential_CPR = Get-Credential -Message "CPR Domain Credentials."
        if (!$Credential_CPR.UserName.ToUpper().StartsWith("CPR\")) {
            $Credential_CPR = New-Object pscredential(
                ("CPR\" + $Credential_CPR.UserName), $Credential_CPR.Password)
    if (!$Credential_VDC) {
        $Credential_VDC = Get-Credential -Message "VDC Domain Credentials."
        if (!$Credential_VDC.UserName.ToUpper().StartsWith("VDC\")) {
            $Credential_VDC = New-Object pscredential( `
                ("VDC\" + $Credential_VDC.UserName), $Credential_VDC.Password)
    if (!$Credential_Admin) {
        $Credential_Admin = Get-Credential -UserName "Administrator or root" `
            -Message "Enter the Administrator or root password for the new VM. The user name here will be ignored"
    .\Gen-VMSpec-Many.ps1 -RequestDir $RequestDir -SpecDir $SpecDir -Credential_VDC $Credential_VDC
    $caption = "Continue Build"
    $message = "Please validate the generated specification files in $SpecDir - Then click Continue to start build"
    $opContinue = new-Object System.Management.Automation.Host.ChoiceDescription "&Continue","help"
    $opAbort = new-Object System.Management.Automation.Host.ChoiceDescription "&Abort","help"
    $choices = [System.Management.Automation.Host.ChoiceDescription[]]($opContinue,$opAbort)
    $answer = $host.ui.PromptForChoice($caption,$message,$choices,0)
    if ($answer -eq 0) {
        .\Build-VM-Many.ps1 -SpecDir $SpecDir -Credential_CPR $Credential_CPR -Credential_VDC $Credential_VDC -Credential_Admin $Credential_Admin
    } else {
        Write-Host "Build step aborted, run Build-VM-Many.ps1 manually to continue."
    This script works well.  Now I need to add a section that adds Active Directory groups to the built servers from the spec document.  I found this script which also works well:
    # Create local group on the local or a remote computer 
    Write-Host -foregroundcolor Yellow 'Admin Privileges Required!' 
    $computerName = Read-Host 'Enter computer name or press <Enter> for localhost' 
    $localGroupName = Read-Host 'Enter local group name' 
    $description = Read-Host 'Enter description for new local group' 
    if ($computerName -eq "") {$computerName = "$env:computername"} 
    if([ADSI]::Exists("WinNT://$computerName,computer")) { 
        $computer = [ADSI]"WinNT://$computerName,computer" 
        $localGroup = $computer.Create("group",$localGroupName) 
        $localGroup.SetInfo() 
        $localGroup.description = [string]$description 
        $localGroup.SetInfo() 
    My question is, how do I make one script from the two?  I am very new to PowerShell scripting.

    Here are the instructions on how to use PowerShell:
    http://technet.microsoft.com/en-us/scriptcenter/dd793612.aspx
    Your question is vague and is asking for someone to do this for you.  It is better if you do it yourself and post back with specific questions.
    In the end you have to write and debug the scripts. We will not do this for you but we will answer questions.
    ¯\_(ツ)_/¯

  • Need some help in building a PowerShell Script

    I am in the process of setting up continuous self-auditing on a set of computers that are on a Domain. My company has a restriction on use of USB devices as well as CDs/DVDs. The domain pushes patches but we have been seeing some users that are using (or
    trying to) the network without becoming a part of the domain. My aim is to run a PowerShell script periodically (say, hourly) on each computer on the domain and dump certain parameters to XML / XHTML and then load these onto a web-server that can display the
    results in a (sort of) dashboard to flag anomalies like unauthorised USB use etc.
    I know there must be some commercial products for this but the boss says "No" to a purchase. 
    Am I on the right track or do I need to change my approach? Also, is there a starting scirpt available somewhere so that I can study it for techniques? My major problem is the display part. I am able to dump it into XML and (sort of ) format it but how do
    I collate the data and display it as a web-page is what is bothering me. Help would be deeply appreciated.

    @JRV:
    Users don't have to be domain administrators
    to be able to install software. Local admin is more than enough. ie: I am no admin in the domain of my customer but am allowed to install software
    Although I agree with you, in the sense it would be easier to restrict the users, it doesn't mean that a company has to do it that way; and it certainly doesn't represent the intelligence of an individual. 
    @SarabRSingh:
    What you are asking for is a lot of work, to get the script right (considering the special demands, ie. AV update checking is different depending on the SW) and it might require a lot of resources on the client.
    From what you describe, you want to prevent any USB/Optical Media use. You should consider Group Policies to manage that. http://technet.microsoft.com/en-us/library/bb742376.aspx
    The only part I would script (based on my work environment) is the checking of AV updates (gets tricky because our SW has a hard time forcing the user to update when connected by VPN).
    user log in / out --> group policy: logon/off script writing appending timestamp to a file
    has he/she used any USB device --> if you want to block it: GPO, if you only want to track it: powershell
    Get-WmiObject Win32_USBControllerDevice
    has any new application / software been installed: restrict installation completely with user permissions or: http://social.technet.microsoft.com/Forums/en-US/f4dc8ab9-370b-423e-b65d-1fa46fa9bcc4/powershell-script-to-remotely-audit-computers-on-lan?forum=ITCG
    was the AV: no idea on what you are using (maybe: http://serverfault.com/questions/129611/how-to-detect-when-antivirus-is-out-of-date-with-powershell
    OS updated: WSUS http://technet.microsoft.com/en-us/library/cc708519(v=ws.10).aspx
    If you found this post helpful, please "Vote as Helpful". If it answered your question, remember to "Mark as Answer"
    MCC & PowerShell enthusiast
    http://oliver.lipkau.net/blog

  • How to Compare 2 CSV file and store the result to 3rd csv file using PowerShell script?

    I want to do the below task using powershell script only.
    I have 2 csv files and I want to compare those two files and I want to store the comparision result to 3rd csv file. Please look at the follwingsnap:
    This image is csv file only. 
    Could you please any one help me.
    Thanks in advance.
    By
    A Path finder 
    JoSwa
    If a post answers your question, please click &quot;Mark As Answer&quot; on that post and &quot;Mark as Helpful&quot;
    Best Online Journal

    Not certain this is what you're after, but this :
    #import the contents of both csv files
    $dbexcel=import-csv c:\dbexcel.csv
    $liveexcel=import-csv C:\liveexcel.csv
    #prepare the output csv and create the headers
    $outputexcel="c:\outputexcel.csv"
    $outputline="Name,Connection Status,Version,DbExcel,LiveExcel"
    $outputline | out-file $outputexcel
    #Loop through each record based on the number of records (assuming equal number in both files)
    for ($i=0; $i -le $dbexcel.Length-1;$i++)
    # Assign the yes / null values to equal the word equivalent
    if ($dbexcel.isavail[$i] -eq "yes") {$dbavail="Available"} else {$dbavail="Unavailable"}
    if ($liveexcel.isavail[$i] -eq "yes") {$liveavail="Available"} else {$liveavail="Unavailable"}
    #create the live of csv content from the two input csv files
    $outputline=$dbexcel.name[$i] + "," + $liveexcel.'connection status'[$i] + "," + $dbexcel.version[$i] + "," + $dbavail + "," + $liveavail
    #output that line to the csv file
    $outputline | out-file $outputexcel -Append
    should do what you're looking for, or give you enough to edit it to your exact need.
    I've assumed that the dbexcel.csv and liveexcel.csv files live in the root of c:\ for this, that they include the header information, and that the outputexcel.csv file will be saved to the same place (including headers).

  • Using WEBDAV in a Windows PowerShell script

    Hello,
    I am trying to write a Windows PowerShell script to copy a file from my SharePoint site to a DB repository folder using a WEBDAV link.  I am not getting it to work.
    When I copy from SharePoint to SharePoint it works.  I have used my credentials on the script which has the authorizations but it still isn't working.  The response error is a 500 Internal Server error.
    Any ideas?
    Has anyone done this before?
    Thanks,
    Matt

    This is not a solution but more an extra tool to help you find a solution....
    You could download and install the Portal Drive to see what actions/commands are used to communicate via webdav to the KM repository.
    Cheers,
    B

  • How to give readonly Permission rights to 1000 users with button using powershell script?

    $site = Get-SPSite
    -Identity "http://mysite/"
    $user = Get-SPUser
    -Identity "mydomain\myuser"
    -Web $site.RootWeb
    $assignment = New-Object
    Microsoft.SharePoint.SPRoleAssignment($user)
    $role = $site.RootWeb.RoleDefinitions[[Microsoft.SharePoint.SPRoleType]::Reader]
    $assignment.RoleDefinitionBindings.Add($role);
    foreach ($web in $site.AllWebs)
        if ($web.HasUniquePerm)
            $web.RoleAssignments.Add($assignment)
    With above script I can give Readonly permission to the users...but at a time I can give permission to only one user...Actually 1000 users requires these permissionMy requirement is I will have a textbox and a button.I will enter username in textbox
    and when i clicked button the required permission should be assigned to the user given in the textbox...can you please tell how can i achieve this........how make to run powershell script when button is clicked.

    Hello,
    Instead of applying security to user level, it'll be better to create a SharePoint group where you will add the users. and use the outof the box interface to give permissions.
    and for your button, just add the direct link to add user
    http://serverurl/_layouts/15/aclinv.aspx?GroupId=7&IsDlg=1 
    replacing the group ID by the id of your new group (you can see it in the url when your are in the group)
    Best regards, Christopher.
    Blog |
    Mail
    Please remember to click "Mark As Answer" if a post solves your problem or
    "Vote As Helpful" if it was useful.
    Why mark as answer?

  • How to set volume using Powershell script?

    I would like to know on how to set volume under Window 7 Home 64 bits system using Powershell script.
    Such as 8000 levels as default
    Does anyone have any suggestions?
    Thanks in advance for any suggestions
    Thanks in advance for any suggestions

    Try this.
    Function Set-SpeakerVolume{
    Param (
    [switch]$min,
    [switch]$max,
    [int]$Percent
    $wshShell = new-object -com wscript.shell
    If ($min){
    1..50 | % {$wshShell.SendKeys([char]174)}
    ElseIf ($max){
    1..50 | % {$wshShell.SendKeys([char]175)}
    elseif($Percent){
    1..50 | % {$wshShell.SendKeys([char]174)}
    1..($Percent/2) |% {$wshShell.SendKeys([char]175)}
    Else{
    $wshShell.SendKeys([char]173)
    This works in Windows 8.1.
    Stolen / Modified from
    http://blogs.technet.com/b/heyscriptingguy/archive/2013/07/28/weekend-scripter-cheesy-script-to-set-speaker-volume.aspx, which took me 20 seconds of (apparently) lucky searching.
    Karl
    When you see answers and helpful posts, please click Vote As Helpful, Propose As Answer, and/or Mark As Answer.
    My Blog: Unlock PowerShell
    My Book:
    Windows PowerShell 2.0 Bible
    My E-mail: -join ('6F6C646B61726C406F75746C6F6F6B2E636F6D'-split'(?<=\G.{2})'|%{if($_){[char][int]"0x$_"}})

  • Windows 8.1 - How to enable "Require additional authentication at startup" for bitlocker using powershell script?

    I need help to do this using powershell scripts on Windows 8.1?
    OS : Windows 8.1 Enterprise
    TPM Chip : None
    Enabling bitlocker on OS drive with a password at boot time is a 2 step process.
    1) Edit the Group Policy (gpedit.msc) - Administrative Templates -> Windows Components -> BitLocker Drive Encryption -> Operating System Drives ->
    Require additional authentication at startup -> Allow bitlocker without a compatible TPM
    ref : http://www.7tutorials.com/how-enable-bitlocker-without-tpm-chip-windows-7-windows-8
    2) Enable Bitlocker on c driver using manage bitlocker snapin
    I need help to do this using powershell scripts?
    I researched on the forums but ran into an issue.
    I found that Group policy commandlets can be used to do step 1.  
    I am getting the error : "ins have been registered for Windows PowerShell version 4" when I try to do the following in windows 8.1
    Add-PSSnapin GroupPolicy
    Import-Module GroupPolicy -Verbose

    Hi TinkerBotFoo,
    I’m writing to just check in to see if the suggestions were helpful. If you need further help,
    please feel free to reply this post directly so we will be notified to follow it up.
    If you have any feedback on our support, please click here.
    Best Regards
    Anna
    TechNet Community Support
    We
    are trying to better understand customer views on social support experience, so your participation in this
    interview project would be greatly appreciated if you have time.
    Thanks for helping make community forums a great place.

  • 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

  • [JS CS3] ScriptUI button wants to be clicked twice

    Hi I created a sample scriptUI dlg with three buttons: res = ]"dialog { \ ]s: StaticText { text:'Chosissez une période:' }\ ]]period: DropDownList { alignment:'center' }, \ ]]s: StaticText { text:'Chosissez un fichier:' }\ ]]files: DropDownList { ali

  • Help! to set up Oracle 9i RAC on Redhat Linux 8.0

    hello, we are setting up Oracle 9i RAC on Redhat Linux 8.0. The problem we are having is at the point of sharing the raw partition and mounting the raw partition via nfs. so we have two dell systems called linuxa and linuxb. the partitions are made o

  • OSB File Transport Polling Interval

    HI, I need to know can i set File Polling Interval in milliseconds in OSB 11g. By default is in Seconds.... http://docs.oracle.com/cd/E14571_01/doc.1111/e15867/proxy_services.htm#i1276922 i have found a link which says we can set in milliseconds also

  • Sales order and Production order status

    Hi Colleagues, We need to use sales order status functionality, so that when sales manager set status , for example, "dont produce" a production order can not be released. Has any one dealt with that? Thank you.

  • How to make page stay in the middle of browser window?

    I was messing around with the CSS code that changes your pages width based on browser window but it really distorted my graphics badly so that was out, but is there a way to set it so everything stays centered? I 'assumed' I could just set all my tab