Piping script line in a powershell script

Hi,
I would like piping informations in a powershell script and getting this:
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
[string]$scriptDirectory = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent # Emplacement du script
powershell.exe -executionpolicy bypass -File $scriptDirectory\Vcredist2005_Frv1.ps1 install
=====================================
======================================
My script is looking this:
$var_InterventionManuelle ="c:\temp"
$var_FichierLancementManuelle = "install_Man.ps1"
$var_EmplacementFichierLancementManuelle ="c:\temp\install_Man.ps1"
New-Item -path $var_InterventionManuelle -Name $var_FichierLancementManuelle -type file
Add-Content -path $var_EmplacementFichierLancementManuelle -Value "`nIf (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))"
Add-Content -path $var_EmplacementFichierLancementManuelle -Value "`n{"
Add-Content -path $var_EmplacementFichierLancementManuelle -Value "`n$arguments = ""&" '" + $myinvocation.mycommand.definition + "'""
Add-Content -path $var_EmplacementFichierLancementManuelle -Value "`nStart-Process powershell -Verb runAs -ArgumentList $arguments"
Add-Content -path $var_EmplacementFichierLancementManuelle -Value "`nBreak"
Add-Content -path $var_EmplacementFichierLancementManuelle -Value "`n}"
Add-Content -path $var_EmplacementFichierLancementManuelle -Value "`n[string]$scriptDirectory = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent"
Add-Content -path $var_EmplacementFichierLancementManuelle -Value "`npowershell.exe -executionpolicy bypass -File $scriptDirectory\$var_Scriptactuel install"
It is failing on the first add-content. Where am I wrong? Is it an easier way to do this?
Thanks,
François

