Powershell vs Tidal6

Hi,
I'm working on automating some excel work using powershell. Environment is TES 6.0.3 on solaris with the agent on a windows7 x64 system.
The job calls a simple one-line bat script which is "powershell -command c:\tidal\autoexcel.ps1".
The script works fine when called from a command window however when TES executes it I get a load of errors which I'm assuming are environment related. In essence it looks like excel can't find a load of embedded functions.
The sample code can be found here. Its the charting of the weather data in Excel section.
http://www.simple-talk.com/dotnet/.net-tools/com-automation-of-office-applications-via-powershell/
I've tried creating an env.bat file to reproduce my command line working environment but it hasn't helped.
Any ideas anyone?
Cheers
Joe

We are running 5.31 but ipowershell should behave the same in 6x
Powershell tips
It can be tricky sometimes with powershell (especially gettign remote execution working) but if you are getting security issues you probably are restricted and need "signed" scripts.. Which depending on your policies may be required... but it wasn't worth the pain to our company.
check it by running a powershell command: get-executionpolicy
We set ours to unrestricted (use set-executionpolicy unrestricted)
If you are running 64 Bit you need to do for both  32 bit and 64 bit versions
if you intend to do remoting useEnable-PSRemoting and follow the prompts
Here's an example where we reach out to an application server (FTP server) and trigger it to run an FTP task for us (send a file):
Invoke-Command -computername -scriptblock {"" '-start:""' -p:SourceFileFromAPI: -waitsecs:60 -noxfers:1}
Quotes can be a real pain with how Tidal Agents interprets the string so don't get frustrated if it works via powershell command line but won't work as a job. We discovered a defect in the way tidal handled quotes with powershell and worked with Cisco to put in a fix. we run agent 3.0.2.03 (If you read the readme files you'll find there's a switch:
3.0.2.03
HOT - CSCtv19905 - Fix to BUG00620 (substituting ticks with quotes, compat with old agent) caused
     problems for some customers.
FIX - Added new tagent.ini parameter, substticks=y|n, to control.  Yes is default for compatibility
     with old agent.
Path to Agent install \Agent\bin\tagent.ini
[config]
substticks=n
[TIDAL_AGENT_1]
Other tips
We installed powershell 2.0 on source and target, you need to keep versions consistent
You can run mutiple statements in a job... reducing the number of jobs with a semicolon ; Last statement does not have a semi-colon
Use Write-Host like you would "echo" to insert comments (all are picked up in output)
Exit Codes: you can force and standardize exit codes easily by using exit(###); as one of your statements, which is a cool way to trigger multiple actions like sending different "scenario" emails based on results with just one job, etc)
You can run "agentless" with powershell. How about stopping or starting services remotely?
set-service -computerName Targetserver -name TargetServices -status Running -passthru
We also run all our file operations with powershell (it is much more flexible and reliable that other commands)
We rarely use scipts, we mostly put basic commands or create functions directly in parameters
Function copy-file-force              
{  Bunch of Commands }
copy-file-force  Param1, Param2, etc
powershell in combination with powershell makes a poweful combination for rapid job development.
We have about 4000 powershell jobs defined and active in our environment

Similar Messages

  • Cannot send email from Powershell on Mailbox Role

    Hi,
    I am trying to send an email from Powershell on Mailbox role of Exchange server. I have installed Symantec Mail Security on Mailbox Role.
    When I try to send email using Powershell, I got the following error.
    PS C:\a> Send-MailMessage -to [email protected] -Subject "Alert Closed.. Service is restarted on Computer" -from
    [email protected] -Body "The service was found stopped on Computer it was started automatically and it is now running normally." -bodyasHTML -priority High -SmtpServer smtp.domain.com
    Send-MailMessage : Service not available, closing transmission channel. The server response was: 4.3.2 Service not active
    At line:1 char:1
    + Send-MailMessage -to [email protected] -Subject "Alert Closed.. Service is ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpException
        + FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage
    This command is working fine on every server except exchange server (CAS, Mailbox). Firewall is off on the servers.
    Any help will be highly appreciated.
    Regards,
    Anees

    Hi,
    Please check the similar thread .
    http://social.technet.microsoft.com/Forums/exchange/en-US/ef699832-8da9-4709-9a50-c6223b13bd95/sendmailmessage-returns-the-server-response-was-432-service-not-available?forum=exchangesvrsecuremessaginglegacy
    smtp server (smtp.domain.com) is rejecting the connection from the
     Mailbox role of Exchange server.
    So please allow the mailbox server ip address on the smtp server's (i.e. smtp.domain.com)
    receive connector to get it done 
    Regards
    S.Nithyanandham
    Thanks S.Nithyanandham

  • How can I display a SP 2010 out of the box workflow's task assignees via powershell?

    There are days where one of the 250+ workflows at the site has attempted to send email to someone no longer at the company.
    I would like to find a way to go through the farm and display all the list URLs that have workflows, and the mail addresses associated to the workflows.
    This way I can track down the workflows that need to be updated to remove the missing users.
    I have started a bit of script to do this. In my script, I just had a site collection - I figured that if I can get that to work, then surely wrapping another loop for the rest of the farm won't be bad. 
    However, for some reason, I am not seeing the output that I expected to show the mail addresses.
    I am hoping a different set of eyes might see what I am missing. It was my understanding that the AssociationData property was XML that contained information about the assignees for tasks, the carbon copy list, etc.
    Maybe I misunderstood something that I read?
    $outLoc = "d:\temp\wfdata.txt"
    $web = Get-SPWeb -Identity "http://myfarm/sites/it/"
    foreach ($list in $web.Lists)
     $associationColl=$list.WorkflowAssociations
     foreach ($association in $associationColl)
           $association.AssociationData | Out-File $outLoc
    $web.Dispose()
    I want to thank you for the helpful tips that so often appear on this list. They help me when I am reading over old threads to figure out what to do. I am hoping that tips on this thread will likewise be helpful.

    Hi,
    With
    SPWorkflowAssociation.AssociationData property, we can get the assignees’ information. Your script can
    be able to retrieve a XML format data which contains the user name we need:
    So the next step would be getting the user name by parsing the XML data we got.
    The two links below will show how to parse XML with PowerShell:
    http://stackoverflow.com/questions/18032147/parsing-xml-using-powershell
    http://blogs.technet.com/b/heyscriptingguy/archive/2012/03/26/use-powershell-to-parse-an-xml-file-and-sort-the-data.aspx
    With the user name, we can get the
    Email property of an user with the scripts as the link below provided:
    http://davidlozzi.com/2012/03/07/using-powershell-to-access-sharepoint-sites/  
    Best regards
    Patrick Liang
    TechNet Community Support

  • Error while updating a custom Windows Azure Diagnostics configuration xml from powershell. "Invalid update to extension reference for role"

    I am attempting to upload a manually edited WADConfig xml to my VM. The WAD service is functioning correctly, I needed to add some custom WinEventLogs. The prescribed steps result in an error.
    What am I overlooking?
    I am following these instructions:
    Step 5: Remotely install Diagnostics on your Azure Virtual Machine
    azure.microsoft.com/en-in/documentation/articles/cloud-services-dotnet-diagnostics/#virtual-machine
    $storage_name = "wadexamplevm"
    $key = "<StorageAccountKey>"
    $config_path="c:\users\<user>\documents\visual studio 2013\Projects\WadExampleVM\WadExampleVM\WadExample.xml"
    $service_name="wadexamplevm"
    $vm_name="WadExample"
    $storageContext = New-AzureStorageContext
    -StorageAccountName $storage_name -StorageAccountKey $key
    $VM1 = Get-AzureVM
    -ServiceName $service_name -Name $vm_name
    $VM2 = Set-AzureVMDiagnosticsExtension
    -DiagnosticsConfigurationPath $config_path
    -Version "1.*"
    -VM $VM1 -StorageContext $storageContext
    $VM3 = Update-AzureVM
    -ServiceName $service_name -Name $vm_name
    -VM $VM2.VM
    Unfortunately, I am receiving this error:
    Update-AzureVM : BadRequest: Invalid update to extension reference for role: XXXXXX and reference: IaaSDiagnostics.
    What's missing from the above script?

    Hi,
    Since Azure SDK 2.5 uses the extension model the diagnostics extension, the configuration and the connection string to the diagnostic storage are no longer part of the deployment package and cscfg. All the diagnostics configuration is contained within the
    wadcfgx. The advantage with this approach is that diagnostics agent and settings are decoupled from the project and can be dynamically enabled and updated even after your application is deployed. 
    Due to this change some existing workflows need to be rethought – instead of configuring the diagnostics as part of the application that gets deployed to each environment you can first deploy the application to the environment and then apply the diagnostics
    configuration for it.  When you publish the application from Visual Studio this process is done automatically for you. However if you were deploying your application outside of VS using PowerShell then you have to install the extension separately through
    PowerShell.
    There PowerShell cmdlets for managing the diagnostics extensions on a Cloud Service are -
    Set-AzureServiceDiagnosticsExtension
    Get-AzureServiceDiagnosticsExtension
    Remove-AzureServiceDiagnosticsExtension
    You can use the Set-AzureServiceDiagnosticsExtension method to enable diagnostics extension on a cloud service. One of the parameters on this cmdlet is the XML configuration file. This file is slightly different from the diagnostics.wadcfgx file. You can
    create this file from scratch by either following the article that you are referring to or  you can modify the wadcfgx file and pass in the modified file as a parameter to the powershell cmdlet.
    To modify the wadcfgx file –
    Make a copy the .wadcfgx.
    Remove the following elements from the Copy:
    <DiagnosticsConfiguration xmlns="http://schemas.microsoft.com/ServiceHosting/2010/10/DiagnosticsConfiguration">
       <PrivateConfig xmlns="http://schemas.microsoft.com/ServiceHosting/2010/10/DiagnosticsConfiguration">
         <StorageAccount name=" " endpoint="https://core.windows.net/" />
       </PrivateConfig>
       <IsEnabled>false</IsEnabled>
    </DiagnosticsConfiguration>
    Make sure the top of the file still has xml version and encoding –
       <?xml version="1.0" encoding="utf-8"?>
    Effectively you are stripping down the Wadcfgx to only contain the <PublicConfig> section and the <?xml> header. You can then call the PowerShell cmdlet along with the appropriate parameters for the staging slots and roles:
    $storage_name = ‘
    <storagename>’
    $key= ‘<key>’
    $service_name = '<servicename>'
    $public_config = '<thepublicconfigfrom_diagnostics.wadcfgx>'
    $storageContext = New-AzureStorageContext –StorageAccountName $storage_name –StorageAccountKey $key
    Set-AzureServiceDiagnosticsExtension -StorageContext $storageContext -DiagnosticsConfigurationPath $public_config –ServiceName $service_name -Slot ‘Staging’ -Role ‘WebRole1’
    Hope this helps !
    Regards,
    Sowmya

  • Looking for help with PowerShell script to delete folders in a Document Library

    I'd like to create a PowerShell script to delete old folders in a Document library that are over 30 days old. Has anyone created something like this?
    Orange County District Attorney

    Hello Sid:
    I am trying to do the same and Iam running the script to delete the subfolders inside a folder  but I have some errors. 
    Could you please take a look?
    _______Script________
    $web = Get-SPWeb -Identity https://myportal.mydomain.com
    $list = $web.GetList("ar_mailingactivity")
    $query =  New-Object Microsoft.SharePoint.SPQuery 
    $camlQuery = '<Where><And><Eq><FieldRef Name="ContentType" /><Value Type="Computed">Folder</Value></Eq><Leq><FieldRef Name="Created" /><Value Type="DateTime"><Today OffsetDays="-30" /></Value></Leq></And></Where>'
    $query.Query = $camlQuery
    $items = $list.GetItems($query)
    for ($intIndex = $items.Count - 1; $intIndex -gt -1; $intIndex--)
       $items.Delete($intIndex);
    ________Errors_______
    Unable to index into an object of type System.Management.Automation.PSMethod.
    At C:\Script.ps1:2 char:22
    + $list =$webGetList <<<< "ar_mailingactivity"]
    + CategoryInfo
    :InvalidOperation: (ar_mailingactivity:String) [], RuntimeException
    + FullyQualifiedErrorID
    :CannotIndex
    You cannot call a method on  a null-valued expression.
    At c:\Script.ps1:6 char:24
    + $items = $list.GetItems <<<< ($query)
    + CategoryInfo
    :InvalidOperation: (GetItems:String) [], RuntimeException
    + FullyQualifiedErrorID
    :InvokeMethodOnNull

  • Powershell Script Send-zip not working when running in cmd

    I found there is powershell send-zip script available in technet.  I tested it and found that it works when the script is running under powershell env, but when it is calling in cmd env, I can see the zip file, but there is nothing in it.  If
    I add the "-noexit" switch it runs normally.  Anyone have ideas what might be happening?
    The orig codes is as following:
    function global:SEND-ZIP ($zipfilename, $filename) { 
    # The $zipHeader variable contains all the data that needs to sit on the top of the 
    # Binary file for a standard .ZIP file
    $zipHeader=[char]80 + [char]75 + [char]5 + [char]6 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0
    # Check to see if the Zip file exists, if not create a blank one
    If ( (TEST-PATH $zipfilename) -eq $FALSE ) { Add-Content $zipfilename -value $zipHeader }
    # Create an instance to Windows Explorer's Shell comObject
    $ExplorerShell=NEW-OBJECT -comobject 'Shell.Application'
    # Send whatever file / Folder is specified in $filename to the Zipped folder $zipfilename
    $SendToZip=$ExplorerShell.Namespace($zipfilename.tostring()).CopyHere($filename.ToString())
    SEND-ZIP C:\abc\a.ZIP C:\a\a.bak

    I've had the same problem with similar code found on another web site.
    The reason the zip file ends up being empty is that the temporary $ExplorerShell object you created is deleted when the send-zip function returns,
    and any incomplete copy operation that may still be ongoing at that time is aborted. (The copy operation is asynchronous, and continues after the CopyHere() function returns.)
    To work around this, you need to add a delay loop before you return, waiting for the copied object to appear in the zip.
    (Note that adding a fixed delay, like I've seen on other web sites, does not work: Small files appear almost immediately, whereas large file or worse still large subdirectory trees can take a long time to appear.)
    Try changing the end of your routine to something like...
    # Create an instance to Windows Explorer's Shell comObject 
    $ExplorerShell=NEW-OBJECT -comobject 'Shell.Application' 
    # Open the zip file object
    $zipFile = $ExplorerShell.Namespace($zipfilename.tostring())
    # Count how many objects were in the zip file initially
    $count = $zipFile.Items().Count
    # Send whatever file / Folder is specified in $filename to the Zipped folder $zipfilename 
    $SendToZip=$zipFile.CopyHere($filename.ToString())
    # Wait until the file / folder appears in the zip file
    $count += 1 # We expect one more object to be there eventually
    while ($zipFile.Items().Count -lt $count) {
        Write-Debug "$filename not in the zip file yet. Sleeping 100ms"
        Start-Sleep -milliseconds 100
    # Return deletes the $zipFile object, and aborts incomplete copy operations.

  • Unable to create web app with PowerShell - An update conflict has occurred

    I am trying to create a new Web Application using PowerShell. I need to use PowerShell because I need to create the Web App using classic authentication and not Claims authentication. the first time I created the Web App, everything went great. Ever since
    the first time, I get an error and the web app creation does not complete. Just as an FYI, I can create a new Web App using Central Admin, but that creates it with Claims authentication which I cannot use.
    Here is my PowerShell script
    New-SPWebApplication -Name "SharePoint2013 (82)" -ApplicationPool "SharePoint2013-82" -AuthenticationMethod "NTLM" -ApplicationPoolAccount (Get-SPManagedAccount "GLOBAL\SP_AppPool") -Port 82 -URL "http://sharepoint2013"
    Here is the error I get in PowerShell
    New-SPWebApplication : An update conflict has occurred, and you must re-try this action. The object SPWebApplication
    Name=SharePoint2013 (82) was updated by DOMAIN\SP_Administrator, in the powershell (13020) process, on machine SPWEB01.
     View the tracing log for more information about the conflict.
    At line:1 char:1
    + New-SPWebApplication -Name "SharePoint2013 (82)" -ApplicationPool "SharePoint201 ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidData: (Microsoft.Share...PWebApplication:SPCmdletNewSPWebApplication) [New-SPWebA
       pplication], SPUpdatedConcurrencyException
        + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletNewSPWebApplicationUnknown SQL Exception 547 occurred. Additional error information from SQL Server is included below.
    The DELETE statement conflicted with the REFERENCE constraint "FK_Dependencies1_Objects". The conflict occurred in database "SP_Config", table "dbo.Dependencies", column 'ObjectId'.
    The statement has been terminated.
    I also get  this error from the trace
    Unknown SQL Exception 547 occurred. Additional error information from SQL Server is included below.
    The DELETE statement conflicted with the REFERENCE constraint "FK_Dependencies1_Objects". The conflict occurred in database "SP_Config", table "dbo.Dependencies", column 'ObjectId'.
    The statement has been terminated.
    I have tried to resolve the issue by performing the following:
    Delete the partially created web app using Central Admin or PowerShell
    Clear the file system cache on all servers in the farm (Stopping wss timer job, Saving Copy of the
    cache.ini file from C:\Documents and Settings\All Users\application data\Microsoft\SharePoint\Config folder. Clearing all the .xml files from the location except cache.ini but Edit the cache.ini to have value 1. Starting the timer job)
    Use Products Configuration Wizard (no detach, just 'upgrade') - People have said to select the option to disconnect the server from server farm and revert back again at next step (so you actually do not disconnect), but there is no next step that I have
    encountered. You select 'disconnect', hit next, and the server disconnects.
    Restart all the servers in the farm
    Run the PowerShell script again...still get the same error
    I have tried it on multiple servers in the farm too.

    Hi Michael,
    I found a similar thread for you reference:
    http://social.msdn.microsoft.com/Forums/sharepoint/en-US/9ccef7bf-87a9-4849-b086-4db2d898f1d7/cannot-create-new-web-application-wss-30?forum=sharepointadminlegacy 
    If it doesn’t work, sometimes the issue might be caused by long time keep powershell opening and generating some cache files. So please try re-opening the powershell and test the issue again.
    http://blogs.msdn.com/b/ronalg/archive/2011/06/24/mount-spcontentdatabase-errors-on-2nd-and-subsequent-attempts-of-same-database.aspx?Redirected=true 
    http://www.oakwoodinsights.com/sharepoint-powershell-surprise/
    In addition, here is an article which explains the possible reason of the SQL error:
    http://technet.microsoft.com/en-us/library/ee513056(v=office.14).aspx
    Regards,
    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] .
    Rebecca Tu
    TechNet Community Support

  • Exchange Powershell return value from Get-command to variable.

    Hi
    I am trying to create a powershell-script for our monitoring-software.
    The script is supposed to establish a connection to our exchange-server mgmt-shell and execute this command:
    "Get-MailboxDatabaseCopyStatus"
    I have the connection in place, but am missing the knowledge of how to return the result of the command to my script, which I can then pass to our monitoring-software.
    (The script take 2 parameters - host and command eg. exch01.domain and Get-MailboxDatabaseCopyStatus).
    Current code:
    $statusAlive = "ScriptRes:Host is alive:"
    $statusDead = "ScriptRes:No answer:"
    $statusUnknown = "ScriptRes:Unknown:"
    $statusNotResolved = "ScriptRes:Unknown host:"
    $statusOk = "ScriptRes:Ok:"
    $statusBad = "ScriptRes:Bad:"
    $statusBadContents = "ScriptRes:Bad contents:"
    $pass = cat C:\securestring.txt | convertto-securestring
    $Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "domain\administrator",$pass
    $host = $args[0]
    $command = $args[1]
    <#
    if (!$args[0]) {
    echo $statusUnknown"Host parameter is empty"
    exit
    if (!$args[1]) {
    echo $statusUnknown"Command parameter is empty"
    exit
    #>
    $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://$host/powershell -Credential $cred
    Import-PSSession $session
    $command
    Remove-PSSession $session
    Now, how do I "catch" the value of the executed command and return it to a variable in the script?
    Best Regards,
    Soren

    Hmm.. doesnt seem to work quite right.
    I added "Echo $result" after "Remove-PSSession $session", but then I just get a bunch of information..
    Script tmp_c3a1c132-f4d9-4d61... {Get-IRMConfiguration, New-MailUser, Get-PublicFolderMigrationRequestSta...
    RunspaceId : 2d179364-2df3-483d-a192-f5f4ca9453bb
    Identity : DB02 - Specielle\EXCHANGE01
    Id : DB02 - Specielle\EXCHANGE01
    Name : DB02 - Specielle\EXCHANGE01
    DatabaseName : DB02 - Specielle
    Status : Mounted
    InstanceStartTime : 01-03-2014 03:35:07
    LastStatusTransitionTime :
    MailboxServer : EXCHANGE01
    ActiveDatabaseCopy : EXCHANGE01
    ActiveCopy : True
    ActivationPreference : 1
    StatusRetrievedTime : 11-03-2014 08:30:15
    WorkerProcessId : 8124
    ActivationSuspended : False
    ActionInitiator : Unknown
    ErrorMessage :
    ErrorEventId :
    ExtendedErrorInfo :
    SuspendComment :
    RequiredLogsPresent :
    SinglePageRestore : 0
    ContentIndexState : Healthy
    ContentIndexErrorMessage :
    ContentIndexVersion : 1
    ContentIndexBacklog : 0
    ContentIndexRetryQueueSize : 0
    ContentIndexMailboxesToCrawl :
    ContentIndexSeedingPercent :
    ContentIndexSeedingSource :
    CopyQueueLength : 0
    ReplayQueueLength : 0
    ReplaySuspended : False
    ResumeBlocked : False
    ReseedBlocked : False
    MinimumSupportedDatabaseSchemaVersion : 0.121
    MaximumSupportedDatabaseSchemaVersion : 0.125
    RequestedDatabaseSchemaVersion : 0.125
    LatestAvailableLogTime :
    LastCopyNotificationedLogTime :
    LastCopiedLogTime :
    LastInspectedLogTime :
    LastReplayedLogTime :
    LastLogGenerated : 0
    LastLogCopyNotified : 0
    LastLogCopied : 0
    LastLogInspected : 0
    LastLogReplayed : 0
    LowestLogPresent : 0
    LastLogInfoIsStale : False
    LastLogInfoFromCopierTime :
    LastLogInfoFromClusterTime :
    LastLogInfoFromClusterGen : 0
    LogsReplayedSinceInstanceStart : 0
    LogsCopiedSinceInstanceStart : 0
    LatestFullBackupTime :
    LatestIncrementalBackupTime :
    LatestDifferentialBackupTime :
    LatestCopyBackupTime :
    SnapshotBackup :
    SnapshotLatestFullBackup :
    SnapshotLatestIncrementalBackup :
    SnapshotLatestDifferentialBackup :
    SnapshotLatestCopyBackup :
    LogReplayQueueIncreasing : False
    LogCopyQueueIncreasing : False
    ReplayLagStatus :
    DatabaseSeedStatus :
    OutstandingDumpsterRequests : {}
    OutgoingConnections :
    IncomingLogCopyingNetwork :
    SeedingNetwork :
    DiskFreeSpacePercent : 50
    DiskFreeSpace : 20.02 GB (21,498,761,216 bytes)
    DiskTotalSpace : 40 GB (42,946,523,136 bytes)
    ExchangeVolumeMountPoint :
    DatabaseVolumeMountPoint : E:\
    DatabaseVolumeName : \\?\Volume{e6cb407f-e4f2-11e2-93eb-005056ae239d}\
    DatabasePathIsOnMountedFolder : False
    LogVolumeMountPoint : F:\
    LogVolumeName : \\?\Volume{e6cb4087-e4f2-11e2-93eb-005056ae239d}\
    LogPathIsOnMountedFolder : False
    LastDatabaseVolumeName :
    LastDatabaseVolumeNameTransitionTime :
    VolumeInfoError :
    IsValid : True
    ObjectState : Unchanged
    RunspaceId : 2d179364-2df3-483d-a192-f5f4ca9453bb
    Identity : DB01 - Standard\EXCHANGE01
    Id : DB01 - Standard\EXCHANGE01
    Name : DB01 - Standard\EXCHANGE01
    DatabaseName : DB01 - Standard
    Status : Mounted
    InstanceStartTime : 01-03-2014 03:35:07
    LastStatusTransitionTime :
    MailboxServer : EXCHANGE01
    ActiveDatabaseCopy : EXCHANGE01
    ActiveCopy : True
    ActivationPreference : 1
    StatusRetrievedTime : 11-03-2014 08:30:15
    WorkerProcessId : 8140
    ActivationSuspended : False
    ActionInitiator : Unknown
    ErrorMessage :
    ErrorEventId :
    ExtendedErrorInfo :
    SuspendComment :
    RequiredLogsPresent :
    SinglePageRestore : 0
    ContentIndexState : Healthy
    ContentIndexErrorMessage :
    ContentIndexVersion : 1
    ContentIndexBacklog : 3
    ContentIndexRetryQueueSize : 0
    ContentIndexMailboxesToCrawl :
    ContentIndexSeedingPercent :
    ContentIndexSeedingSource :
    CopyQueueLength : 0
    ReplayQueueLength : 0
    ReplaySuspended : False
    ResumeBlocked : False
    ReseedBlocked : False
    MinimumSupportedDatabaseSchemaVersion : 0.121
    MaximumSupportedDatabaseSchemaVersion : 0.125
    RequestedDatabaseSchemaVersion : 0.125
    LatestAvailableLogTime :
    LastCopyNotificationedLogTime :
    LastCopiedLogTime :
    LastInspectedLogTime :
    LastReplayedLogTime :
    LastLogGenerated : 0
    LastLogCopyNotified : 0
    LastLogCopied : 0
    LastLogInspected : 0
    LastLogReplayed : 0
    LowestLogPresent : 0
    LastLogInfoIsStale : False
    LastLogInfoFromCopierTime :
    LastLogInfoFromClusterTime :
    LastLogInfoFromClusterGen : 0
    LogsReplayedSinceInstanceStart : 0
    LogsCopiedSinceInstanceStart : 0
    LatestFullBackupTime :
    LatestIncrementalBackupTime :
    LatestDifferentialBackupTime :
    LatestCopyBackupTime :
    SnapshotBackup :
    SnapshotLatestFullBackup :
    SnapshotLatestIncrementalBackup :
    SnapshotLatestDifferentialBackup :
    SnapshotLatestCopyBackup :
    LogReplayQueueIncreasing : False
    LogCopyQueueIncreasing : False
    ReplayLagStatus :
    DatabaseSeedStatus :
    OutstandingDumpsterRequests : {}
    OutgoingConnections :
    IncomingLogCopyingNetwork :
    SeedingNetwork :
    DiskFreeSpacePercent : 50
    DiskFreeSpace : 20.02 GB (21,498,761,216 bytes)
    DiskTotalSpace : 40 GB (42,946,523,136 bytes)
    ExchangeVolumeMountPoint :
    DatabaseVolumeMountPoint : E:\
    DatabaseVolumeName : \\?\Volume{e6cb407f-e4f2-11e2-93eb-005056ae239d}\
    DatabasePathIsOnMountedFolder : False
    LogVolumeMountPoint : F:\
    LogVolumeName : \\?\Volume{e6cb4087-e4f2-11e2-93eb-005056ae239d}\
    LogPathIsOnMountedFolder : False
    LastDatabaseVolumeName :
    LastDatabaseVolumeNameTransitionTime :
    VolumeInfoError :
    IsValid : True
    ObjectState : Unchanged
    I am only interested in the 2 "ContentIndexState" - how can I pick these 2 out and put them into a variable?
    I though the command "Get-MailboxDatabaseCopyStatus" would only display these two, since it is what happens if I run the command inside PowerShell on the server itself.

  • Using Powershell Script Run simple query in MS Access 2007 and export the results of query to Excel

    Hi Experts,
    I have a Access 2007 DB file and 2 Big tables inside that (bigger than the size that can be easily handled by MS Excel 2007).
    My requirement is automate using powershell scripts the below things.
    1. Create a SQL query in Access DB and save that in access DB
    2. Run the saved query and export the result in excel sheet where I can create the charts and Pivots. Thanks in advance
    Prajesh

    Do you have to use the Access query, couldn't you just recreate the query in Powershell?  Here's a link with good info that references an existing script for querying an Access database:
    http://blogs.technet.com/b/heyscriptingguy/archive/2009/08/13/hey-scripting-guy-can-i-query-a-microsoft-access-database-with-a-windows-powershell-script.aspx
    Once you have your dataset you can pipe it to
    Export-Csv -NoType c:\pathtofile\output.csv

  • How do I update columns in a library using PowerShell during a file upload?

    I am trying to put together a script that will do a bulk upload of files along with associated metadata into a SP library. The first part of the requirement is to upload .pdf files while grabbing the metadata from the file name. Currently, my script does
    the uploads, but it it does not update the fields with the metadata it is getting from the file names. Here is what my script curently looks like
    if((Get-PSSnapin "Microsoft.SharePoint.PowerShell") -eq $null)
    Add-PSSnapin Microsoft.SharePoint.PowerShell
    #Script settings
    $webUrl = "http://llc-hdc-spfe1d:19500/sites/SampleRecordCenter/"
    $docLibraryName = "My Library"
    $docLibraryUrlName = "MyLibrary"
    $localFolderPath = get-childitem "C:\test" -recurse
    #Open web and library
    $web = Get-SPWeb $webUrl
    $docLibrary = $web.Lists[$docLibraryName]
    $files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles()
    ForEach($file in $files)
    if ($localFolderPath | where {$_.extension -eq ".pdf"})
    #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
    $myArray = @()
    foreach ($MetaDataString in $FileNameArray)
    #Add file
    $folder = $web.getfolder($docLibraryUrlName)
    write-host "Copying file " $file.Name " to " $folder.ServerRelativeUrl "..."
    $spFile = $folder.Files.Add($folder.Url + "/" + $file.Name, [System.IO.Stream]$fileStream, $true)
    if ($FileNameArray.Length -eq 3)
    #populate columns
    $spItem = $docLibrary.AddItem()
    $spItem["FirstColumn"] = $myArray[0]
    $spItem["SecondColumn"] = $myArray[1]
    $spItem["ThirdColumn"] = $myArray[2]
    $spItem.Update()
    elseif ($myArray.Length -eq 4)
    #populate columns
    $spItem = $docLibrary.AddItem()
    $spItem["FirstColumn"] = $myArray[0]
    $spItem["SecondColumn"] = $myArray[1]
    $spItem["ThirdColumn"] = $myArray[2]
    $spItem["FourthColumn"] = $myArray[3]
    $spItem.Update()
    #Close file stream
    $fileStream.Close();
    #Dispose web
    $web.Dispose()
    The .pdf files have the same naming convention like "first_second_third.pdf" and "first_second_third_fourth.pdf"...I want to grab each part of the file name, and put that data in the associated column in the library. Right now, am getting
    my file name and storing that information in an array, but my code isn't updating each column as I hope it will. What am I doing wrong here?
    Thanks for the help.

    Just figured out what was wrong with my logic...this does the trick.
    if ($localFolderPath | where {$_.extension -eq ".pdf"})
    $fileStream = ([System.IO.FileInfo] (Get-Item $file.FullName)).OpenRead()
    $FileName = $File.Name
    $NewName = [IO.Path]::GetFileNameWithoutExtension($FileName)
    $FileNameArray = $NewName.split("_")
    $folder = $web.getfolder($docLibraryUrlName)
    $spFile = $folder.Files.Add($folder.Url + "/" + $file.Name, [System.IO.Stream]$fileStream, $true)
    $spItem = $spFile.Item
    if ($FileNameArray.Length -eq 3)
    $spItem["FirstColumn"] = $FileNameArray[0].ToString()
    $spItem["SecondColumn"] = $FileNameArray[1].ToString()
    $spItem["ThirdColumn"] = $FileNameArray[2].ToString()
    $spItem.Update()
    elseif ($FileNameArray.Length -eq 4)
    $spItem["FirstColumn"] = $FileNameArray[0]
    $spItem["SecondColumn"] = $FileNameArray[1]
    $spItem["ThirdColumn"] = $FileNameArray[2]
    $spItem["FourthColumn"] = $FileNameArray[3]
    $spItem.Update()
    $fileStream.Close();

  • How do I use nested Label with nested Switch in Powershell?

    Hi,
    I am trying to run the script with Label and Switch in Menu format so that the main module calls the submodule and ends in the submodule. The submodule should be able to call another module.
    Please correct the script, as I think I am going wrong
    Do { Write-Host " ----------MENU A----------
    1 = option 1
    2 = Option 2
    3 = Option 3
    $choice1 = read-host -prompt "Select number & press enter" }
    until ($choice1 -eq "1" -or $choice1 -eq "2" -or $choice1 -eq "3")
    Switch ($choice1)
        { "1" break :module1
          "2" break :module2
          "3" break :module3
    module1
        Do { Write-Host " ----------MENU B----------
        1 = option 1
        2 = Option 2
        $choice2 = read-host -prompt "Select number & press enter" }
        until ($choice2 -eq "1" -or $choice2 -eq "2")
        Switch ($choice2)
        { write "Module 2"
          "1" break :module2
          "2" break :module3
    module2
        Do { Write-Host " ----------MENU C----------
        1 = option 1
        $choice3 = read-host -prompt "Select number & press enter" }
        until ($choice3 -eq "1")
        Switch ($choice3)
        { write "Module 3"
          "1" break :module2
    Tirtha Chandan Tripathy

    Hi Tirtha,
    What you want to do in PowerShell is separate elements of logic trees into individual functions. I rewrote your script attempt somewhat to show you how to do this:
    function Show-MenuMain
    Do
    Write-Host @"
    ----------MENU A----------
    1 = option 1
    2 = Option 2
    3 = Option 3
    $Choice = read-host -prompt "Select number & press enter"
    until ($Choice -eq "1" -or $Choice -eq "2" -or $Choice -eq "3")
    Switch ($Choice)
    "1" { Show-MenuModule1 }
    "2" { Show-MenuModule2 }
    "3" { Show-MenuModule3 }
    function Show-MenuModule1
    Do
    Write-Host @"
    ----------MENU B----------
    1 = option 1
    2 = Option 2
    $Choice = read-host -prompt "Select number & press enter"
    until ($Choice -eq "1" -or $Choice -eq "2")
    Switch ($Choice)
    "1" { Show-MenuModule2 }
    "2" { Show-MenuModule3 }
    function Show-MenuModule2
    Do
    Write-Host @"
    ----------MENU C----------
    1 = option 1
    $Choice = read-host -prompt "Select number & press enter"
    until ($Choice -eq "1")
    Switch ($Choice)
    "1" { Show-MenuModule1 }
    Show-MenuMain
    I know, this really only prepares the path to a host of new questions, more than answering your current ones, but it gives you something to work with and build upon.
    Cheers,
    Fred
    There's no place like 127.0.0.1

  • Remotely editing text files in Windows WinRM/PSExec/Powershell/cmd

    Hi!
    How can I remotely edit a text file in Windows?
    I am running and administering a number of Windows 7 workstations and Windows Server 2012 machines. I would like to be able to remotely edit text files on any of these machines. I can connect to any of these machines via psexec or powershell remoting. I
    can also connect via rdp, but for the workstations I would rather not kick the user off unless I absolutely have to.
    For example, we manage state configuration using
    Salt. Local configuration files are stored in C:/salt/conf. I would like to be able to edit these config files on the fly.
    This question on Stack Overflow covers the same topic, but none of the answers are particularly satisfying. Some of the possible solutions
    are:
    Remote Desktop: as I say, I would rather not have to kick a user off their workstation
    Edit a file over a UNC path: this only works for files on a share, and setting up arbitrary shares for quick edits seems like a bad idea.
    Install some manner of ftp or ssh server on all the target computers. This would certainly work, but it is it necessary with WinRM already active? I feel like installing and configuring extra software across all the machines in my organisation would be
    a last resort.
    Edit with a command line editor (e.g. vim, emacs) over a remote powershell session. This doesn't work. I don't understand the technical details, but a powershell remote session isn't interactive in the same way that ssh connections are.
    Edit using powershell's -replace operator, out-file and add-content cmdlets. This works, but is hardly the same as a fully featured text editor.
    Retrieve content from the remote, edit locally, and post back to the remote. This works, and is arguably the best solution I've found. Code sample from SO:
    PS C:\Users\Meredith> Invoke-Command -Session $ps -ScriptBlock {get-content c:/inetpub/myapp/web.config} > web.config
    edit web config
    PS C:\Users\Meredith> get-content web.config | Invoke-Command -Session $ps -ScriptBlock {set-content c:/inetpub/myapp/web.config}
    The last two options are the workflow that I've been using for now. Regex replacement for very simple changes, and copying to local and editing there for more complicated ones. Neither is ideal, but they work. It just feels incredibly old fashioned.
    I'm considering writing a plugin to my editor of choice (vim) to perform the remote fetch and save, to make my workflow a little bit smoother. Before I try that, I just want to know if there's anything that I've missed, or misunderstood.
    Cheers

    What is the "redirector"?
    I posted the same question to Stack Overflow, and was told about administrative shares. I wasn't aware of this, and it's exactly what I wanted. I can open the filetree of a remote machine with the path \\machinename\c$\. Perfectly simple, now that I know
    the answer.

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

  • Issue creating Item Activated Events for a third party form Control in Windows Powershell

    I was asked at work to look into converting some of our VB.Net Applications to PowerShell. We use the
    QIOS dev Suite for some of the controls to make it more visually appealing. I have been testing to controls out and I can load and create forms with no issue in powershell but I'm stumped on the error I'm
    receiving when I add and ItemActivated event. I need to make it so when a user clicks on a given menu Item the form gets which menu item is clicked. 
    Below is the code to my test form.
    [VOID][reflection.assembly]::Load('System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
    [VOID][reflection.assembly]::LoadFile("C:\Code\Qios.DevSuite.Components.dll")
    [System.Windows.Forms.Application]::EnableVisualStyles()
    $form1 = New-Object 'System.Windows.Forms.Form'
    $Menu = New-Object 'Qios.DevSuite.Components.QCompositeControl'
    $item = New-Object 'Qios.DevSuite.Components.QCompositeMenuItem'
    $DOSOMETHING={Write-Host "DO SOMETHING"}
    # form1
    $form1.Controls.Add($Menu)
    $form1.ClientSize = '202, 262'
    $form1.Name = "form1"
    $form1.Text = "Form"
    $form1.add_Load($form1_Load)
    #MenuItem
    $Item.ItemName = "Test Item"
    $Item.Title = "Test Item"
    # Menu
    $Menu.Location = '13, 12'
    $Menu.Name = "panel1"
    $Menu.Size = '177, 238'
    $Menu.Items.Add($Item)
    $Menu.Add_ItemActivated($DOSOMETHING)
    $form1.ShowDialog()
    If someone could take a look and tell me what I'm doing wrong that would be great. If you need the dll file below is a link to my copy.

    I was able to get the attached code to work in windows 7 with powershell version 2. I have to see why it dosent like windows 8 and powershell version 4.
    Update: I just did powershell -version 2 in windows 8 and I was able to run the code. 
    [void][reflection.assembly]::Load('System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
    [void][reflection.assembly]::LoadFile("C:\Users\xAdmin\Desktop\Qios.DevSuite.Components.dll")
    $frmMain = New-Object 'System.Windows.Forms.Form'
    $ccMenu = New-Object 'Qios.DevSuite.Components.QCompositeControl'
    $ccitem = New-Object 'Qios.DevSuite.Components.QCompositeMenuItem'
    $Function = {
    param ($sender, $e)
    [System.Windows.Forms.MessageBox]::Show($e.Item.ItemName)
    $frmMain.Controls.Add($ccMenu)
    $frmMain.ClientSize = '202, 262'
    $frmMain.Name = "form1"
    $frmMain.Text = "Form"
    $frmMain.add_Load($form1_Load)
    $ccMenu.Location = '13, 12'
    $ccMenu.Name = "panel1"
    $ccMenu.Size = '177, 238'
    $ccMenu.Items.Add($ccitem) | Out-Null
    $ccMenu.Add_ItemActivated($Function)
    $ccitem.ItemName = "Test Item"
    $ccitem.Title = "Test Item"
    $ccitem.Configuration.StretchHorizontal = $true
    $frmMain.ShowDialog()

  • Sharepoint 2010 search service from C# web service and Powershell - passing credentials to search

    Good morning everyone,
    I really need your expert help about the following issue. I ve developed a web service in C#. Its core code has a Powershell script inside which makes a call to SharePoint 2010 search service to make some search queries, and returns some URL of some files. 
    In Powershell code I make connection to SharePoint search service using the Farm Admin account. This system works, but given results are not filetered by the user using the web service (I remember you I m using the Farm admin account in PS code)
    How can I use user account to make some queries ? How can I filter search results by user ? In Powershell code I put username and password of Farm Admin account and I know them because I m the farm administrator, but
    what about if I want to pass Powershell code some other user credentials ? Of course I cannot know his credential ..  Can I do it , in which way ?
    Any help is really appreciated !
    Gae 

    Hi Gae, if you are using web services, you shouldn't need to add a SharePoint DLL to your project. I would advise against using C# -> PS -> Web Service Call -> PS -> C# if you could go straight C# -> Web Service -> C#.
    Anyways, back to the matter at hand. Do you know what type of authentication your SharePoint server is running? Is it direct NTLM, NTLM over Kerberos, Claims, or something different?
    The following article provides the various types of impersonation available in SharePoint:
    http://extreme-sharepoint.com/2012/05/30/impersonation-elevation-of-privileges/
    Dimitri Ayrapetov (MCSE: SharePoint)

Maybe you are looking for