none
intermittent : The term 'get-date' is not recognized as the name of a cmdlet, function, script file, or operable program. RRS feed

  • Question

  • I have developed a batch harness whereby all scheduled tasks (W2012) invoke a common powershell script that acts as a wrapper to all our housekeeping jobs.

    The first step in the wrapper is to create a Transcript file using following code

    if ($Host.name -ne "Windows PowerShell ISE Host") # Transcript does not work within ISE
    {
    $timestamp = (get-date -format "yyyy-MM-dd-HH-mm-ss.fff")
    $path = "c:\corp\$timestamp" + "_$pid.txt"
    Start-Transcript -path $path -append
    }

    As expected the folder contains files with timestamp & pid in name

    08/08/2013  11:00 AM            14,388 2013-08-08-11-00-01.158_1620.txt
    08/08/2013  11:00 AM            12,506 2013-08-08-11-00-01.485_936.txt
    08/08/2013  11:00 AM            12,994 2013-08-08-11-00-01.735_9328.txt
    08/08/2013  11:00 AM            12,024 2013-08-08-11-00-01.766_8624.txt
    08/08/2013  11:00 AM            13,902 2013-08-08-11-00-01.860_1756.txt
    08/08/2013  11:01 AM            15,142 2013-08-08-11-01-31.392_10120.txt
    08/08/2013  05:00 AM            14,982 _1692.txt

    However note the last file, it has a zero length date time value in the name

    The error recorded by PowerShell is

    get-date : The term 'get-date' is not recognized as the name of a cmdlet, function, script file, or operable program.
    Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
    At C:\Corp\Powershell\DMPRun-ScheduledTask.ps1:171 char:18
    +    $timestamp = (get-date -format "yyyy-MM-dd-HH-mm-ss.fff")
    +                  ~~~~~~~~
        + CategoryInfo          : ObjectNotFound: (get-date:String) [], CommandNotFoundException
        + FullyQualifiedErrorId : CommandNotFoundException

    IE get-date has failed and returned a zero length field as the timestamp

    Can anyone think of a good reason why get-date would fail intermittently?

    Do I have to code defensively for base Powershell functions?

    Thursday, August 8, 2013 3:46 AM

Answers

  • Microsoft support have identified that this problem is fixed in Powershell 4. My testing confirms this assertion.

    'It is a known issue caused by improper security settings for mutex “PowerShell_CommandAnalysis_Lock”, '

    Thursday, January 23, 2014 9:40 PM