Hi,
If all you're trying to do is write all of that to a file, you can do something like this:
$text = @'
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
[string]$scriptDirectory = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent # Emplacement du script
powershell.exe -executionpolicy bypass -File $scriptDirectory\Vcredist2005_Frv1.ps1 install
$text | Out-File .\script.ps1
Here's some information about here-strings:
http://technet.microsoft.com/en-us/library/ee692792.aspx
Don't retire TechNet! -
(Don't give up yet - 13,085+ strong and growing)

Similar Messages

  • 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

  • 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

  • Powershell Script

    Hello,
    Need help with PowerShell. Do you have any powershell script or number of powershell scripts put together to get the following result :
    1.
    Name of all servers (including DB server)
    2. Service Pack level of each (aka. version number).
    3. Count and list of web application URL, site collections, content databases.
    4. List of managed accounts/service accounts used.
    5. List of service applications that are configured/turned on (e.g. Search, User Profile Sync, App Domain, WorkflowManager, Office WebApp, XLS/Visio/Powerpoint/WordAutomation, BCS, etc.)
    6. For EACH site collection:
    a. Actual storage used
    b. # of site at root level
    c. # of subsites (including the root sites) and how many has security inheritance broken.
    d. Deepest sub-site level.
    e. Names of site collection administrators.
    f. # of document libraries
    g. # of Infopath form libraries
    h. # of lists
    i. Top 5 list/library with most item counts.
    j. Number of documents with more than 20 versions.
    7. List of solutions deployed in Central Admin (if possible, all URL of site/subsites they’re activated at)
    8. List of error showing in Central Admin (under “Health Analyzer”)
    9. Current settings of:
    a. Default ULS log location.
    b. Current settings for Search Crawl schedule.
    c. Current setting for User Profile Sync schedule.
    d. Recycle Bin policy.
    e. Site quota templates configured
    Please help
    chirag

    Hi Chirag,
    I have not seen such a exhaustive
    powershell script available, however you may find individual scripts, and you can combine them in a single script.  I think bing would be able to help you in this case :)
    here are some to start with-
    http://talbottcrowell.wordpress.com/2010/10/22/listing-services-on-sharepoint-farm-by-server-using-powershell/
    http://code.msdn.microsoft.com/Find-Large-Lists-of-the-dde321f1
    http://code.msdn.microsoft.com/List-all-published-pages-70f9e356
    SharePoint Management PowerShell scripts
    http://sharepointpsscripts.codeplex.com/
    SharePoint 2013 Web Analytics Data Export to CSV using PowerShell
    http://sp2013wade.codeplex.com/
    Hope this helps!
    Ram - SharePoint Architect
    Blog - SharePointDeveloper.in
    Please vote or mark your question answered, if my reply helps you

  • Powershell script sends e-mail in ISE but not from powershell command line

    I have created a script that generates a report of all users who do not have photos in Active Directory. The script runs and sends an e-mail to a distribution list. It runs fine in ISE, but I cannot run it from command line or as a scheduled task. Any suggestions
    what I am doing wrong?
    #Starts Powershell Snap-In
    Start-Transcript -path c:\Scripts\StaffWithoutPhotos.txt
    add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010 -erroraction silentlyContinue
    $mailboxes = $null
    $mailboxes = @(Get-Mailbox -OrganizationalUnit "Staff User Accounts" -ResultSize Unlimited | Where {$_.HasPicture -eq $False})
    Write-Host $mailboxes
    $report = @()
    foreach ($mailbox in $mailboxes)
    $mbObj = New-Object PSObject
        $mbObj | Add-Member -MemberType NoteProperty -Name "Display Name" -Value $mailbox.DisplayName
        $report += $mbObj
    Write-Host "Diagnostic Output"
    Write-Host "Before Mailbox value check"
    Write-Host $report
    Write-Host "After Mailbox Value check"
    if ($mailboxes -ne $null)
        Write-Host $report
        #Send the report generated to the e-mail list specified above
        $style = "<style>BODY{font-family: Arial; font-size: 10pt;}"
        $style = $style + "TABLE{border: 1px solid black; border-collapse: collapse;}"
        $style = $style + "TH{border: 1px solid black; background: #dddddd; padding: 5px; }"
        $style = $style + "TD{border: 1px solid black; padding: 5px; }"
        $style = $style + "</style>"
        #Start-Sleep -Seconds 5
        $smtpserver = "MAIL.contoso.com"
        $msg = new-object Net.Mail.MailMessage
        $smtp = new-object Net.Mail.SmtpClient($smtpServer)
        $msg.From = "[email protected]"
        $msg.To.Add("[email protected]")
        #$msg.To.Add("[email protected]") #Used for testing
        $msg.Subject = "Staff without Photos report"
        $msg.Body = "This report contains the list of users who do not currently have photos."
        $msg.Body += "<p>"
        $msg.Body += "After photos are available for these users please submit a request to have their accounts updated or send an e-mail to <a href='mailto:[email protected]?Subject=Staff%20Photo%20Updates' target='_top'> [email protected]
    </a> with <b>Staff Photo Updates</b> in the subject."
        $msg.Body += "<p>"
        $msg.Body += "This report runs on Fridays and will only send a message if we have Staff without Photos. For more information please contact your systems administrator."
        $msg.Body += "<p>"
        $msg.Body += $Report | ConvertTo-Html -Head $Style
        $msg.IsBodyHTML = $true
        $smtp.Send($msg)
    Stop-Transcript

    So after researching further and not receiving any more replies I decided to rewrite the script and attempt to use the send-mailmessage function. I have been unable to determine the reason for the original not script not working. We use a very similar script
    to my original code which works to generate a report and e-mail that report as an attachment and it works without any problems.
    After re-writing the script and using the send-mailmessage function I was able to get this report to work as expected. This has now been set up as a scheduled task to run on a server once a week. Here is the final code:
    Start-Transcript -path c:\Scripts\StaffWithoutPhotos.txt
    #Starts Powershell Snap-In
    add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010 -erroraction silentlyContinue
    $mailboxes = $null
    $mailboxes = @(Get-Mailbox -OrganizationalUnit "contoso Staff User Accounts" -ResultSize Unlimited | Where {$_.HasPicture -eq $False})
    Write-Host $mailboxes
    $report = @()
    foreach ($mailbox in $mailboxes)
    $mbObj = New-Object PSObject
        $mbObj | Add-Member -MemberType NoteProperty -Name "Display Name" -Value $mailbox.DisplayName
        $report += $mbObj
    Write-Host "Diagnostic Output"
    Write-Host "Before Mailbox value check"
    Write-Host $report
    Write-Host "After Mailbox Value check"
    if ($mailboxes -ne $null)
        Write-Host $report
        #Send the report generated to the e-mail list specified above
        $style = "<style>BODY{font-family: Arial; font-size: 10pt;}"
        $style = $style + "TABLE{border: 1px solid black; border-collapse: collapse;}"
        $style = $style + "TH{border: 1px solid black; background: #dddddd; padding: 5px; }"
        $style = $style + "TD{border: 1px solid black; padding: 5px; }"
        $style = $style + "</style>"
        $smtpserver = "MAIL.contoso.com"
        $smtpFrom = "[email protected]"
        $smtpTo = "[email protected]
        $messageSubject = "Staff without Photos report"
        $Body = "This report contains the list of users who do not currently have photos."
        $Body += "<p>"
        $Body += "After photos are available for these users please submit a request to the Help Desk to have their accounts updated or send an e-mail to <a href='mailto:[email protected]?Subject=Staff%20Photo%20Updates' target='_top'> [email protected]
    </a> with <b><u>Staff Photo Updates</b></u> in the subject."
        $Body += "<p>"
        $Body += "This report runs on Fridays and will only send a message if we have Staff without Photos. For more information please contact your systems administrator."
        $Body += "<p>"
        $Body += $Report | ConvertTo-Html -Head $Style
        #Send the report
        send-mailmessage -from "$smtpFrom" -to "$smtpTo" -subject "$messageSubject" -body "$Body" -smtpServer "$smtpserver" -BodyAsHtml
    Stop-Transcript

  • SQL Server upgradation Issue : 2012 to 2014. A job step received an error at line 1 in a PowerShell script. The corresponding line is 'set-executionpolicy RemoteSigned -scope process -Force'. Correct the script and reschedule the job.

    Message
    Executed as user: CORPTST\XXXXX. A job step received an error at line 1 in a PowerShell script. The corresponding line is 'set-executionpolicy RemoteSigned -scope process -Force'. Correct the script and reschedule the job. The error information returned
    by PowerShell is: 'Security error.  '.  Process Exit Code -1.  The step failed.
    I receive this error during the sql server job 'syspolicy_purge_history' execution  when sql server got upgraded form SQL Server 2008 to 2014.

    Hi Vishnu,
    According to the error message, it also occurs in SQL Server 2012.  Here is a feedback about the error in the link below.
    https://connect.microsoft.com/SQLServer/feedback/details/754063/sql-server-2012-syspolicy-purge-history-job-step-3-fails-with-security-error
    To resolve this issue, please change the value of the following registry key from ‘RemoteSigned’ to ‘Unrestricted’. For more details, you can review this similar
    blog.
    HKLM\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps120\ExecutionPolicy
    Thanks,
    Lydia Zhang

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

  • Need Help on powershell Script to send mails in different languages

    Hello, Just wanted to use the script below to remind users of password expiry date (I got it from internet New-Passwordreminder.ps1). We have companies in many countries, so the email should be in the language of that country. So since our users are in different
    OU's according to countries, I thought some one could help me edit this script and say if the user is in AB ou then email in english will be sent, if in BC ou then the email will be in Russian....So in the script I will have all the languages I need
    to have written.
    <#
    .SYNOPSIS
      Notifies users that their password is about to expire.
    .DESCRIPTION
        Let's users know their password will soon expire. Details the steps needed to change their password, and advises on what the password policy requires. Accounts for both standard Default Domain Policy based password policy and the fine grain
    password policy available in 2008 domains.
    .NOTES
        Version            : v2.6 - See changelog at
    http://www.ehloworld.com/596
        Wish list      : Better detection of Exchange server
                  : Set $DaysToWarn automatically based on Default Domain GPO setting
                  : Description for scheduled task
                  : Verify it's running on R2, as apparently only R2 has the AD commands?
                  : Determine password policy settings for FGPP users
                  : better logging
        Rights Required   : local admin on server it's running on
        Sched Task Req'd  : Yes - install mode will automatically create scheduled task
        Lync Version    : N/A
        Exchange Version  : 2007 or later
        Author           : M. Ali (original AD query), Pat Richard, Exchange MVP
        Email/Blog/Twitter :
    [email protected]  http://www.ehloworld.com @patrichard
        Dedicated Post   :
    http://www.ehloworld.com/318
        Disclaimer       : You running this script means you won't blame me if this breaks your stuff.
        Info Stolen from   : (original)
    http://blogs.msdn.com/b/adpowershell/archive/2010/02/26/find-out-when-your-password-expires.aspx
                  : (date)
    http://technet.microsoft.com/en-us/library/ff730960.aspx
                : (calculating time)
    http://blogs.msdn.com/b/powershell/archive/2007/02/24/time-till-we-land.aspx
    http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/23fc5ffb-7cff-4c09-bf3e-2f94e2061f29/
    http://blogs.msdn.com/b/adpowershell/archive/2010/02/26/find-out-when-your-password-expires.aspx
                : (password decryption)
    http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/f90bed75-475e-4f5f-94eb-60197efda6c6/
                : (determine per user fine grained password settings)
    http://technet.microsoft.com/en-us/library/ee617255.aspx
    .LINK    
        http://www.ehloworld.com/318
    .INPUTS
      None. You cannot pipe objects to this script
    .PARAMETER Demo
      Runs the script in demo mode. No emails are sent to the user(s), and onscreen output includes those who are expiring soon.
    .PARAMETER Preview
      Sends a sample email to the user specified. Usefull for testing how the reminder email looks.
    .PARAMETER PreviewUser
      User name of user to send the preview email message to.
    .PARAMETER Install
      Create the scheduled task to run the script daily. It does NOT create the required Exchange receive connector.
    .EXAMPLE
      .\New-PasswordReminder.ps1
      Description
      Searches Active Directory for users who have passwords expiring soon, and emails them a reminder with instructions on how to change their password.
    .EXAMPLE
      .\New-PasswordReminder.ps1 -demo
      Description
      Searches Active Directory for users who have passwords expiring soon, and lists those users on the screen, along with days till expiration and policy setting
    .EXAMPLE
      .\New-PasswordReminder.ps1 -Preview -PreviewUser [username]
      Description
      Sends the HTML formatted email of the user specified via -PreviewUser. This is used to see what the HTML email will look like to the users.
    .EXAMPLE
      .\New-PasswordReminder.ps1 -install
      Description
      Creates the scheduled task for the script to run everyday at 6am. It will prompt for the password for the currently logged on user. It does NOT create the required Exchange receive connector.
    #>
    #Requires -Version 2.0
    [cmdletBinding(SupportsShouldProcess = $true)]
    param(
     [parameter(ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true, Mandatory = $false)]
     [switch]$Demo,
     [parameter(ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true, Mandatory = $false)]
     [switch]$Preview,
     [parameter(ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true, Mandatory = $false)]
     [switch]$Install,
     [parameter(ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true, Mandatory = $false)]
     [string]$PreviewUser
    Write-Verbose "Setting variables"
    [string]$Company = "Contoso Ltd"
    [string]$OwaUrl = "https://mail.contoso.com"
    [string]$PSEmailServer = "10.9.0.11"
    [string]$EmailFrom = "Help Desk <[email protected]>"
    [string]$HelpDeskPhone = "(586) 555-1010"
    [string]$HelpDeskURL = "https://intranet.contoso.com/"
    [string]$TranscriptFilename = $MyInvocation.MyCommand.Name + " " + $env:ComputerName + " {0:yyyy-MM-dd hh-mmtt}.log" -f (Get-Date)
    [int]$global:UsersNotified = 0
    [int]$DaysToWarn = 14
    [string]$ImagePath = "http://www.contoso.com/images/new-passwordreminder.ps1"
    [string]$ScriptName = $MyInvocation.MyCommand.Name
    [string]$ScriptPathAndName = $MyInvocation.MyCommand.Definition
    [string]$ou
    [string]$DateFormat = "d"
    if ($PreviewUser){
     $Preview = $true
    Write-Verbose "Defining functions"
    function Set-ModuleStatus {
     [cmdletBinding(SupportsShouldProcess = $true)]
     param (
      [parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $true, HelpMessage = "No module name specified!")]
      [string]$name
     if(!(Get-Module -name "$name")) {
      if(Get-Module -ListAvailable | ? {$_.name -eq "$name"}) {
       Import-Module -Name "$name"
       # module was imported
       return $true
      } else {
       # module was not available (Windows feature isn't installed)
       return $false
     }else {
      # module was already imported
      return $true
    } # end function Set-ModuleStatus
    function Remove-ScriptVariables { 
     [cmdletBinding(SupportsShouldProcess = $true)]
     param($path)
     $result = Get-Content $path | 
     ForEach { if ( $_ -match '(\$.*?)\s*=') {     
       $matches[1]  | ? { $_ -notlike '*.*' -and $_ -notmatch 'result' -and $_ -notmatch 'env:'} 
     ForEach ($v in ($result | Sort-Object | Get-Unique)){  
      Remove-Variable ($v.replace("$","")) -ErrorAction SilentlyContinue
    } # end function Get-ScriptVariables
    function Install {
     [cmdletBinding(SupportsShouldProcess = $true)]
     param()
    http://technet.microsoft.com/en-us/library/cc725744(WS.10).aspx
     $error.clear()
     Write-Host "Creating scheduled task `"$ScriptName`"..."
     $TaskPassword = Read-Host "Please enter the password for $env:UserDomain\$env:UserName" -AsSecureString
     $TaskPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($TaskPassword))
     # need to fix the issue with spaces in the path
     schtasks /create /tn $ScriptName /tr "$env:windir\system32\windowspowershell\v1.0\powershell.exe -psconsolefile '$env:ExchangeInstallPath\Bin\exshell.psc1' -command $ScriptPathAndName" /sc Daily /st 06:00 /ru $env:UserDomain\$env:UserName /rp
    $TaskPassword | Out-Null
     if (!($error)){
      Write-Host "done!" -ForegroundColor green
     }else{
      Write-Host "failed!" -ForegroundColor red
     exit
    } # end function Install
    function Get-ADUserPasswordExpirationDate {
     [cmdletBinding(SupportsShouldProcess = $true)]
     Param (
      [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, HelpMessage = "Identity of the Account")]
      [Object]$accountIdentity
     PROCESS {
      Write-Verbose "Getting the user info for $accountIdentity"
      $accountObj = Get-ADUser $accountIdentity -properties PasswordExpired, PasswordNeverExpires, PasswordLastSet, name, mail
      # Make sure the password is not expired, and the account is not set to never expire
        Write-Verbose "verifying that the password is not expired, and the user is not set to PasswordNeverExpires"
        if (((!($accountObj.PasswordExpired)) -and (!($accountObj.PasswordNeverExpires))) -or ($PreviewUser)) {
         Write-Verbose "Verifying if the date the password was last set is available"
         $passwordSetDate = $accountObj.PasswordLastSet      
          if ($passwordSetDate -ne $null) {
           $maxPasswordAgeTimeSpan = $null
            # see if we're at Windows2008 domain functional level, which supports granular password policies
            Write-Verbose "Determining domain functional level"
            if ($global:dfl -ge 4) { # 2008 Domain functional level
              $accountFGPP = Get-ADUserResultantPasswordPolicy $accountObj
              if ($accountFGPP -ne $null) {
               $maxPasswordAgeTimeSpan = $accountFGPP.MaxPasswordAge
         } else {
          $maxPasswordAgeTimeSpan = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
        } else { # 2003 or ealier Domain Functional Level
         $maxPasswordAgeTimeSpan = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
        if ($maxPasswordAgeTimeSpan -eq $null -or $maxPasswordAgeTimeSpan.TotalMilliseconds -ne 0) {
         $DaysTillExpire = [math]::round(((New-TimeSpan -Start (Get-Date) -End ($passwordSetDate + $maxPasswordAgeTimeSpan)).TotalDays),0)
         if ($preview){$DaysTillExpire = 1}
         if ($DaysTillExpire -le $DaysToWarn){
          Write-Verbose "User should receive email"
          $PolicyDays = [math]::round((($maxPasswordAgeTimeSpan).TotalDays),0)
          if ($demo) {Write-Host ("{0,-25}{1,-8}{2,-12}" -f $accountObj.Name, $DaysTillExpire, $PolicyDays)}
                # start assembling email to user here
          $EmailName = $accountObj.Name      
          $DateofExpiration = (Get-Date).AddDays($DaysTillExpire)
          $DateofExpiration = (Get-Date($DateofExpiration) -f $DateFormat)      
    Write-Verbose "Assembling email message"      
    [string]$emailbody = @"
    <html>
     <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
     </head>
    <body>
     <table id="email" border="0" cellspacing="0" cellpadding="0" width="655" align="center">
      <tr>
       <td align="left" valign="top"><img src="$ImagePath/spacer.gif" alt="Description: $ImagePath/spacer.gif" width="46" height="28" align="absMiddle">
    if ($HelpDeskURL){     
    $emailbody += @" 
       <font style="font-size: 10px; color: #000000; line-height: 16px; font-family: Verdana, Arial, Helvetica, sans-serif">If this e-mail does not appear properly, please <a href="$HelpDeskURL" style="font-weight:
    bold; font-size: 10px; color: #cc0000; font-family: verdana, arial, helvetica, sans-serif; text-decoration: underline">click here</a>.</font>
    $emailbody += @"   
       </td>
      </tr>
      <tr>
    if ($HelpDeskURL){  
    $emailbody += @"
       <td height="121" align="left" valign="bottom"><a href="$HelpDeskURL"><img src="$ImagePath/header.gif" border="0" alt="Description: $ImagePath/header.gif"
    width="655" height="121"></a></td>
    }else{
    $emailbody += @" 
       <td height="121" align="left" valign="bottom"><img src="$ImagePath/header.gif" border="0" alt="Description: $ImagePath/header.gif" width="655" height="121"></td>
    $emailbody += @"
      </tr>
      <tr>
       <td>
        <table id="body" border="0" cellspacing="0" cellpadding="0">
         <tr>
          <td width="1" align="left" valign="top" bgcolor="#a8a9ad"><img src="$ImagePath/spacer50.gif" alt="Description: $ImagePath/spacer50.gif" width="1"
    height="50"></td>
          <td><img src="$ImagePath/spacer.gif" alt="Description: $ImagePath/spacer.gif" width="46" height="106"></td>
          <td id="text" width="572" align="left" valign="top" style="font-size: 12px; color: #000000; line-height: 17px; font-family: Verdana, Arial, Helvetica, sans-serif">
    if ($DaysTillExpire -le 1){
     $emailbody += @"
      <div align='center'>
       <table border='0' cellspacing='0' cellpadding='0' style='width:510px; background-color: white; border: 0px;'>
        <tr>
         <td align='right'><img width='36' height='28' src='$ImagePath/image001b.gif' alt='Description: $ImagePath/image001b.gif'></td> 
         <td style="font-family: verdana; background: #E12C10; text-align: center; padding: 0px; font-size: 9.0pt; color: white">ALERT: You must change your password today or you will be locked out!</td>  
         <td align='left'><img border='0' width='14' height='28' src='$ImagePath/image005b.gif' alt='Description: $ImagePath/image005b.gif'></td>
        </tr>
       </table>
      </div>
    $emailbody += @"
       <p style="font-weight: bold">Hello, $EmailName,</p>
       <p>It's change time again! Your $company password expires in <span style="background-color: red; color: white; font-weight: bold;">&nbsp;$DaysTillExpire&nbsp;</span> day(s), on $DateofExpiration.</p>
       <p>Please use one of the methods below to update your password:</p>
       <ol>
        <li>$company office computers and Terminal Server users: You may update your password on your computer by pressing Ctrl-Alt-Delete and selecting 'Change Password' from the available options. If you use a $company laptop in addition
    to a desktop PC, be sure and read #3 below.</li>
        <li>Remote Outlook Client, Mac, and/or Outlook Web App users: If you only access our email system, please use the following method to easily change your password:</li>
        <ul>
         <li>Log into <a href="$owaurl">Outlook Web App</a> using Internet Explorer (PC) or Safari or Firefox (Mac).</li>
         <li>Click on the Options button in the upper right corner of the page.</li>  
         <li>Select the &quot;Change Password&quot; link to change your password.</li>
         <li>Enter your current password, then your new password twice, and click Save</li>
         <li><span style="font-weight: bold">NOTE:</span> You will now need to use your new password when logging into Outlook Web App, Outlook 2010, SharePoint, Windows Mobile (ActiveSync) devices, etc. Blackberry
    Enterprise Users (BES) will not need to update their password. Blackberry Internet Service (BIS) users will be required to use their new password on their device.</li>
        </ul>
        <li>$company issued laptops: If you have been issued a $company laptop, you must be in a corporate office and directly connected to the company network to change your password. If you also use a desktop PC in the office, you must
    remember to always update your domain password on the laptop first. Your desktop will automatically use the new password.</li>
        <ul>
         <li>Log in on laptop</li>
         <li>Press Ctrl-Alt-Delete and select 'Change Password' from the available options.</li>
         <li>Make sure your workstation (if you have one) has been logged off any previous sessions so as to not cause conflict with your new password.</li>
        </ul>
       </ol>
       <p>Think you've got a complex password? Run it through the <a href="The">http://www.passwordmeter.com/">The Password Meter</a></p>
       <p>Think your password couldn't easily be hacked? See how long it would take: <a href="How">http://howsecureismypassword.net/">How Secure Is My Password</a></p>
       <p>Remember, if you do not change your password before it expires on $DateofExpiration, you will be locked out of all $company Computer Systems until an Administrator unlocks your account.</p>
       <p>If you are traveling or will not be able to bring your laptop into the office before your password expires, please call the number below for additional instructions.</p>
       <p>You will continue to receive these emails daily until the password is changed or expires.</p>
       <p>Thank you,<br />
       The $company Help Desk<br />
       $HelpDeskPhone</p>
    if ($accountFGPP -eq $null){
     $emailbody += @"
       <table style="background-color: #dedede; border: 1px solid black">
        <tr>
         <td style="font-size: 12px; color: #000000; line-height: 17px; font-family: Verdana, Arial, Helvetica, sans-serif"><b>$company Password Policy</b>
          <ul>
           <li>Your password must have a minimum of a $MinPasswordLength characters.</li>
           <li>You may not use a previous password.</li>
           <li>Your password must not contain parts of your first, last, or logon name.</li>
           <li>Your password must be changed every $PolicyDays days.</li>
    if ($PasswordComplexity){
     Write-Verbose "Password complexity"
     $emailbody += @"
           <li>Your password requires a minimum of two of the following three categories:</li>
           <ul>
            <li>1 upper case character (A-Z)</li>
            <li>1 lower case character (a-z)</li>
            <li>1 numeric character (0-9)</li>        
           </ul>
    $emailbody += @"
           <li>You may not reuse any of your last $PasswordHistory passwords</li>
          </ul>
         </td>
        </tr>
       </table>
    $emailbody += @"        
           </td>
           <td width="49" align="left" valign="top"><img src="$ImagePath/spacer50.gif" alt="" width="49" height="50"></td>
           <td width="1" align="left" valign="top" bgcolor="#a8a9ad"><img src="$ImagePath/spacer50.gif" alt="Description: $ImagePath/spacer50.gif" width="1"
    height="50"></td>
          </tr>
         </table>
         <table id="footer" border="0" cellspacing="0" cellpadding="0" width="655">
          <tr>
           <td><img src="$ImagePath/footer.gif" alt="Description: $ImagePath/footer.gif" width="655" height="81"></td>
          </tr>
         </table>
         <table border="0" cellspacing="0" cellpadding="0" width="655" align="center">
          <tr>
           <td align="left" valign="top"><img src="$ImagePath/spacer.gif" alt="Description: $ImagePath/spacer.gif" width="36" height="1"></td>
           <td align="middle" valign="top"><font face="Verdana" size="1" color="#000000"><p>This email was sent by an automated process.
    if ($HelpDeskURL){
    $emailbody += @"               
           If you would like to comment on it, please visit <a href="$HelpDeskURL"><font color="#ff0000"><u>click here</u></font></a>
    $emailbody += @"               
            </p><p style="color: #009900;"><font face="Webdings" size="4">P</font> Please consider the environment before printing this email.</p></font>
           </td>
           <td align="left" valign="top"><img src="$ImagePath/spacer.gif" alt="Description: $ImagePath/spacer.gif" width="36" height="1"></td>
          </tr>
         </table>
        </td>
       </tr>
      </table>
     </body>
    </html>
          if (!($demo)){
           $emailto = $accountObj.mail
           if ($emailto){
            Write-Verbose "Sending demo message to $emailto"
            Send-MailMessage -To $emailto -Subject "Your password expires in $DaysTillExpire day(s)" -Body $emailbody -From $EmailFrom -Priority High -BodyAsHtml
            $global:UsersNotified++
           }else{
            Write-Verbose "Can not email this user. Email address is blank"
    } # end function Get-ADUserPasswordExpirationDate
    if ($install){
     Write-Verbose "Install mode"
     Install
    Write-Verbose "Checking for ActiveDirectory module"
    if ((Set-ModuleStatus ActiveDirectory) -eq $false){
     $error.clear()
     Write-Host "Installing the Active Directory module..." -ForegroundColor yellow
     Set-ModuleStatus ServerManager
     Add-WindowsFeature RSAT-AD-PowerShell
     if ($error){
      Write-Host "Active Directory module could not be installed. Exiting..." -ForegroundColor red;
      if ($transcript){Stop-Transcript}
      exit
    Write-Verbose "Getting Domain functional level"
    $global:dfl = (Get-AdDomain).DomainMode
    # Get-ADUser -filter * -properties PasswordLastSet,EmailAddress,GivenName -SearchBase "OU=Users,DC=domain,DC=test" |foreach {
    if (!($PreviewUser)){
     if ($ou){
      Write-Verbose "Filtering users to $ou"
      $users = Get-AdUser -filter * -SearchScope subtree -SearchBase $ou -ResultSetSize $null
     }else{
      $users = Get-AdUser -filter * -ResultSetSize $null
    }else{
     Write-Verbose "Preview mode"
     $users = Get-AdUser $PreviewUser
    if ($demo){
     Write-Verbose "Demo mode"
     # $WhatIfPreference = $true
     Write-Host "`n"
     Write-Host ("{0,-25}{1,-8}{2,-12}" -f "User", "Expires", "Policy") -ForegroundColor cyan
     Write-Host ("{0,-25}{1,-8}{2,-12}" -f "========================", "=======", "===========") -ForegroundColor cyan
    Write-Verbose "Setting event log configuration"
    $evt = new-object System.Diagnostics.EventLog("Application")
    $evt.Source = $ScriptName
    $infoevent = [System.Diagnostics.EventLogEntryType]::Information
    $EventLogText = "Beginning processing"
    $evt.WriteEntry($EventLogText,$infoevent,70)
    Write-Verbose "Getting password policy configuration"
    $DefaultDomainPasswordPolicy = Get-ADDefaultDomainPasswordPolicy
    [int]$MinPasswordLength = $DefaultDomainPasswordPolicy.MinPasswordLength
    # this needs to look for FGPP, and then default to this if it doesn't exist
    [bool]$PasswordComplexity = $DefaultDomainPasswordPolicy.ComplexityEnabled
    [int]$PasswordHistory = $DefaultDomainPasswordPolicy.PasswordHistoryCount
    ForEach ($user in $users){
     Get-ADUserPasswordExpirationDate $user.samaccountname
    Write-Verbose "Writing summary event log entry"
    $EventLogText = "Finished processing $global:UsersNotified account(s). `n`nFor more information about this script, run Get-Help .\$ScriptName. See the blog post at
    http://www.ehloworld.com/318."
    $evt.WriteEntry($EventLogText,$infoevent,70)
    # $WhatIfPreference = $false
    # Remove-ScriptVariables -path $MyInvocation.MyCommand.Name
    Remove-ScriptVariables -path $ScriptPathAndName

    Hi petro_jemes,
    Just a little claritification, you need to add the value to the variable "[string]$ou", and also change the language in the variable "$emailbody" in the function "Get-ADUserPasswordExpirationDate".
    I hope this helps.

  • Powershell script monitor with encrypted password

    I have created a powershell script based monitor in my management pack and everything is ok but I can't get my credentials work inside the script. I want to open pssession to another computer with my credentials. I have triple checked that my pssession is
    working because I can access it from powershell console.
    This works perfectly at local server from PSconsole:
    $EncryptedPassword ="01000000d08c9ddf0115d1118c7a00c04fc297eb01000000534b2....etc...etc..."
    $pw = convertto-securestring -String $EncryptedPassword
    $cred = new-object System.Management.Automation.PSCredential -argumentlist "MyDOMAIN\MyACCOUNT",$pw
    $s = New-PSSession -ComputerName "MyServer" -Port MyPort -Credential $cred
    But when I run the same lines inside my management pack the convertto-securestring
    does nothing, it just wont convert the encrypted password to secure string!
    I have tried this plain text method and it works
    inside my management pack, but I don't want to use it because you can see the password in plain text:
    ConvertTo-SecureString -String "myPlainTextPassword" -AsPlainText -Force
    This is the $error variable, so it's basically says that I don't have anything in the password secure string variable because the convertion did not work for some reason:
    The argument is null. Provide a valid value for the argument, and then try running the command again. Cannot process argument transformation on parameter 'Credential'. PromptForCredential Exception calling ".ctor" with "2" argument(s):
    "Cannot process argument because the value of argument "password" is null. Change the value of argument "password" to a non-null value." The system cannot find the file specified. Exception calling "SecureStringToBSTR"
    with "1" argument(s): "Value cannot be null. Parameter name: s" The system cannot find the file specified. Exception calling "SecureStringToBSTR" with "1" argument(s): "Value cannot be null. Parameter name: s"
    The system cannot find the file specified. 
    So is there some known issue with SCOM Agent / management pack when you are dealing with convertto-securestring
    function with encrypted passwords?
    I used these methods to encrypt the password: Technet article about encryption

    I got it to work!
      <TypeDefinitions>
        <EntityTypes>
          <ClassTypes>
            <ClassType ID="MyClass" Accessibility="Public" Abstract="false" Base="Windows!Microsoft.Windows.LocalApplication" Hosted="true" Singleton="false" Extension="false"
    />
          </ClassTypes>
        </EntityTypes>
        <SecureReferences>
          <SecureReference ID="MyRunAsAccountProfile" Accessibility="Public" Context="System!System.Entity" />
        </SecureReferences>
    <ScriptBody>param (
      [string]$Username,
      [string]$Password
    $API = new-object -comObject "MOM.ScriptAPI" 
    $PropertyBag = $API.CreatePropertyBag()
    $cred = New-Object System.Management.Automation.PSCredential -Argumentlist @($Username,(ConvertTo-SecureString -String $Password -AsPlainText -Force))
    $s = New-PSSession -ComputerName "myserver" -Credential $cred
    Invoke-Command -Session $s -ScriptBlock { $service = Get-Service -Name Spooler}
    $invcom = Invoke-Command -Session $s -ScriptBlock { $service.status}
    Remove-PSSession -Id $s.Id
    if ($invcom.Value -ne "Running") {
    $PropertyBag.AddValue("State","ERROR") 
    $outputLongLine = "Spooler Service is not running on target server!" 
    $PropertyBag.AddValue("Description", $outputLongLine)
    else {
    $PropertyBag.AddValue("State","OK") 
    $outputLongLine = "Spooler is Running on target server."
    $PropertyBag.AddValue("Description", $outputLongLine) 
    $PropertyBag</ScriptBody>
    <Parameters>
    <Parameter>
    <Name>Username</Name>
     <Value>$RunAs[Name="MyRunAsAccountProfile"]/Domain$\$RunAs[Name="MyRunAsAccountProfile"]/UserName$</Value>
    </Parameter>
    <Parameter>
    <Name>Password</Name>
    <Value>$RunAs[Name="MyRunAsAccountProfile"]/Password$</Value>
    </Parameter>

  • 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

  • Looking for a Powershell Script which can put the scom servers in maintenance mode

    Looking for a Powershell Script which can put the scom servers in maintenance mode so that SCOM should not send an alert during planned task.
    Rahul

    1. Provide list of servers line-by-line in C:\ServerList.txt, make sure you provide limited no. of servers, do not exceed 20 - 25 per batch
    2. Save the script with suitable name (test.ps1)
    3. Open PowerShell cmd prompt
    4. Script accepts 3 params - TimeInMinutes, Reason and Comment
    **** Please note, this script will work for SCOM 2012 R2
    param([int32]$TimeMin, [string]$Reason, [string]$Comment)
    try
    $api = new-object -comObject 'MOM.ScriptAPI'
    Import-Module operationsmanager
    New-SCOMManagementGroupConnection
    $Servers = Get-Content "C:\ServerList.txt"
    $Time = (Get-Date).Addminutes($TimeMin)
    Foreach ($Server in $Servers)
    #Get Computer instance
    $ComputerClass = Get-SCOMClass -Name Microsoft.Windows.Computer
    $ComputerClassInstance = Get-SCOMClassInstance  -Class $ComputerClass | Where {$_.DisplayName -eq $Server}
    If ($ComputerClassInstance -ne $Null)
    $HealthServiceWatcherClass = Get-SCOMClass -name:Microsoft.SystemCenter.HealthServiceWatcher
    #Get Health Service Watcher Class instance of the server
    $HSWClass = Get-SCOMClass -Name Microsoft.SystemCenter.HealthServiceWatcher
    $HSWClassIns = Get-SCOMClassInstance  -Class $HSWClass | Where {$_.DisplayName -eq $Server}
    #Starting the maintenance mode
    Start-SCOMMaintenanceMode -Instance $HSWClassIns -EndTime $Time -Reason $Reason -Comment $Comment
    Start-SCOMMaintenanceMode -Instance $ComputerClassInstance -EndTime $Time  -Reason $Reason -Comment $Comment
    Write-Host "Health Service Watcher and Agent server "$Server " kept in maintenance mode"  -foregroundcolor "green"
    $api.LogScriptEvent('MaintenanceModeScript.ps1', 200, 0, "$Server kept in maintenance mode for $TimeMin minutes")
    Else
    Write-Host $Server" not found " -foregroundcolor "red"
    $api.LogScriptEvent('MaintenanceModeScript.ps1', 201, 1, "$Server could not be found in domain")
    Catch [system.exception]
    $api.LogScriptEvent('MaintenanceModeScript.ps1', 201, 1, $_.Exception.Message)
    Faizan

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

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

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

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

  • Powershell script to get the low disk space on the servers...

    Hi,
    We have many SQL & Sharepoint servers running on windows server. I need some Powershell script to get the low disk space on those servers and it should send an mail alert saying "Disc d:\ have less than threshold 15% free space".
    Awaiting for response.
    Thanks
    Anil

    you should be able to use this powershell script which you can run as a scheduled task.
    just change the details at the start of the script to point the script to the right location to create log files. you will need to have a plain text file containing a list of server names or ip addresses that you want to check drive space on.
    # Change the following variables based on your environment
    #specify the path to the file you want to generate containing drive space information
    $html_file_dir = "\\server\share\DriveSpace"
    #specify the path and file name of the text file containing the list of servers names you want to check drive space on - each server name on a seperate line in plain text file
    $server_file = "\\server\share\servers.txt"
    #speicfy the from address for the email
    $from_address = "[email protected]"
    #specify the to address for the email
    $to_address = "[email protected]"
    #specify the smtp server to use to send the email
    $email_gateway = "smtp.domain.com" # Can either be DNS name or IP address to SMTP server
    # The seventh line from the bottom (line 167) is used if your smtp gateway requires authentication. If you require smtp authentication
    # you must uncomment it and set the following variables.
    $smtp_user = ""
    $smtp_pass = ""
    # Change the following variables for the style of the report.
    $background_color = "rgb(140,166,193)" # can be in rgb format (rgb(0,0,0)) or hex format (#FFFFFF)
    $server_name_font = "Arial"
    $server_name_font_size = "20px"
    $server_name_bg_color = "rgb(77,108,145)" # can be in rgb format (rgb(0,0,0)) or hex format (#FFFFFF)
    $heading_font = "Arial"
    $heading_font_size = "14px"
    $heading_name_bg_color = "rgb(95,130,169)" # can be in rgb format (rgb(0,0,0)) or hex format (#FFFFFF)
    $data_font = "Arial"
    $data_font_size = "11px"
    # Colors for space
    $very_low_space = "rgb(255,0,0)" # very low space equals anything in the MB
    $low_space = "rgb(251,251,0)" # low space is less then or equal to 10 GB
    $medium_space = "rgb(249,124,0)" # medium space is less then or equal to 100 GB
    #### NO CHANGES SHOULD BE MADE BELOW UNLESS YOU KNOW WHAT YOU ARE DOING
    # Define some variables
    $ErrorActionPreference = "SilentlyContinue"
    $date = Get-Date -UFormat "%Y%m%d"
    $html_file = New-Item -ItemType File -Path "$html_file_dir\DiskSpace_$date.html" -Force
    # Create the file
    $html_file
    # Function to be used to convert bytes to MB or GB or TB
    Function ConvertBytes {
    param($size)
    If ($size -lt 1MB) {
    $drive_size = $size / 1KB
    $drive_size = [Math]::Round($drive_size, 2)
    [string]$drive_size + ' KB'
    }elseif ($size -lt 1GB){
    $drive_size = $size / 1MB
    $drive_size = [Math]::Round($drive_size, 2)
    [string]$drive_size + ' MB'
    }ElseIf ($size -lt 1TB){
    $drive_size = $size / 1GB
    $drive_size = [Math]::Round($drive_size, 2)
    [string]$drive_size + ' GB'
    }Else{
    $drive_size = $size / 1TB
    $drive_size = [Math]::Round($drive_size, 2)
    [string]$drive_size + ' TB'
    # Create the header and footer contents of the html page for output
    $html_header = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>Server Drive Space</title>
    <style type="text/css">
    .serverName { text-align:center; font-family:"' + $server_name_font + '"; font-size:' + $server_name_font_size + `
    '; font-weight:bold; background-color: ' + $server_name_bg_color + '; border: 1px solid black; width: 150px; }
    .headings { text-align:center; font-family:"' + $heading_font + '"; font-size:' + $heading_font_size + `
    '; font-weight:bold; background-color: ' + $heading_name_bg_color + '; border: 1px solid black; width: 150px; }
    .data { font-family:"' + $data_font + '"; font-size:' + $data_font_size + '; border: 1px solid black; width: 150px; }
    #dataTable { border: 1px solid black; border-collapse:collapse; }
    body { background-color: ' + $background_color + '; }
    #legend { border: 1px solid black; ; right:500px; top:10px; }
    </style>
    <script language="JavaScript" type="text/javascript">
    <!--
    function zxcWWHS(){
    if (document.all){
    zxcCur=''hand'';
    zxcWH=document.documentElement.clientHeight;
    zxcWW=document.documentElement.clientWidth;
    zxcWS=document.documentElement.scrollTop;
    if (zxcWH==0){
    zxcWS=document.body.scrollTop;
    zxcWH=document.body.clientHeight;
    zxcWW=document.body.clientWidth;
    else if (document.getElementById){
    zxcCur=''pointer'';
    zxcWH=window.innerHeight-15;
    zxcWW=window.innerWidth-15;
    zxcWS=window.pageYOffset;
    zxcWC=Math.round(zxcWW/2);
    return [zxcWW,zxcWH,zxcWS];
    window.onscroll=function(){
    var img=document.getElementById(''legend'');
    if (!document.all){ img.style.position=''fixed''; window.onscroll=null; return; }
    if (!img.pos){ img.pos=img.offsetTop; }
    img.style.top=(zxcWWHS()[2]+img.pos)+''px'';
    //-->
    </script>
    </head>
    <body>'
    $html_footer = '</body>
    </html>'
    # Start to create the reports file
    Add-Content $html_file $html_header
    # Retrieve the contents of the server.txt file, this file should contain either the
    # ip address or the host name of the machine on a single line. Loop through the file
    # and get the drive information.
    Get-Content $server_file |`
    ForEach-Object {
    # Get the hostname of the machine
    $hostname = Get-WmiObject -Impersonation Impersonate -ComputerName $_ -Query "SELECT Name From Win32_ComputerSystem"
    $name = $hostname.Name.ToUpper()
    Add-Content $html_file ('<Table id="dataTable"><tr><td colspan="3" class="serverName">' + $name + '</td></tr>
    <tr><td class="headings">Drive Letter</td><td class="headings">Total Size</td><td class="headings">Free Space</td></tr>')
    # Get the drives of the server
    $drives = Get-WmiObject Win32_LogicalDisk -Filter "drivetype=3" -ComputerName $_ -Impersonation Impersonate
    # Now that I have all the drives, loop through and add to report
    ForEach ($drive in $drives) {
    $space_color = ""
    $free_space = $drive.FreeSpace
    $total_space = $drive.Size
    $percentage_free = $free_space / $total_space
    $percentage_free = $percentage_free * 100
    If ($percentage_free -le 5) {
    $space_color = $very_low_space
    }elseif ($percentage_free -le 10) {
    $space_color = $low_space
    }elseif ($percentage_free -le 15) {
    $space_color = $medium_space
    Add-Content $html_file ('<tr><td class="data">' + $drive.deviceid + '</td><td class="data">' + (ConvertBytes $drive.size) + `
    '</td><td class="data" bgcolor="' + $space_color + '">' + (ConvertBytes $drive.FreeSpace) + '</td></tr>')
    # Close the table
    Add-Content $html_file ('</table></br><div id="legend">
    <Table><tr><td style="font-size:12px">Less then or equal to 5 % free space</td><td bgcolor="' + $very_low_space + '" width="10px"></td></tr>
    <tr><td style="font-size:12px">Less then or equal to 10 % free space</td><td bgcolor="' + $low_space + '" width="10px"></td></tr>
    <tr><td style="font-size:12px">Less then or equal to 15 % free space</td><td bgcolor="' + $medium_space + '" width="10px"></td></tr>
    </table></div>')
    # End the reports file
    Add-Content $html_file $html_footer
    # Email the file
    $mail = New-Object System.Net.Mail.MailMessage
    $att = new-object Net.Mail.Attachment($html_file)
    $mail.From = $from_address
    $mail.To.Add($to_address)
    $mail.Subject = "Server Diskspace $date"
    $mail.Body = "The diskspace report file is attached."
    $mail.Attachments.Add($att)
    $smtp = New-Object System.Net.Mail.SmtpClient($email_gateway)
    #$smtp.Credentials = New-Object System.Net.NetworkCredential($smtp_user,$smtp_pass)
    $smtp.Send($mail)
    $att.Dispose()
    # Delete the file
    Remove-Item $html_file
    Regards,
    Denis Cooper
    MCITP EA - MCT
    Help keep the forums tidy, if this has helped please mark it as an answer
    My Blog
    LinkedIn:

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

Maybe you are looking for

  • How to Merge multiple XML  files in one file ( Env: XML Publisher 5.6.2)

    All, I have recently started working on XML publisher and have developed 3 reports in last 2 days using XML Publisher and integrating them with Concurrent programs. This is a great tool. I have got another requirement, where i need to use xml file ge

  • HotNews correction for Y2010 spool request error available

    Dear gurus, I became aware of [SAP Note 1422843|https://service.sap.com/sap/support/notes/1422843] which has affected all my systems's spool request reorg jobs. It is currently release and patch level independent, so you will all be affected by it as

  • Submit via email without an email program

    I want to submit via email without an email program like in windows using the maildoc()  it uses outlook but i want to make it more universal(for use on computers where outlook, iMail, or some sort of program set up to send and multi-OS) where it wil

  • Help - Schuffle is not linking

    We just got a second generation schuffle. The schuffle is not recognized by the computer. We have XP. I have plugged it into every usb port and it does not recognize the schuffle. Do I have a bad schuffle?

  • CS6 Disk Cache reporting as full when it's not

    I put a 120GB Samsung Pro 840 Pro SSD on a Sonnet Tempo Card into my 4,1 Mac Pro to use a AE's Disk Cache, I set the disk cache to 100GB Recently AE often reports that there is not enough available space on the drive for the cache when I start it up.