Pass Y as by default on powershell script

Hi,i Am creating a power shell script for import-spweb but it is asking for Y,N and A for all, but i need to pass by default "Y" without asking me to enter and perform the job...Please help.

set-executionpolicy is a security change. i dont think it will work on it.
If this helped you resolve your issue, please mark it Answered. You can reach me through http://itfreesupport.com/

Similar Messages

  • Powershell script set timezone and default calendar rights to NonEditingAuthor

    Hi
    How do I make a Powershell script setting Timezone to da-dk and calendar rights on default user to NonEditingAuthor for all users?
    Best regards
    MSISOM

    For product specificquestions yoou should post in the product forum.  In this case in teh O365 forum.
    I conencted in to see how easy it is to find the info.  On query was all it took.
    Set-MailboxRegionalConfiguration  --->>
    http://technet.microsoft.com/en-us/library/dd351103(v=exchg.150).aspx
    Searhing O65 is the best place to find your answers.  Post here when you have an issue of how to use PowerShell.
    http://community.office365.com/en-us/f/613/t/29986.aspx
    ¯\_(ツ)_/¯

  • 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

  • Powershell script calling batch file, how to "echo" or otherwise pass in two or more values asked for by batch file

    I've been having a lot of problems trying to get an old batch file we have laying around, to run from my powershell script. The batch file actually asks for two inputs from the user. I've managed to put together a powershell that echos a response, but of
    course, that only will answer one of the prompts. As usual, I've simplified things here to get my testing done. The batch file looks like this:
    @ECHO OFF
    SET /P CUSTID=Customer Number:
    SET /P DBCOUNT=Number of Live Databases:
    ECHO Customer Id was set to : %CUSTID%
    ECHO Database Count was set to : %DBCOUNT%
    Two inputs, two echos to verify values have been set. Now, the powershell looks like this:
    Param(
     [string]$ClientADG,
        [string]$ClientDBCount,
        [scriptblock]$Command
    $ClientADG = '1013'
    $ClientDBCount = '2'
    $Response = $ClientADG + "`r`n" + $ClientDBCount
    $Command = 'Invoke-Command -ComputerName localhost -ScriptBlock {cmd /c "echo ' + $ClientADG + ' | E:\Scripts\Setup\Company\DatabaseSetupTest.bat"}'
    powershell -command $Command
    Output looks like:
    Customer Number: Number of Live Databases: Customer Id was set to : 1013
    Database Count was set to :
    As expected, as I'm only passing in one value. I can't figure out how to get a second value passed in for the second prompt. Instead of $ClientADG, I tried to mash the two value together in the $Response variable with a cr/lf or a cr or a lf in between,
    but no go there either. The first input gets set to the second value, and second input is blank still. In the essence of time, I need to get this batch file called from Powershell to get some folks productive while I actually rewrite what the batch file does
    in another powershell, so it can be integrated into other things. (I'm automating what a bunch of people spend hours doing into multiple scripts and eventually one BIG script so they can focus on doing their real jobs instead).
    How do I get this right in powershell? I don't want to modify the batch file at all at this point, just get it running from the powershell.
    Thanks in advance!
    mpleaf

    It's a "simple" test so I can figure out how to get the arguments passed from ps to bat. The bat file looks like this:
    @ECHO OFF
    SET CUSTID = %1
    SET DBCOUNT = %2
    ECHO Customer Id was set to : %CUSTID%
    ECHO Database Count was set to : %DBCOUNT%
    That's it. The PS script looks like this:
    Invoke-Command-ComputerName myserver-ScriptBlock{cmd/c"E:\Scripts\Setup\Company\DatabaseSetupTest.bat
    1013 2"}
    That's it. The bat file exists on "myserver", and I'm getting the echo back, but without the values.
    mpleaf

  • Run PowerShell script from C# writing to input pipe

    Hello,
    I am trying to run a PowerShell script from C# (I have no control over what's in the script). The script may have a prompt like "Press enter to continue". So my goal is:
    1. Get text output from the script (easy, many examples available)
    3. If output contains "Press enter to continue", write a blank line to the running script's pipe to make it finish its job and quit
    4. If output does contain that prompt, just let it exit by itself without sending any input
    Note that commands in this PS script also try to get at script's file path, so I can't read script from file and pass it as text. It has to be executed as a script so it knows where it's located.
    I have done this with .exes and batch files before. All you do in that case is process.StandardInput.WriteLine() which "types" enter into the input stream of script you are trying to control. But this does not work with Power Shell. How do I do this?
    I have tried using PS object model like so:
    using (Pipeline pipeline = runspace.CreatePipeline())
    Command command = new Command(scriptPS, true, true);
       pipeline.Commands.Add(command);
       pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
       pipeline.Input.Write("\n");
       Collection<PSObject> psresults = pipeline.Invoke();   //...
    But I get an error because the script prompts:
    "A command that prompts the user failed because the host program or the command type does not support user interaction. Try a host program that supports user interaction, such as the Windows PowerShell Console or Windows PowerShell ISE, and remove prompt-related
    commands from command types that do not support user interaction, such as Windows PowerShell workflows."
    I also tried using Process, and running PowerShell with -File switch to execute the script, then write to StandardInput with C#. I get no errors then, but the input is ignored and doesn't make it to PowerShell.
    Please help!

    No man, what kind of answer is that? You should have left it unanswered rather than waste people's time like this. I already seen those links before I posted my question. They address the issue of specifying script parameters, but not
    writing to the input pipe.
    Fortunately I did figure this out by writing a custom script host for PowerShell. Anyone interested can read about this in detail on MSDN (fortunately simple material with samples you can copy paste as I did, so this solution takes little time to implement).
    Implement PSHost interface. Nothing special here, just paste directly from MSDN sample and modify their SetShouldExit function definition to contain just a "return;". Here's the relevant link:
    http://msdn.microsoft.com/en-us/library/windows/desktop/ee706559(v=vs.85).aspx
    Implement PSHostUserInterface interface. This is the ticket to solving this problem
    (see below). Here's the MSDN link:
    http://msdn.microsoft.com/en-us/library/windows/desktop/ee706584(v=vs.85).aspx
    Implement PSHostRawUserInterface. This may not be required (not sure) but I did anyway. Nearly a direct paste from MSDN:
    http://msdn.microsoft.com/en-us/library/windows/desktop/ee706601(v=vs.85).aspx
    So, there are two PSHostUserInterface function implementations that are of particular interest. First is Prompt (read header comment to see why):
    /// <summary>
    /// When script attempts to get user input, we override it and give it input programmatically,
    /// by looking up within promptInput's dictionary<string,string> or lineInput array.
    /// PromptInput dictionary is mapped by input prompt (for example, return "" in response to "Press ENTER to continue")
    /// LineInput is a regular array, and each time the script wants to prompt for input we return the next line in that array;
    /// this works much like piping inputs from a regular text file in DOS command line.
    /// </summary>
    /// <param name="caption">The caption or title of the prompt.</param>
    /// <param name="message">The text of the prompt.</param>
    /// <param name="descriptions">A collection of FieldDescription objects that
    /// describe each field of the prompt.</param>
    /// <returns>Throws a NotImplementedException exception.</returns>
    public override Dictionary<string, PSObject> Prompt(string caption, string message, System.Collections.ObjectModel.Collection<FieldDescription> descriptions)
    Dictionary<string, PSObject> ret = new Dictionary<string, PSObject>();
    foreach (FieldDescription desc in descriptions)
    if (this.promptInput.Count != 0)
    ret[desc.Name] = new PSObject(this.promptInput[desc.Name] + "\r\n");
    else if (this.lineInput != null && this.currentLineInput >= 0 && this.currentLineInput < this.lineInput.Length)
    ret[desc.Name] = new PSObject(this.lineInput[this.currentLineInput++] + "\r\n");
    else
    if (desc.DefaultValue == null)
    ret[desc.Name] = new PSObject("\r\n");
    else
    ret[desc.Name] = new PSObject(desc.DefaultValue);
    return ret;
    Next is PromptForChoice. Here I opted to always return the default choice, but you could rewrite it to read from somewhere to "simulate" reading from input pipe just like the function above:
    public override int PromptForChoice(string caption, string message, System.Collections.ObjectModel.Collection<ChoiceDescription> choices, int defaultChoice)
            return defaultChoice;
    Last but not least, here's a ReadLine implementation (again read header comment):
    /// <summary>
    /// If the LineInput is set, "read" the next line from line input string array, incrementing line pointer/// </summary>
    /// <returns>The characters that are entered by the user.</returns>
    public override string ReadLine()
    if (this.lineInput != null && this.currentLineInput >= 0 && this.currentLineInput < this.lineInput.Length)
    return this.lineInput[this.currentLineInput++];
    else
    return Console.ReadLine();
    Both are exposed as properties:
    /// <summary>
    /// Gets or sets the input pipe override
    /// </summary>
    public string Input
    get
    return string.Join("\n", this.lineInput);
    set
    if (value != null)
    this.lineInput = value.Split('\n');
    this.currentLineInput = 0;
    else
    this.lineInput = null;
    /// <summary>
    /// Gets or sets input pipe override for named prompts
    /// </summary>
    public Dictionary<string, string> PromptInput
    get
    return this.promptInput;
    set
    this.promptInput = value;
    And finally, here's how the whole shebang is used:
    /// <summary>
    /// Runs a powershell script, with input pipe arguments
    /// </summary>
    /// <param name="script">Path of the script to execute, or script text</param>
    /// <param name="inline">Whether or not to execute script text directly, or execute script from path</param>
    /// <param name="unrestricted">Whether or not to set unrestricted execution policy</param>
    /// <param name="parameters">Parameters to pass to the script command line</param>
    /// <param name="inputOverride">Input to pass into the script's input pipe</param>
    /// <param name="inputOverrideName">Input to pass into the script's input pipe, to each prompt by label</param>
    /// <returns>Output lines</returns>
    public static string PowerShell(string script, bool inline, bool unrestricted = false, Dictionary<string, string> parameters = null, string inputOverride = null, Dictionary<string, string> inputOverrideByName = null)
    string output = null;
    ScriptHost host = new ScriptHost();
    (host.UI as ScriptHostUserInterface).Input = inputOverride;
    (host.UI as ScriptHostUserInterface).PromptInput = inputOverrideByName;
    using (Runspace runspace = RunspaceFactory.CreateRunspace(host))
    runspace.Open();
    if (unrestricted)
    RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace);
    runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
    using (Pipeline pipeline = runspace.CreatePipeline())
    if (inline)
    pipeline.Commands.AddScript(script);
    else
    Command command = new Command(script, true, true);
    foreach (KeyValuePair<string, string> param in parameters)
    command.Parameters.Add(param.Key, param.Value);
    pipeline.Commands.Add(command);
    pipeline.Commands.Add("Out-String");
    pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
    Collection<PSObject> psresults = pipeline.Invoke();
    var sb = new StringBuilder();
    foreach (PSObject obj in psresults)
    sb.AppendLine(obj.ToString());
    output = sb.ToString();
    pipeline.Dispose();
    runspace.Close();
    return (host.UI as ScriptHostUserInterface).Output + "\r\n" + output;
    As you can see, I also did some magic with the .Output property. That just accumulates lines of text output by the script in every WriteXXX function implemented in your custom PSHostUserInterface. The end result of all this, is that if you have a script
    that has prompts, choices or reads from standard input, you can execute the script within the context of your custom script host written as above, to control precisely what strings are passed to it in response to prompts.
     

  • How can I setup a scheduled task to run a Powershell Script delivered as a Group Policy Preference

    I have a Powershell script I want to run only once when a user logs onto their system. This script would move all the PST files from the Local drive and the Home drive to a folder location within the users profile. I wanted to run this as a Windows 7 Scheduled Task using Group Policy Preferences. How can I get this to happen short of a logon script? I have updated all the machines to WMF 4.0 so could I use a Scheduled Job instead? I wanted to run the script as the logon user but elevated.#Start Outlook and Disconnect attached PST files.
    $Outlook = New-Object -ComObject Outlook.Application
    $namespace = $outlook.getnamespace("MAPI")
    $folder = $namespace.GetDefaultFolder("olFolderInbox")
    $explorer = $folder.GetExplorer()
    $explorer.Display()
    $myArray= @()
    $outlook.Session.Stores | where{ ($_.FilePath -like'*.PST') } | foreach{[array]$myArray+= $_.FilePath}
    for
    ($x=0;$x-le$myArray.length-1;$x++)
    $PSTPath= $myArray[$x]
    $PST= $namespace.Stores | ?{$_.FilePath -like$PSTPath}
    $PSTRoot= $PST.GetRootFolder() #Get Root Folder name of PST
    $PSTFolder= $Namespace.Folders.Item($PSTRoot.Name) #Bind to PST for disconnection
    $Namespace.GetType().InvokeMember('RemoveStore',[System.Reflection.BindingFlags]::InvokeMethod,$null,$Namespace,($PSTFolder)) #Disconnect .PST
    #Move All PST files to the default location while deleting the PST files from their original location.
    $SourceList = ("$env:SystemDrive", "$env:HOMEDRIVE")
    $Destination = ("$env:USERPROFILE\MyOutlookFiles")
    (Get-ChildItem -Path $SourceList -Recurse -Filter *.PST) | Move-Item -Destination $Destination
    #Attach all PST files from the default location.
    Add-type -assembly "Microsoft.Office.Interop.Outlook" | out-null
    $outlook = new-object -comobject outlook.application
    $namespace = $outlook.GetNameSpace("MAPI")
    dir “$env:USERPROFILE\MyOutlookFiles\*.pst” | % { $namespace.AddStore($_.FullName) }

    Mike,
    I do not understand what appears to be a regular expression above. I did add the PowerShell script to the HKCU RunOnce Key as suggested.
    Windows Registry Editor Version 5.00
    C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -noprofile -sta -WindowStyle Hidden -ExecutionPolicy RemoteSigned -File "C:\scripts\Windows PowerShell\Move-PST.ps1"
     I'm delivering this using Group Policy Preferences. It seems to fail or time out when run because the behavior is different if I run the script from within the PowerShell IDE. I added the parameters to the script and will try it again in the morning.

  • Trying to deploy a batch or powershell script unsuccessful

    I've deployed a .cmd file out that contains a WMI script to uninstall all instances of an application called "VirtViewer". The script looks like this:
    taskkill /F /IM remote-viewer.exe /T
    wmic product where "name like 'VirtViewer%%'" call uninstall /nointeractive
    exit /B %EXIT_CODE%
    Previously, I had used MSI product codes for the uninstall, and got the same result. My original problem, is that there are currently 9 different versions of this app out there, so i am ripping them all out and replacing with 1 version. Installing over an
    old version does not overwrite the older one, it instead installs a new instance.
    Reading through the execmgr.log on the client, everything looks as it should.
    The end result, is that nothing happens. I had originally set the program to run as hidden, but then changed it to normal but still do not see it run. The application is right where i left it, untouched. If i run the script locally it works fine, but not
    when deployed. Am i missing something??
    <![LOG[Service startup.]LOG]!><time="16:09:31.647+300" date="01-12-2015" component="execmgr" context="" type="1" thread="248" file="execmgr.cpp:135">
    <![LOG[A user has logged on.]LOG]!><time="16:09:43.507+300" date="01-12-2015" component="execmgr" context="" type="1" thread="4256" file="execreqmgr.cpp:4911">
    <![LOG[Requesting content from CAS for package VNT00018 version 21]LOG]!><time="16:11:13.649+300" date="01-12-2015" component="execmgr" context="" type="1" thread="124" file="contentaccesshelper.cpp:246">
    <![LOG[Policy arrived for parent package VNT00018 program Uninstall Script]LOG]!><time="16:11:13.649+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2528" file="execreqmgr.cpp:6893">
    <![LOG[Raising client SDK event for class CCM_Program, instance CCM_Program.PackageID="VNT00018",ProgramID="Uninstall Script", actionType 6l, value NULL, user NULL, session 4294967295l, level 0l, verbosity 30l]LOG]!><time="16:11:13.665+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2528" file="event.cpp:405">
    <![LOG[Successfully created a content request handle {B2BA42EE-5988-47F4-BF44-ADAAC975994B} for the package VNT00018 version 21]LOG]!><time="16:11:13.665+300" date="01-12-2015" component="execmgr" context="" type="1" thread="124" file="contentaccesshelper.cpp:331">
    <![LOG[Program Uninstall Script change to state STATE_ADVANCED_DOWNLOAD content available]LOG]!><time="16:11:13.665+300" date="01-12-2015" component="execmgr" context="" type="2" thread="124" file="executionrequest.cpp:3663">
    <![LOG[Execution Request for advert VNT20014 package VNT00018 program Uninstall Script state change from NotExist to AdvancedDownload]LOG]!><time="16:11:13.665+300" date="01-12-2015" component="execmgr" context="" type="1" thread="124" file="executionrequest.cpp:501">
    <![LOG[Raising client SDK event for class CCM_Program, instance CCM_Program.PackageID="VNT00018",ProgramID="Uninstall Script", actionType 1l, value , user NULL, session 4294967295l, level 0l, verbosity 30l]LOG]!><time="16:11:13.665+300" date="01-12-2015" component="execmgr" context="" type="1" thread="124" file="event.cpp:405">
    <![LOG[Raising event:
    [SMS_CodePage(437), SMS_LocaleID(1033)]
    instance of SoftDistProgramOfferReceivedEvent
    AdvertisementId = "VNT20014";
    ClientID = "GUID:E306FF26-C884-4E36-9C03-C19523A17F40";
    DateTime = "20150112211113.665000+000";
    MachineName = "VM-WIN7-MIKE";
    ProcessID = 1788;
    SiteCode = "VNT";
    ThreadID = 2528;
    ]LOG]!><time="16:11:13.665+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2528" file="event.cpp:715">
    <![LOG[Mandatory execution requested for program Uninstall Script and advertisement VNT20014]LOG]!><time="16:11:13.680+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2564" file="execreqmgr.cpp:3527">
    <![LOG[Creating mandatory request for advert VNT20014, program Uninstall Script, package VNT00018]LOG]!><time="16:11:13.680+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2564" file="execreqmgr.cpp:3653">
    <![LOG[An existing MTC token was not supplied, using ExecutionRequest's Id as MTC token and this execution request is the owner of resultant MTC task.]LOG]!><time="16:11:13.696+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2564" file="executionrequest.cpp:8942">
    <![LOG[Request a MTC task for execution request of package VNT00018, program Uninstall Script with request id: {D52026A7-5735-402B-868C-EF9791656512}]LOG]!><time="16:11:13.696+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2564" file="executionrequest.cpp:8966">
    <![LOG[Execution Request for advert VNT20014 package VNT00018 program Uninstall Script state change from WaitingDependency to Ready]LOG]!><time="16:11:13.712+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2564" file="executionrequest.cpp:501">
    <![LOG[MTC task with id {D52026A7-5735-402B-868C-EF9791656512}, changed state from 0 to 4]LOG]!><time="16:11:13.712+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="execreqmgr.cpp:6288">
    <![LOG[Raising client SDK event for class CCM_Program, instance CCM_Program.PackageID="VNT00018",ProgramID="Uninstall Script", actionType 1l, value , user NULL, session 4294967295l, level 0l, verbosity 30l]LOG]!><time="16:11:13.712+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2564" file="event.cpp:405">
    <![LOG[MTC signaled SWD execution request with program id: Uninstall Script, package id: VNT00018 for execution.]LOG]!><time="16:11:13.743+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="execreqmgr.cpp:6406">
    <![LOG[Sending ack to MTC for task with id: {D52026A7-5735-402B-868C-EF9791656512}]LOG]!><time="16:11:13.743+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="executionrequest.cpp:9005">
    <![LOG[Executing program VirtViewerUninstall.cmd in Admin context]LOG]!><time="16:11:13.743+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="executionrequest.cpp:3239">
    <![LOG[Execution Request for advert VNT20014 package VNT00018 program Uninstall Script state change from Ready to NotifyExecution]LOG]!><time="16:11:13.743+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="executionrequest.cpp:501">
    <![LOG[Raising client SDK event for class CCM_Program, instance CCM_Program.PackageID="VNT00018",ProgramID="Uninstall Script", actionType 1l, value , user NULL, session 4294967295l, level 0l, verbosity 30l]LOG]!><time="16:11:13.759+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="event.cpp:405">
    <![LOG[Checking content location C:\Windows\ccmcache\1c for use]LOG]!><time="16:11:13.774+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="executioncontext.cpp:1663">
    <![LOG[Successfully selected content location C:\Windows\ccmcache\1c]LOG]!><time="16:11:13.774+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="executioncontext.cpp:1719">
    <![LOG[Executing program as a script]LOG]!><time="16:11:13.774+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="executionengine.cpp:82">
    <![LOG[Successfully prepared command line "C:\Windows\ccmcache\1c\VirtViewerUninstall.cmd"]LOG]!><time="16:11:13.774+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="scriptexecution.cpp:650">
    <![LOG[Command line = "C:\Windows\ccmcache\1c\VirtViewerUninstall.cmd", Working Directory = C:\Windows\ccmcache\1c\]LOG]!><time="16:11:13.774+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="scriptexecution.cpp:352">
    <![LOG[Running "C:\Windows\ccmcache\1c\VirtViewerUninstall.cmd" with 32bitLauncher]LOG]!><time="16:11:13.774+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="scriptexecution.cpp:370">
    <![LOG[Created Process for the passed command line]LOG]!><time="16:11:13.852+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="scriptexecution.cpp:513">
    <![LOG[Raising event:
    [SMS_CodePage(437), SMS_LocaleID(1033)]
    instance of SoftDistProgramStartedEvent
    AdvertisementId = "VNT20014";
    ClientID = "GUID:E306FF26-C884-4E36-9C03-C19523A17F40";
    CommandLine = "\"C:\\Windows\\ccmcache\\1c\\VirtViewerUninstall.cmd\"";
    DateTime = "20150112211113.852000+000";
    MachineName = "VM-WIN7-MIKE";
    PackageName = "VNT00018";
    ProcessID = 1788;
    ProgramName = "Uninstall Script";
    SiteCode = "VNT";
    ThreadID = 2164;
    UserContext = "NT AUTHORITY\\SYSTEM";
    WorkingDirectory = "C:\\Windows\\ccmcache\\1c\\";
    ]LOG]!><time="16:11:13.852+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="event.cpp:715">
    <![LOG[Raised Program Started Event for Ad:VNT20014, Package:VNT00018, Program: Uninstall Script]LOG]!><time="16:11:13.852+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="executioncontext.cpp:459">
    <![LOG[Raising client SDK event for class CCM_Program, instance CCM_Program.PackageID="VNT00018",ProgramID="Uninstall Script", actionType 1l, value NULL, user NULL, session 4294967295l, level 0l, verbosity 30l]LOG]!><time="16:11:13.852+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="event.cpp:405">
    <![LOG[Raising client SDK event for class CCM_Program, instance CCM_Program.PackageID="VNT00018",ProgramID="Uninstall Script", actionType 1l, value , user NULL, session 4294967295l, level 0l, verbosity 30l]LOG]!><time="16:11:13.868+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="event.cpp:405">
    <![LOG[MTC task with id {D52026A7-5735-402B-868C-EF9791656512}, changed state from 4 to 5]LOG]!><time="16:11:13.884+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="execreqmgr.cpp:6288">
    <![LOG[Program exit code 0]LOG]!><time="16:11:17.571+300" date="01-12-2015" component="execmgr" context="" type="1" thread="4128" file="scriptexecution.cpp:676">
    <![LOG[Looking for MIF file to get program status]LOG]!><time="16:11:17.571+300" date="01-12-2015" component="execmgr" context="" type="1" thread="4128" file="executionstatus.cpp:282">
    <![LOG[Script for Package:VNT00018, Program: Uninstall Script succeeded with exit code 0]LOG]!><time="16:11:17.571+300" date="01-12-2015" component="execmgr" context="" type="1" thread="4128" file="executionstatus.cpp:262">
    <![LOG[Raising event:
    [SMS_CodePage(437), SMS_LocaleID(1033)]
    instance of SoftDistProgramCompletedSuccessfullyEvent
    AdvertisementId = "VNT20014";
    ClientID = "GUID:E306FF26-C884-4E36-9C03-C19523A17F40";
    DateTime = "20150112211117.571000+000";
    MachineName = "VM-WIN7-MIKE";
    PackageName = "VNT00018";
    ProcessID = 1788;
    ProgramName = "Uninstall Script";
    SiteCode = "VNT";
    ThreadID = 4128;
    UserContext = "NT AUTHORITY\\SYSTEM";
    ]LOG]!><time="16:11:17.587+300" date="01-12-2015" component="execmgr" context="" type="1" thread="4128" file="event.cpp:715">
    <![LOG[Raised Program Success Event for Ad:VNT20014, Package:VNT00018, Program: Uninstall Script]LOG]!><time="16:11:17.587+300" date="01-12-2015" component="execmgr" context="" type="1" thread="4128" file="executioncontext.cpp:483">
    <![LOG[Execution is complete for program Uninstall Script. The exit code is 0, the execution status is Success]LOG]!><time="16:11:17.587+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2564" file="execreqmgr.cpp:4165">
    <![LOG[Raising client SDK event for class CCM_Program, instance CCM_Program.PackageID="VNT00018",ProgramID="Uninstall Script", actionType 10l, value Result:TRUE ,SDKCallerId:, user NULL, session 4294967295l, level 0l, verbosity 30l]LOG]!><time="16:11:17.602+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2564" file="event.cpp:405">
    <![LOG[Requesting MTC to delete task with id: {D52026A7-5735-402B-868C-EF9791656512}]LOG]!><time="16:11:17.618+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2564" file="executionrequest.cpp:9036">
    <![LOG[MTC task with id: {D52026A7-5735-402B-868C-EF9791656512} deleted successfully.]LOG]!><time="16:11:17.618+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2564" file="executionrequest.cpp:9065">
    <![LOG[Raising client SDK event for class CCM_Program, instance CCM_Program.PackageID="VNT00018",ProgramID="Uninstall Script", actionType 1l, value , user NULL, session 4294967295l, level 0l, verbosity 30l]LOG]!><time="16:11:17.618+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2564" file="event.cpp:405">

    I just tried using powershell to accomplish the same task, and got the same result. Script ran fine, but nothing resulted. 0 errors in the execmgr.log on the client.
    Program options:
    Command Line: Powershell.exe -executionpolicy Bypass -file .\VirtUninstall.ps1
    the powershell script looks like this:
    $app = Get-WmiObject -Class Win32_Product | Where-Object {$_.Name -match "VirtViewer*"}
    $app.Uninstall()
    exit /B
    Again, the script runs great when launched locally, but not wehen deployed

  • An unknown error occurred while executing the PowerShell script:

    Hello all,
    Not the most descriptive title, granted. I'm hoping this may prompt the next version toprovide additional valuable content.
    Kindly requesting any help on this problem. I'm running VMM 2012 R2 version 3.2.7668
    When I try to look at properties of an existing Private Cloud, I get this error, only if I "look" at certain attributes. If I stay away from the specific attributes, everything is hunky dory. For reasons unknown, after I get this error, I have
    to exit and go back into VMM in order to get anything else to run.
    The text in the error dialogue box is not entirely applicable because I was connected to the VMM server and will connect again, when I exit/relaunch.
    An unknown error occurred while executing the PowerShell script:
    The connection to the VMM management server scvmm2.mmmmmm.com was lost.
    Ensure that scvmm2.mmmmmm.com is online and that you can access the server remotely from your computer. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. Or, you can ensure that the Virtual Machine Manager service is started
    on scvmm2.mmmmmm.com. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. If the command fails again because of a connection failure, restart the Virtual Manager service and then try the operation again.
    Try the operation again. If the issue persists, contact Microsoft Help and Support.
    ID: 27235
    This is what I get in Events
    Warning 4/9/2015 3:27:04 PM PowerShell (Microsoft-Windows-PowerShell) 4100 Executing Pipeline
    Log Name:      Microsoft-Windows-PowerShell/Operational
    Source:        Microsoft-Windows-PowerShell
    Date:          4/9/2015 3:27:04 PM
    Event ID:      4100
    Task Category: Executing Pipeline
    Level:         Warning
    Keywords:      None
    User:          mmmmmm\paufra
    Computer:      tools-francis.mmmmmm.com
    Description:
    Error Message = The connection to the VMM management server scvmm2.mmmmmm.com was lost. (Error ID: 1610)
    Ensure that scvmm2.mmmmmm.com is online and that you can access the server remotely from your computer. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. Or, you can ensure that the Virtual Machine Manager service is started
    on scvmm2.mmmmmm.com. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. If the command fails again because of a connection failure, restart the Virtual Manager service and then try the operation again.
    Fully Qualified Error ID = 1610,Microsoft.SystemCenter.VirtualMachineManager.Cmdlets.GetSCReplicationGroupCmdlet
    Recommended Action = Ensure that scvmm2.mmmmmm.com is online and that you can access the server remotely from your computer. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. Or, you can ensure that the Virtual Machine Manager
    service is started on scvmm2.mmmmmm.com. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. If the command fails again because of a connection failure, restart the Virtual Manager service and then try the operation again.
    Context:
            Severity = Warning
            Host Name = Default Host
            Host Version = 4.0
            Host ID = 94963cd4-5979-4786-9da2-c8814de8c7c3
            Host Application = C:\Program Files\Microsoft System Center 2012 R2\Virtual Machine Manager\Bin\VmmAdminUI.exe
            Engine Version = 4.0
            Runspace ID = 359d7a46-3752-4929-8c09-0de4152d10e4
            Pipeline ID = 16
            Command Name = Get-SCReplicationGroup
            Command Type = Cmdlet
            Script Name =
            Command Path =
            Sequence Number = 91
            User = mmmmmm\paufra
            Shell ID = Microsoft.PowerShell
    User Data:
    Event Xml:
    <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
      <System>
        <Provider Name="Microsoft-Windows-PowerShell" Guid="{A0C1853B-5C40-4B15-8766-3CF1C58F985A}" />
        <EventID>4100</EventID>
        <Version>1</Version>
        <Level>3</Level>
        <Task>106</Task>
        <Opcode>19</Opcode>
        <Keywords>0x0</Keywords>
        <TimeCreated SystemTime="2015-04-09T22:27:04.993655700Z" />
        <EventRecordID>285</EventRecordID>
        <Correlation ActivityID="{48059811-1A63-41E1-9057-7498D0E4FC20}" />
        <Execution ProcessID="2344" ThreadID="4076" />
        <Channel>Microsoft-Windows-PowerShell/Operational</Channel>
        <Computer>tools-francis.mmmmmm.com</Computer>
        <Security UserID="S-1-5-21-4008432563-1984933819-4238309236-2721" />
      </System>
      <EventData>
        <Data Name="ContextInfo">        Severity = Warning
            Host Name = Default Host
            Host Version = 4.0
            Host ID = 94963cd4-5979-4786-9da2-c8814de8c7c3
            Host Application = C:\Program Files\Microsoft System Center 2012 R2\Virtual Machine Manager\Bin\VmmAdminUI.exe
            Engine Version = 4.0
            Runspace ID = 359d7a46-3752-4929-8c09-0de4152d10e4
            Pipeline ID = 16
            Command Name = Get-SCReplicationGroup
            Command Type = Cmdlet
            Script Name =
            Command Path =
            Sequence Number = 91
            User = mmmmmm\paufra
            Shell ID = Microsoft.PowerShell
    </Data>
        <Data Name="UserData">
        </Data>
        <Data Name="Payload">Error Message = The connection to the VMM management server scvmm2.mmmmmm.com was lost. (Error ID: 1610)
    Ensure that scvmm2.mmmmmm.com is online and that you can access the server remotely from your computer. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. Or, you can ensure that the Virtual Machine Manager service is started
    on scvmm2.mmmmmm.com. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. If the command fails again because of a connection failure, restart the Virtual Manager service and then try the operation again.
    Fully Qualified Error ID = 1610,Microsoft.SystemCenter.VirtualMachineManager.Cmdlets.GetSCReplicationGroupCmdlet
    Recommended Action = Ensure that scvmm2.mmmmmm.com is online and that you can access the server remotely from your computer. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. Or, you can ensure that the Virtual Machine Manager
    service is started on scvmm2.mmmmmm.com. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. If the command fails again because of a connection failure, restart the Virtual Manager service and then try the operation again.
    </Data>
      </EventData>
    </Event>

    Hi Sir,
    First , please try to run the VMM configuration analyzer on that computer :
    http://www.microsoft.com/en-us/download/details.aspx?id=41555
    In addition , please try to use "VMMTrace" mentioned in following article to collect trace log and find some useful information :
    http://blogs.technet.com/b/jonjor/archive/2011/01/07/vmmtrace-simplified-scvmm-tracing.aspx
    Best Regards,
    Elton Ji
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact [email protected] .

  • Trouble adding leading zeros to numbers in PowerShell script

    I am new to PowerShell scripting (so have mercy on me please!), and I'm trying to write a script that takes simplified, menu-based user input to create a folder on the network named based on a month number and the year. The month must be expressed as a two-digit
    number, but I'm trying to make it simple enough that the user only needs to input a one-digit number (for the first nine months of the year) and have the script add the leading zero (for example, if a user inputs the number "2" for February, the
    script will output "02").
    Here is a portion of my script:
    # Get current year
    $year = Get-Date -Format yyyy
    # Provide menu of months for user to choose from
    Write-Host "Choose the name of the month for the folder you want to create."
    Write-Host "1. January"
    Write-Host "2. February"
    Write-Host "3. March"
    Write-Host "4. April"
    Write-Host "5. May"
    Write-Host "6. June"
    Write-Host "7. July"
    Write-Host "8. August"
    Write-Host "9. September"
    Write-Host "10. October"
    Write-Host "11. November"
    Write-Host "12. December"
    Write-Host " "
    Do {
    $mNum = Read-Host "Select the number of the month (1 - 12): "
    # Convert the menu item to the month name
    switch ($mNum)
    1 {$month = "January"}
    2 {$month = "February"}
    3 {$month = "March"}
    4 {$month = "April"}
    5 {$month = "May"}
    6 {$month = "June"}
    7 {$month = "July"}
    8 {$month = "August"}
    9 {$month = "September"}
    10 {$month = "October"}
    11 {$month = "November"}
    12 {$month = "December"}
    default {"Invalid entry. Please select a number from 1 - 12 (without the trailing period)."}
    # Validate user input. Current code is cumbersome; try to find more elegant method.
    While ($mNum -ne 1 -and $mNum -ne 2 -and $mNum -ne 3 -and $mNum -ne 4 -and $mNum -ne 5 -and `
    $mNum -ne 6 -and $mNum -ne 7 -and $mNum -ne 8 -and $mNum -ne 9 -and $mNum -ne 10 -and `
    $mNum -ne 11 -and $mNum -ne 12)
    # Add leading zeros to month number
    $fNum = "{0:D2}" -f $mNum
    Write-Host $fNum
    When I run it, I don't get the leading zero. However, when I create a very basic script, it seems to work:
    $mNum = 3
    $fNum = "{0:D2}" -f $mNum
    Write-Host $fNum
    Can anyone offer any suggestions as to what I might be doing wrong?
    Also, if anyone has a suggestion on how to better validate the user input (making sure they enter a number between 1 and 12), I would appreciate that as well.

    .NET formatting is a complicated subject
    http://msdn.microsoft.com/en-us/library/26etazsy(v=vs.110).aspx#FormatStrings
    I'm not sure how all that documentation applies when you attempt to format a value that is already a string.
    In general, formatting is described as "Formatting is the process of converting an instance of a class,
    structure, or enumeration value to its string representation".  If it is already a string I'm not sure what to expect.
    For example,
    <# C: #> '3',3,'03',03,'003',003 | % { "{0:D2}" -f $_ }
    3
    03
    03
    03
    003
    03
    <# C: #>

  • Powershell Script to create "custom" Document Library

    I have a powershell script which creates a Document Library for every user in AD.
    This works, but rather than using the default Document Library I want it use a custom Document Library.  However this isnt working.
    My script to create the default Document Library is this...
    [System.Reflection.Assembly]::Load("Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")
    $site = new-object Microsoft.SharePoint.SPSite("http://servername/sitename");
    $siteweb = $site.OpenWeb();
    $webs = $siteweb.Webs;
    $strFilter = "(&(objectCategory=User)(name=accountname))"
    $objDomain = New-Object System.DirectoryServices.DirectoryEntry
    $objSearcher = New-Object System.DirectoryServices.DirectorySearcher
    $objSearcher.SearchRoot = $objDomain
    $objSearcher.PageSize = 1000
    $objSearcher.Filter = $strFilter
    $objSearcher.SearchScope = "Subtree"
    $colProplist = "samaccountname"
    foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)}
    $colResults = $objSearcher.FindAll()
    foreach ($objResult in $colResults)
    $objItem = $objResult.Properties; $objItem.samaccountname
    $listTemplate = [Microsoft.SharePoint.SPListTemplateType]::DocumentLibrary
    $listId = $siteweb.Lists.Add($objItem.samaccountname, "", $listtemplate);
    $list = $siteweb.Lists.GetList($listId, $true);
    $roleDef = $siteweb.RoleDefinitions.GetByType("Contributor");
    $user = "domain\" + $objItem.samaccountname;
    $rolAssign = new-object Microsoft.SharePoint.SPRoleAssignment($user, "email", "name", "notes");
    $rolAssign.RoleDefinitionBindings.Add($roleDef);
    if(!$list.HasUniqueRoleAssignments)
    {$list.BreakRoleInheritance($true);}
    for ($i = $list.roleAssignments.Count - 1; $i -gt -1; $i--)
    { $list.RoleAssignments.Remove($i) }
    $list.RoleAssignments.Add($rolAssign);
    $list.Update();
    Now I have a custom Document Library named "TESTLIB" so if I substitute the line:
    $listTemplate = [Microsoft.SharePoint.SPListTemplateType]::DocumentLibrary
    with
    $listTemplate = [Microsoft.SharePoint.SPListTemplateType]::TESTLIB
    Then it errors with this...
    How can I script powershell to create a "custom" Document Library?
    Thanks

    The below link should help you in creating custom document library using powershell
    http://blogs.technet.com/b/heyscriptingguy/archive/2010/09/23/use-powershell-cmdlets-to-manage-sharepoint-document-libraries.aspx
    Vinod H
    Thanks for the link but I cant see anything to assist creating a custom library?  Was there something in paticular you saw?

  • Exchange PowerShell script to get mailbox properties of user from a CSV file

    Hi Team,
    I've a CSV file with alias of numerous users and I want to get their mailbox sizes and other properties. These users are dispersed in various databases of same Exchange organization.
    Need a Powershell Script, Any help?
    Muhammad Nadeem Ahmed Sr System Support Engineer Premier Systems (Pvt) Ltd T. +9221-2429051 Ext-226 F. +9221-2428777 M. +92300-8262627 Web. www.premier.com.pk

    You can use this and modify it to what you need. Output to a file (IE: Export-CSV "path to file"
    If you need more specifics let me know. This one is for one user at a time but can be used to read a CSV file.
    # Notifies the user a remote session needs to be started
    Write-Host "Get a users mailbox size" -fore yellow -back red;
    Write-Host "Please wait while a remote session started" -fore red -back yellow;
    # Import a remote session with exchange
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://exchangeservername/Powershell/ -Authentication Kerberos
    Import-PSSession $Session
    Do {
    # Prompts user for a name
    $name = Read-Host "Enter a username"
    # Get the mailbox statistics for that user
    Get-MailboxStatistics $name | fl totalitemsize, storagelimitstatus, totaldeleteditemsize | out-default
    # Give the user a choice to test another or EXIT
    $Output = Read-Host "Press Y to continue or ENTER to exit"
    # Ends the program if the user does not press Y
    Until ($Output -ne "Y")
    HossFly, Exchange Administrator

  • PowerShell script : Directory object not found error in Get-ADGroupMember

    I am new in powershell scripting. I am writing a script to add users in different AD Groups. while doing so I do the following:
    Check if the user already exist in the group:
    $mbr_exist = Get-ADGroupMember $grpname | Where-Object {$_.SamAccountName -eq $sam}
    If user does not exist then add the user to the group.
    When I manually run the script its runs flawless, without any errors. But when I schedule the script to run it gives an error as follows:
    3/30/2015 8:32:15 AM Directory object not foundAt + $mbr_exist = Get-ADGroupMember $grpname | Where-Object {$_.SamAc ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~ Error at Line:$mbr_exist = Get-ADGroupMember
    $grpname | Where-Object {$_.SamAccountName -eq $sam}
    The strange thing is the user for which it throws the error is present in the group.I am not sure why this error is occurring when scheduled. Can any one please help? All the suggestions will be appreciated
    Note: (The script is scheduled using Windows Task Scheduler)
    try
    # # Initialize the variables we will use
    $status = 'false'
    $drivename = "H:"
    $sysdate = Get-Date -UFormat "%m_%d_%Y"
    $foldername = $drivename + "\Script_Result\PowershellData"+ $sysdate
    $backup_folder = "$foldername\AD_Groups_Backup"
    $updatedGroup = "$foldername\Updated_AD_Groups_LogFiles"
    $LogFilePath = "$foldername\Log_Update_ADGroups"+$sysdate+".log"
    # # Initialize the arrays we will use
    $GroupArray = @()
    # # maintain log of program startup
    $logdate = get-date
    $logdate.ToString() + "`tStarted script to Update AD user Groups..." | Out-File -FilePath $LogFilePath
    # # Create a sub folder to store the backup files
    $fileexist = Test-Path $backup_folder -PathType Container
    if($fileexist -ne 'False')
    New-Item -ItemType Directory $backup_folder
    # # Create a sub folder to store Updated AD group Log files
    $fileexist = Test-Path $updatedGroup -PathType Container
    if($fileexist -ne 'False')
    New-Item -ItemType Directory $updatedGroup
    # # Take back up of the AD groups data
    Get-ADGroupMember -Identity "Group1" | Export-csv "$backup_folder\Group1_BackUP$sysdate.csv"
    Get-ADGroupMember -Identity "Group2" | Export-csv "$backup_folder\Group1_BackUP$sysdate.csv"
    Get-ADGroupMember -Identity "Group3" | Export-csv "$backup_folder\Group1_BackUP$sysdate.csv"
    Get-ADGroupMember -Identity "Group4" | Export-csv "$backup_folder\Group1_BackUP$sysdate.csv"
    (an so on..... 11 such groups )
    # # Fetch AD Users data
    $ADusers = Get-ADUser -filter {(EmployeeNumber -gt 1) -and (EmployeeNumber -ne "N/A") -and (Enabled -eq $true)} -Properties * | Sort-Object -Property EmployeeNumber
    $ADusers.Count
    foreach($u in $ADusers)
    $sam = $u.SamAccountName
    $empnum = $u.EmployeeNumber
    $mgr = $u.mgr
    $fsal = $u.'fsalary-Hourly'
    $comp = $u.Company
    $ofc = $u.Office
    Write-Host "$sam : $empnum : $mgr :$fsal : $comp : $ofc" -ForegroundColor Yellow
    $GroupArray = @()
    # # Check if the user fits in any of the 11 scenarios
    if($comp -eq "US")
    # scenario 7
    write-host "7. Add to US Employees"
    $GroupArray += "US Employees"
    if($mgr -eq "Y")
    Write-Host "1. ADD to US MAnagers"
    $group = "US Managers"
    $GroupArray += $group
    if(($fsal -eq "Hourly") -and ($ofc -ne "Canton"))
    Write-Host "3. Add to US Hourly (excluding Canton)"
    $group = "US Hourly (excluding Canton)"
    $GroupArray += $group
    if(($fsal -eq "Hourly") -and ($ofc -eq "Canton"))
    write-host "4. Add to US Canton Hourly"
    $group = "US Canton Hourly"
    $GroupArray += $group
    if(($fsal -eq "Salaried") -and ($ofc -eq "Corporate" -or $ofc -eq "Landis Lakes 1" -or $ofc -eq "Landis Lakes 2"))
    Write-Host "5. Add to US Salaried Corporate"
    $group = "US Salaried Corporate"
    $GroupArray += $group
    if(($fsal -eq "Salaried") -and ($ofc -ne "Corporate" -and $ofc -ne "Landis Lakes 1" -and $ofc -ne "Landis Lakes 2"))
    Write-Host "6. Add to US Salaried Plant"
    $group = "US Salaried Plant"
    $GroupArray +=$group
    elseif($comp -eq "canada")
    # scenario 9
    write-host "9. Canada Employees"
    $GroupArray += "Canada Employees"
    if($mgr -eq "Y")
    Write-Host "2. Add to Canada Managers"
    $group = "Canada Managers"
    $GroupArray += $group
    if($fsal -eq "Hourly")
    Write-Host "10. Add to Canada Hourly"
    $group = "Canada Hourly"
    $GroupArray += $group
    if($fsal -eq "Salaried")
    Write-Host "11. Add to Canada Salaried Plant"
    $group = "Canada Salaried Plant"
    $GroupArray += $group
    elseif($ofc -eq "Corporate" -or $ofc -eq "Landis Lakes 1" -or $ofc -eq "Landis Lakes 2")
    Write-Host "8. Add to Corporate Employees"
    $GroupArray += "Corporate Employees"
    write-host "Final Group List" -ForegroundColor Green
    $grplen = $GroupArray.Length
    #$GroupArray
    $grplen
    for($i= 0; $i -lt $grplen; $i++)
    $grpname = $GroupArray[$i]
    write-host "$sam will be added to Group : $grpname" -ForegroundColor Magenta
    # # Check if the user is already present in the Group
    $mbr_exist = Get-ADGroupMember $grpname | Where-Object {$_.SamAccountName -eq $sam}
    if($mbr_exist -eq $null)
    # #Add user to US Managers group
    Add-ADGroupMember -Identity $grpname -Members $sam
    Write-Host "1. User $sam is added to $grpname group" -ForegroundColor Green
    # # documenting the user list that are added to this group
    $grpmbr = New-Object PSObject
    $grpmbr | Add-Member -MemberType NoteProperty -Name "EmployeeNumber" -Value $empnum
    $grpmbr | Add-Member -MemberType NoteProperty -Name "SamAccountName" -Value $sam
    $grpmbr | Add-Member -MemberType NoteProperty -Name "Name" -Value $u.Name
    $grpmbr | Add-Member -MemberType NoteProperty -Name "DistinguishedName" -Value $u.DistinguishedName
    $grpmbr | Add-Member -MemberType NoteProperty -Name "mgr" -Value $mgr
    $grpmbr | Add-Member -MemberType NoteProperty -Name "Company" -Value $comp
    $grpmbr | Add-Member -MemberType NoteProperty -Name "Salary/Hourly" -Value $fsal
    $grpmbr | Add-Member -MemberType NoteProperty -Name "Office" -Value $ofc
    $grpmbr | Add-Member -MemberType NoteProperty -Name "ADGroup" -Value $grpname
    $grpmbr | Export-Csv "$updatedGroup\ADUsers_To_Group($grpname)_$sysdate.csv" -Append -NoTypeInformation
    else
    Write-Host "Member $sam already exist in $grpname group" -ForegroundColor Red
    $logdate = get-date
    $logdate.ToString() + "`tCompleted script to Update Update AD Groups..." | Out-File -FilePath $LogFilePath -Append
    $status = 'true'
    return $status
    catch
    $err_lineno = $error[0].InvocationInfo.ScriptLineNumber
    $err_line = $error[0].InvocationInfo.Line
    $ExceptionMessage = $_.Exception.Message
    #$ExceptionMessage
    $error_info = $error[0].ToString() + $error[0].InvocationInfo.PositionMessage
    Write-Host "$error_info " -ForegroundColor Red
    $FailedItem = $_.Exception.ItemName
    if($ExceptionMessage)
    $logdate.ToString() + "`t $error_info " | out-file "$foldername\ErrorLog_Update_AD_Groups$sysdate.log" -append
    "Line Number: $err_lineno . `nError at Line: $err_line" | out-file "$foldername\ErrorLog_Update_AD_Groups$sysdate.log" -append
    #Invoke-Item "C:\ErrorLog.log"
    $status = 'false'
    return $status

    Hi mdkelly, Sorry for such a late reply (due to credential issues).
    I am using Windows task scheduler to schedule the task. I am given the administrator access to the server (Windows Server 2012). So I think I set to run the script under system account.
    My apologies for asking this, am I missing something while scheduling the script through task scheduler?  how to check if the scheduled task is running under who's credentials? How to pass my (admin) credentials, so that the script execution won't face
    a problem? Any suggestion on the above questions will be helpful. (I tried to search on net for the questions but didn't get any conclusive answers)  
    Thanks in advance.

  • 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

  • Calling powershell script from a batch file

    Hello All,
    I have a batch script that calls a powershell script. Before calling the script I set the execution policy to unrestricted, but when it gets to the line that calls the batch script i still get the confirmation in the command window: "Do you want to
    perform this operation" I then have to press Y for the PS script to run and then my batch script finishes.
    Does anyone know the setting I need to change in order to suppress the confirmation?
    Note: this is Windows 8, see code below
    set THIS_DIR=%~dp0
    powershell Set-ExecutionPolicy unrestricted
    powershell %THIS_DIR%MyScript.ps1 "param1"

    I may sound like a jerk but you really want to look at PowerShell.exe /?
    PowerShell[.exe] [-PSConsoleFile <file> | -Version <version>]
        [-NoLogo] [-NoExit] [-Sta] [-Mta] [-NoProfile] [-NonInteractive]
        [-InputFormat {Text | XML}] [-OutputFormat {Text | XML}]
        [-WindowStyle <style>] [-EncodedCommand <Base64EncodedCommand>]
        [-File <filePath> <args>] [-ExecutionPolicy <ExecutionPolicy>]
        [-Command { - | <script-block> [-args <arg-array>]
                      | <string> [<CommandParameters>] } ]
    PowerShell[.exe] -Help | -? | /?
    -PSConsoleFile
        Loads the specified Windows PowerShell console file. To create a console
        file, use Export-Console in Windows PowerShell.
    -Version
        Starts the specified version of Windows PowerShell.
        Enter a version number with the parameter, such as "-version 2.0".
    -NoLogo
        Hides the copyright banner at startup.
    -NoExit
        Does not exit after running startup commands.
    -Sta
        Starts the shell using a single-threaded apartment.
        Single-threaded apartment (STA) is the default.
    -Mta
        Start the shell using a multithreaded apartment.
    -NoProfile
        Does not load the Windows PowerShell profile.
    -NonInteractive
        Does not present an interactive prompt to the user.
    -InputFormat
        Describes the format of data sent to Windows PowerShell. Valid values are
        "Text" (text strings) or "XML" (serialized CLIXML format).
    -OutputFormat
        Determines how output from Windows PowerShell is formatted. Valid values
        are "Text" (text strings) or "XML" (serialized CLIXML format).
    -WindowStyle
        Sets the window style to Normal, Minimized, Maximized or Hidden.
    -EncodedCommand
        Accepts a base-64-encoded string version of a command. Use this parameter
        to submit commands to Windows PowerShell that require complex quotation
        marks or curly braces.
    -File
        Runs the specified script in the local scope ("dot-sourced"), so that the
        functions and variables that the script creates are available in the
        current session. Enter the script file path and any parameters.
        File must be the last parameter in the command, because all characters
        typed after the File parameter name are interpreted
        as the script file path followed by the script parameters.
    -ExecutionPolicy
        Sets the default execution policy for the current session and saves it
        in the $env:PSExecutionPolicyPreference environment variable.
        This parameter does not change the Windows PowerShell execution policy
        that is set in the registry.
    -Command
        Executes the specified commands (and any parameters) as though they were
        typed at the Windows PowerShell command prompt, and then exits, unless
        NoExit is specified. The value of Command can be "-", a string. or a
        script block.
        If the value of Command is "-", the command text is read from standard
        input.
        If the value of Command is a script block, the script block must be enclosed
        in braces ({}). You can specify a script block only when running PowerShell.exe
        in Windows PowerShell. The results of the script block are returned to the
        parent shell as deserialized XML objects, not live objects.
        If the value of Command is a string, Command must be the last parameter
        in the command , because any characters typed after the command are
        interpreted as the command arguments.
        To write a string that runs a Windows PowerShell command, use the format:
            "& {<command>}"
        where the quotation marks indicate a string and the invoke operator (&)
        causes the command to be executed.
    -Help, -?, /?
        Shows this message. If you are typing a PowerShell.exe command in Windows
        PowerShell, prepend the command parameters with a hyphen (-), not a forward
        slash (/). You can use either a hyphen or forward slash in Cmd.exe.
    Hope that helps! Jason

  • 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$_"}})

Maybe you are looking for

  • Data type Enhancement in SPROXY

    HI, We are using standard  software component : SAP SRM 5.5 ... We created some data types in Datatype enhancement and link to the standard Data types. Activated. When we are looking in the SPROXY that Enhance Data type is not vissible.. Our Version

  • Getting HTTP 500 Internal Server Error in JDeveloper 10g Release 3

    Hello, I had run a web page of JSF a month ago with no issues from the server. Now however whnever I try running any page from the IDE, I keep getting following message in the log: [i]Mar 1, 2008 10:06:25 AM com.evermind.server.ApplicationStateRunnin

  • Color balancing not saved

    I cropped a photo and did some color balancing, I did not add any layers, then saved the photo.    However if I view in a photo viewer or just in windows explorer with large icons or print the photo none of the editing, except the cropping, are appli

  • NullPointerException in getHeader() & IMAPMessage

    Hi everyone, My software is running fine 99% of the time, except that I get this error once in a while. I'm using JDK 1.4 and JavaMail 1.2 java.lang.NullPointerException      at com.sun.mail.util.LineInputStream.readLine(LineInputStream.java:56)     

  • Why won't my form work on my iPad?

    I've created a simple form, using Acrobat Pro 9 / LiveCycle Designer on a Windows PC. The form has a few radio buttons, text entry boxes, and a drop-down selection box. It also has place that shows the current date. The form works fine on the PC. I'v