All replies

  • That is really weird... I have no idea what could be causing the error, but you could try to work around it by using the .NET class directly:

    $timestamp = [System.DateTime]::Now.ToString("yyyy-MM-dd-HH-mm-ss.fff")

    Thursday, August 8, 2013 4:33 AM
  • cant seem to reproduce it, whats your full code?
    Thursday, August 8, 2013 1:43 PM
  • Hi,

    I can't reproduce the issue, I would like to suggest you open a new Windows ISE window and run get-date command again.

    Regards,

    Yan Li

    TechNet Subscriber Support

    If you are TechNet Subscription user and have any feedback on our support quality, please send your feedback here.


    Cataleya Li
    TechNet Community Support

    Friday, August 9, 2013 5:59 AM
    Moderator
  • I am not running in ISE.

    It is being invoked from Scheduled Task.

    It is intermittent, In fact it has happened once in last 1000 invocations.

    I suspect it is related to other activity happening at the same time (There were 5 scheduled tasks triggered at 5 AM that all called this code. 4 worked, one exhibited the symptom).

    It may even be something else happening on the server like virus scan, backups etc.

    My concern is that I am building a complete housekeeping environment based on scheduled tasks invoking powershell and logging to files and I got this basic error in the fundamental framework. 

    What I was looking for was some clues on how to identify root cause. IE Some debugging switch that would enable a detailed log of powershell activity under the covers.

     

    Friday, August 9, 2013 6:24 AM
  • Glad this thread is active right now, because guess what?

    I had exactly the same problem with a scheduled task last night.

    Get-Date : The term 'Get-Date' is not recognized as the name of a cmdlet,   function, script file, or operable program. Check the spelling of the name, or   if a path was included, verify that the path is correct and try again.  

    The interesting thing is that the same script gets called in the next step (less than a second later) with different params and runs fine. When I reran the task this morning (unchanged) it runs fine. 

    There is clearly something odd about this. 



    Friday, August 9, 2013 8:29 AM
  • Friday, August 9, 2013 1:05 PM
    Moderator
  • I have also been getting this message.  We have several scripts that run from Scheduled Tasks, some as often as once per minute that monitor queues for user provisioning.  I've seen this message with the 'get-date' command as well as even the 'Test-Path' command.  It's almost like PowerShell isn't completely loading the command library.  We'll see a message saying that 'get-date' is not recognized, then the next minute when the same script runs it runs without error.  Then possibly an hour two later we'll get another message.  It seems to come and go over time (we've been running these Scheduled Tasks for over a year) but they've definitely starting to happen more often lately.

    This is the first post where I've actually found someone else having the same issue.


    • Edited by Blando Monday, August 12, 2013 2:26 PM
    Monday, August 12, 2013 2:25 PM
  • Monday, August 12, 2013 2:49 PM
    Moderator
  • Hi,

    Just checking in to see if the suggestions were helpful. Please let us know if you would like further assistance.

    TechNet Subscriber Support

    If you are TechNet Subscription user and have any feedback on our support quality, please send your feedback here.


    Cataleya Li
    TechNet Community Support

    Thursday, August 15, 2013 9:03 AM
    Moderator
  • Sorry for the delay

    I now have some simple steps that enable the problem to be reproduced (fingers-crossed)

    Create a scheduled task to be run when user is not logged on.

    the schedule task should have an action

    Powershell.exe "C:\jctest.BAT"

    C:\jctest.BAT should look like this..

    :TheLoop
     powershell.exe c:\jccheck1.ps1 >>c:\jccheck1.txt 2>&1
     ping 127.0.0.1 -n 005 >NUL
     goto :TheLoop

    IE loop ever 5 seconds creating a poweshell envionment and running a powershell script

    c:\jccheck1.ps1 should look like this..

    trap {
    "Exception: " + $_
    "Error: " + $Error[0]
    "Message: " + $_.Exception.Message
    "InnerException: " + $_.Exception.InnerException
    "StackTrace: " + $_.Exception.StackTrace
    "FailedItem: " + $_.Exception.ItemName
    }

    get-date

    IE print date and exit

    Start scheduled task and monitor what gets put into c:\jcchcek1.txt

    In my case


    Thursday, 15 August 2013 1:14:21 PM
    Thursday, 15 August 2013 1:14:25 PM
    ...
    ...

    Thursday, 15 August 2013 1:38:40 PM

    Thursday, 15 August 2013 1:38:45 PM


    Exception: The term 'get-date' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
    Error: The term 'get-date' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
    Message: The term 'get-date' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
    InnerException:
    StackTrace:    at System.Management.Automation.CommandDiscovery.LookupCommandInfo(String commandName, CommandTypes commandTypes, SearchResolutionOptions searchResolutionOptions, CommandOrigin commandOrigin, ExecutionContext context)
       at System.Management.Automation.CommandDiscovery.LookupCommandProcessor(String commandName, CommandOrigin commandOrigin, Nullable`1 useLocalScope)
       at System.Management.Automation.ExecutionContext.CreateCommand(String command, Boolean dotSource)
       at System.Management.Automation.PipelineOps.AddCommand(PipelineProcessor pipe, CommandParameterInternal[] commandElements, CommandBaseAst commandBaseAst, CommandRedirection[] redirections, ExecutionContext context)
       at System.Management.Automation.PipelineOps.InvokePipeline(Object input, Boolean ignoreInput, CommandParameterInternal[][] pipeElements, CommandBaseAst[] pipeElementAsts, CommandRedirection[][] commandRedirections, FunctionContext funcContext)
       at System.Management.Automation.Interpreter.ActionCallInstruction`6.Run(InterpretedFrame frame)
       at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
    FailedItem:
    get-date : The term 'get-date' is not recognized as the name of a cmdlet,
    function, script file, or operable program. Check the spelling of the name, or
    if a path was included, verify that the path is correct and try again.
    At C:\jccheck1.ps1:10 char:1
    + get-date
    + ~~~~~~~~
        + CategoryInfo          : ObjectNotFound: (get-date:String) [], CommandNot
       FoundException
        + FullyQualifiedErrorId : CommandNotFoundException

    Thursday, 15 August 2013 1:38:54 PM
    Thursday, 15 August 2013 1:38:59 PM
    ...
    ...

    Thursday, 15 August 2013 5:41:47 PM
    Thursday, 15 August 2013 5:41:51 PM

    Make sure you kill the scheduled task before c drive fills up !!!

    Thursday, August 15, 2013 9:55 AM
  • I just ran into this same problem today, but it happened interactively while I was testing some code in the ISE.  As a result, I was able to do a bit of troubleshooting before I closed the window.

    In my case, the error was with ConvertTo-SecureString.  I'm not sure how it happened, but the Microsoft.PowerShell.Security module which contains that cmdlet was not loaded (though it still showed up in Get-Module -ListAvailable), and on top of that, the PowerShell feature that's supposed to automatically load modules wasn't helping.

    I was able to run the command Import-Module Microsoft.PowerShell.Security , and the command worked fine after that.

    Get-Date is in a different module, Microsoft.PowerShell.Utility, but I assume the same workaround would help here.  It may be worthwhile to put these commands at the beginning of your script, until such time as the underlying bug is found and fixed:

    Import-Module Microsoft.PowerShell.Management
    Import-Module Microsoft.PowerShell.Utility


    • Edited by David Wyatt Sunday, November 24, 2013 3:09 PM
    Sunday, November 24, 2013 3:06 PM
  • I implemented David's suggestion and now I intermittently get

    import-module : Access to the path 'PowerShell_CommandAnalysis_Lock' is denied.
    At D:\temp\loop_jc2_2013_11_25_08_55_02.ps1:15 char:1
    + import-module Microsoft.Powershell.Utility
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [Import-Module], UnauthorizedA
       ccessException
        + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.Pow
       erShell.Commands.ImportModuleCommand

    I added a trap chain (My Powershell skills do not yet include recursive trap coding, any suggestions welcome)

    trap {
        trap {
            "Trap1"
            "Exception: " + $_
            "Error: " + $Error[0]
            "Message: " + $_.Exception.Message
            "InnerException: " + $_.Exception.InnerException
            "StackTrace: " + $_.Exception.StackTrace
            "FailedItem: " + $_.Exception.ItemName
            import-module Microsoft.Powershell.Management
            import-module Microsoft.Powershell.Security
            import-module Microsoft.Powershell.Utility
            }
        "Trap2"
        "Exception: " + $_
        "Error: " + $Error[0]
        "Message: " + $_.Exception.Message
        "InnerException: " + $_.Exception.InnerException
        "StackTrace: " + $_.Exception.StackTrace
        "FailedItem: " + $_.Exception.ItemName
        import-module Microsoft.Powershell.Management
        import-module Microsoft.Powershell.Security
        import-module Microsoft.Powershell.Utility
        }
    import-module Microsoft.Powershell.Management
    import-module Microsoft.Powershell.Security
    import-module Microsoft.Powershell.Utility
    trap {
        "Trap3"
        "Exception: " + $_
        "Error: " + $Error[0]
        "Message: " + $_.Exception.Message
        "InnerException: " + $_.Exception.InnerException
        "StackTrace: " + $_.Exception.StackTrace
        "FailedItem: " + $_.Exception.ItemName
        exit 1
        }

    get-date

    Now I intermittently get ..

    Trap2
    Exception: Access to the path 'PowerShell_CommandAnalysis_Lock' is denied.
    Error: Access to the path 'PowerShell_CommandAnalysis_Lock' is denied.
    Message: Access to the path 'PowerShell_CommandAnalysis_Lock' is denied.
    InnerException:
    StackTrace:    at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
       at System.Threading.Mutex.MutexTryCodeHelper.MutexTryCode(Object userData)
       at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
       at System.Threading.Mutex.CreateMutexWithGuaranteedCleanup(Boolean initiallyOwned, String name, Boolean& createdNew, SECURITY_ATTRIBUTES secAttrs)
       at System.Threading.Mutex..ctor(Boolean initiallyOwned, String name, Boolean& createdNew, MutexSecurity mutexSecurity)
       at System.Threading.Mutex..ctor(Boolean initiallyOwned, String name, Boolean& createdNew)
       at System.Management.Automation.AnalysisCache.CacheExportedCommands(PSModuleInfo module, Boolean force, ExecutionContext context)
       at Microsoft.PowerShell.Commands.ModuleCmdletBase.LoadUsingModulePath(PSModuleInfo parentModule, Boolean found, IEnumerable`1 modulePath, String name, SessionState ss, ImportModuleOptions options, ManifestProcessingFlags manifestProcessingFlags, PSModuleInfo& module)
       at Microsoft.PowerShell.Commands.ImportModuleCommand.ImportModule_LocallyViaName(ImportModuleOptions importModuleOptions, String name)
       at Microsoft.PowerShell.Commands.ImportModuleCommand.ProcessRecord()
       at System.Management.Automation.CommandProcessor.ProcessRecord()
    FailedItem:
    import-module : Access to the path 'PowerShell_CommandAnalysis_Lock' is denied.
    At D:\temp\loop_jc2_2013_11_25_09_19_52.ps1:26 char:1
    + import-module Microsoft.Powershell.Security
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [Import-Module], UnauthorizedA
       ccessException
        + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.Pow
       erShell.Commands.ImportModuleCommand
     

    Monday, November 25, 2013 1:31 AM
  • A summary of what I now know

    • Problem only occurs when you have multiple scheduled tasks invoking powershell and the users associated with the scheduled tasks are not administrators.
    • Problem has been reproduced on Windows 8 desktop and Windows Server 2012
    • Problem is related to failure of Powershell to automatically load modules when a second scheduled task is at a particular point loading modules itself
    • Following code inserted at the start of any Powershell script will mitigate problem by retrying until second scheduled task has completed its processing.
    • The code has the potential for a race condition (where both scheduled tasks continually conflict). I have seen this occur, but so far it has always resolved itself within 4 iterations.
     

       $Done = 0
        $Count = 0

        while ($done -eq 0 -and $count -lt 1000)
        {
            Try
            {
                import-module Microsoft.Powershell.Management
                import-module Microsoft.Powershell.Security
                import-module Microsoft.Powershell.Utility
                $Done = 1
            }
            Catch
            {
                $Count = $count + 1
            }
        }
        if ($count -gt 0)
        {
            $error.clear()
            Write-EventLog -EventId $($count + 700) -LogName Application -Message "Count = $count" -Source "DBA TASK"
        }

    The biggest value for Count that I have seen so far is 4

    Wednesday, November 27, 2013 10:13 PM
  • Great info!  Have you posted a bug report over on http://connect.microsoft.com/PowerShell yet?

    Thursday, November 28, 2013 12:55 AM
  • Microsoft support have identified that this problem is fixed in Powershell 4. My testing confirms this assertion.

    'It is a known issue caused by improper security settings for mutex “PowerShell_CommandAnalysis_Lock”, '

    Thursday, January 23, 2014 9:40 PM
  • I'm encountering this exact issue in Powershell 5.0.  Running scheduled tasks with non-admin users causes commandlets like get-date to occasionally fail.

    Is there anything that needs to be done to get the fix applied that was in Powershell 4?

    Wednesday, February 1, 2017 9:52 PM
  • Install PowerShell 4 or 5


    \_(ツ)_/

    Wednesday, February 1, 2017 11:22 PM
    Moderator
  • I'm encountering this exact issue in Powershell 5.0.  Running scheduled tasks with non-admin users causes commandlets like get-date to occasionally fail.

    Is there anything that needs to be done to get the fix applied that was in Powershell 4?


    Any typos with versions here?
    Thursday, February 2, 2017 12:28 AM
  • I observe the same issue randomly on my machine all do is open up another console. :)

    It logs a event like below:

    Error Message = This command cannot be run due to the error: The system cannot find the file specified.
    Fully Qualified Error ID = InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand


    Thursday, February 2, 2017 6:42 AM
  • No typo there.  I'm definitely running Powershell 5.0 on Windows 2012R2.  My scheduled task still gives an occasional "error: The term 'Get-Date' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again."

    My PSVersionTable:

    PS U:\> $PSVersionTable

    Name                           Value
    ----                           -----
    PSVersion                      5.0.10514.6
    WSManStackVersion              3.0
    SerializationVersion           1.1.0.1
    CLRVersion                     4.0.30319.42000
    BuildVersion                   10.0.10514.6
    PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
    PSRemotingProtocolVersion      2.3

    Tuesday, February 14, 2017 10:27 PM
  • I upgraded to Powershell 5.1 and this bug appears to be resolved for me.
    Friday, February 24, 2017 8:05 PM