PowerShell / PowerShellGetv2

PowerShellGet is the Package Manager for PowerShell
https://www.PowerShellGallery.com
MIT License
432 stars 138 forks source link

Cannot convert null to type "System.DateTime". #135

Closed gluons closed 7 years ago

gluons commented 7 years ago

Expected Behavior

No error message.

Current Behavior

Get error:

default
Cannot convert null to type "System.DateTime".
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\1.1.3.1\PSModule.psm1:7060 char:17
+                 $InstalledDate = $null
+                 ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (:) [], ArgumentTransformationMetadataException
    + FullyQualifiedErrorId : RuntimeException

Possible Solution

I have no idea. I'm new to PowerShell. 😅 I've tried to update to latest with

Install-Module –Name PowerShellGet –Force

that in readme but no luck.

Steps to Reproduce (for bugs)

Use this command:

Get-InstalledModule

Context

Just annoying error messages. I don't know other thing that this error will affect.

Your Environment


> $PSVersionTable
Name                           Value
----                           -----
PSVersion                      5.1.15063.296
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.15063.296
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

> Get-Module
ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Script     0.0        chocolateyProfile                   {TabExpansion, Update-SessionEnvironment, refreshenv}
Manifest   3.1.0.0    Microsoft.PowerShell.Management     {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Content...}
Manifest   3.1.0.0    Microsoft.PowerShell.Utility        {Add-Member, Add-Type, Clear-Variable, Compare-Object...}
Script     1.1.4.0    PackageManagement                   {Find-Package, Find-PackageProvider, Get-Package, Get-PackageProvider...}
Script     1.1.3.1    PowerShellGet                       {Find-Command, Find-DscResource, Find-Module, Find-RoleCapability...}
Script     1.2        PSReadline                          {Get-PSReadlineKeyHandler, Get-PSReadlineOption, Remove-PSReadlineKeyHandler, S...

> Get-Module -ListAvailable PowerShellGet,PackageManagement
    Directory: C:\Program Files\WindowsPowerShell\Modules

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Script     1.1.4.0    PackageManagement                   {Find-Package, Get-Package, Get-PackageProvider, Get-PackageSource...}
Binary     1.0.0.1    PackageManagement                   {Find-Package, Get-Package, Get-PackageProvider, Get-PackageSource...}
Binary     1.0.0.0    PackageManagement                   {Find-Package, Get-Package, Get-PackageProvider, Get-PackageSource...}
Script     1.1.3.1    PowerShellGet                       {Install-Module, Find-Module, Save-Module, Update-Module...}
Script     1.0.0.1    PowerShellGet                       {Install-Module, Find-Module, Save-Module, Update-Module...}

> Get-PackageProvider
Name                     Version          DynamicOptions
----                     -------          --------------
msi                      3.0.0.0          AdditionalArguments
msu                      3.0.0.0
NuGet                    2.8.5.209        Destination, ExcludeVersion, Scope, SkipDependencies, Headers, FilterOnTag, Contains, AllowPrer...
PowerShellGet            1.1.3.1          PackageManagementProvider, Type, Scope, AllowClobber, SkipPublisherCheck, InstallUpdate, NoPath...
Programs                 3.0.0.0          IncludeWindowsInstaller, IncludeSystemComponent

> Get-PackageProvider -ListAvailable
Name                     Version          DynamicOptions
----                     -------          --------------
msi                      3.0.0.0          AdditionalArguments
msu                      3.0.0.0
nuget                    2.8.5.208
nuget                    2.8.5.206
NuGet                    2.8.5.209        Destination, ExcludeVersion, Scope, SkipDependencies, Headers, FilterOnTag, Contains, AllowPrer...
PowerShellGet            1.1.3.1          PackageManagementProvider, Type, Scope, AllowClobber, SkipPublisherCheck, InstallUpdate, NoPath...
PowerShellGet            1.0.0.1
Programs                 3.0.0.0          IncludeWindowsInstaller, IncludeSystemComponent
bmanikm commented 7 years ago

@gluons Could you please get the output of following commands to investigate on this issue?

[System.Globalization.DateTimeFormatInfo]::CurrentInfo
[System.Globalization.DateTimeFormatInfo]::InvariantInfo

#==========
$InstalledDateString = (Get-Date).ToString()
$InstalledDate = New-Object System.DateTime
if(-not ([System.DateTime]::TryParse($InstalledDateString, ([ref]$InstalledDate))))
{
    $InstalledDate = $null
}
$InstalledDate

#==========
$Path = "$env:ProgramFiles\WindowsPowerShell\Modules\PowerShellGet\1.1.3.1\PSGetModuleInfo.xml"
$filecontent = Microsoft.PowerShell.Management\Get-Content -Path $Path
$PSGModuleInfo = [System.Management.Automation.PSSerializer]::Deserialize($filecontent)
$PSGModuleInfo.InstalledDate

#==========
Get-Package -Provider PowerShellGet | Format-List * -Force

#==========
$p = Get-Package -Provider PowerShellGet -Name PowerShellGet
$p.Metadata["installeddate"]
$InstalledDateString = $p.Metadata["installeddate"]
$InstalledDate = New-Object System.DateTime
[System.DateTime]::TryParse($InstalledDateString, ([ref]$InstalledDate))
$InstalledDate

#=====================

function Get-First 
{
    param
    (
        [Parameter(Mandatory=$true)]
        $IEnumerator
    ) 

    foreach($item in $IEnumerator)
    {
        return $item
    }

    return $null
}

$InstalledDateString = (Get-First $swid.Metadata['installeddate'])
$InstalledDateString
$InstalledDate = New-Object System.DateTime
[System.DateTime]::TryParse($InstalledDateString, ([ref]$InstalledDate))
$InstalledDate
gluons commented 7 years ago

@bmanikm This is content output of your script: log.txt

I got some error at the end.

default
Cannot index into a null array.
At C:\Users\<username>\Desktop\script.ps1:51 char:1
+ $InstalledDateString = (Get-First $swid.Metadata['installeddate'])
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray
bmanikm commented 7 years ago

@gluons From the log.txt, it looks like you have changed the date & time format from 24 hour to 12 hour after installing the modules. Please uninstall these versions manually and try again with the current date & time format settings.

Date        : 5/31/2017 12:00:00 AM
Day         : 31
DayOfWeek   : Wednesday
DayOfYear   : 151
Hour        : 9
Kind        : Unspecified
Millisecond : 0
Minute      : 26
Month       : 5
Second      : 35
Ticks       : 636318195950000000
TimeOfDay   : 09:26:35
Year        : 2017
DateTime    : Wednesday, May 31, 2017 9:26:35 AM
installeddate="29/5/2560 15:54:53"
PS C:\> $InstalledDateString="29/5/2560 15:54:53"
PS C:\> $InstalledDate = New-Object System.DateTime
PS C:\> [System.DateTime]::TryParse($InstalledDateString, ([ref]$InstalledDate))
False
gluons commented 7 years ago

I honestly have never change date & time format after install. But I got Anniversary Update and Creators Update. 😳

I've tried to reinstall but not work. 🤔

Reinstall Output ```powershell C:\Users\> Uninstall-Module -Name PowerShellGet -Force C:\Users\> Install-Module -Name PowerShellGet -Force WARNING: The version '1.1.4.0' of module 'PackageManagement' is currently in use. Retry the operation after closing the applications. C:\Users\> Uninstall-Module -Name PowerShellGet -Force C:\Users\> Get-InstalledModule Cannot convert null to type "System.DateTime". At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\1.1.3.1\PSModule.psm1:7060 char:17 + $InstalledDate = $null + ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException + FullyQualifiedErrorId : RuntimeException Version Name Repository Description ------- ---- ---------- ----------- 1.1.4.0 PackageManagement PSGallery PackageManagement (a.k.a. OneGet) is a new way to discover and instal... Cannot convert null to type "System.DateTime". At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\1.1.3.1\PSModule.psm1:7060 char:17 + $InstalledDate = $null + ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException + FullyQualifiedErrorId : RuntimeException 0.7.1 posh-git PSGallery Provides prompt with Git status summary information and tab completio... C:\Users\> Install-Module -Name PowerShellGet -Force WARNING: The version '1.1.4.0' of module 'PackageManagement' is currently in use. Retry the operation after closing the applications. C:\Users\> Get-InstalledModule Cannot convert null to type "System.DateTime". At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\1.1.3.1\PSModule.psm1:7060 char:17 + $InstalledDate = $null + ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException + FullyQualifiedErrorId : RuntimeException Version Name Repository Description ------- ---- ---------- ----------- 1.1.4.0 PackageManagement PSGallery PackageManagement (a.k.a. OneGet) is a new way to discover and instal... Cannot convert null to type "System.DateTime". At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\1.1.3.1\PSModule.psm1:7060 char:17 + $InstalledDate = $null + ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException + FullyQualifiedErrorId : RuntimeException 0.7.1 posh-git PSGallery Provides prompt with Git status summary information and tab completio... 1.1.3.1 PowerShellGet PSGallery PowerShell module with commands for discovering, installing, updating... ```

My laptop always use this format: 29/5/2560 15:54:53 Default by Windows (Thai):

default

Sorry, I've no idea now. I'm new to PowerShell. 😅

bmanikm commented 7 years ago

@gluons Thanks for the additional details. This is not related to Anniversary Update and Creators Update. I am not sure why your PowerShell Console has different date time format than other threads spawned within the same process.

# Your PowerShell Console output
Date        : 5/31/2017 12:00:00 AM
Day         : 31
DayOfWeek   : Wednesday
DayOfYear   : 151
Hour        : 9
Kind        : Unspecified
Millisecond : 0
Minute      : 26
Month       : 5
Second      : 35
Ticks       : 636318195950000000
TimeOfDay   : 09:26:35
Year        : 2017
DateTime    : Wednesday, May 31, 2017 9:26:35 AM

Do you have any specific instructions for setting up a repro machine for this language and date & time format? I will try to repro it locally on a Windows 10 machine.

gluons commented 7 years ago

My Windows is Windows 10 Pro 64-bits (Thai version). Now, my Windows version is 1703. And my build version is 15063.332.

My region, language and date/time are Thailand/Thai. (Default after installed)

My Windows is installed before Anniversary Update and Creators Update and get these upgrade later.


I've tried something from your script ```powershell C:\Users\> $p = Get-Package -Provider PowerShellGet -Name PowerShellGet >> $p.Metadata["installeddate"] >> $InstalledDateString = $p.Metadata["installeddate"] >> $InstalledDate = New-Object System.DateTime >> [System.DateTime]::TryParse($InstalledDateString, ([ref]$InstalledDate)) >> $InstalledDate 1/6/2560 9:54:38 True Sunday, January 6, 2560 9:54:38 AM ``` ```powershell C:\Users\> $InstalledDateString = (Get-Date).ToString() >> $InstalledDateString >> $InstalledDate = New-Object System.DateTime >> [System.DateTime]::TryParse($InstalledDateString, ([ref]$InstalledDate)) >> $InstalledDate 6/1/2017 1:48:16 PM True Thursday, June 1, 2017 1:48:16 PM ```


I'm so confused. haha 🙄

bmanikm commented 7 years ago

@gluons Until this issue is understood and resolved, please use the following workaround on your machine. Comment line 7060 in PSModule.psm1 file by putting # at the beginning of this line and restart the PowerShell Console then run Get-InstalledModule cmdlet.

C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\1.1.3.1\PSModule.psm1:7060

# $InstalledDate = $null
gluons commented 7 years ago

Thanks. That error gone for now.

bmanikm commented 7 years ago

@gluons Could you please verify whether https://github.com/bmanikm/PowerShellGet/commit/9f6d9b674e6b7352254a91a8abf24a86bc34355f fixes the issue on your machine?

Please get the output of following commands from your machine.

# Open an admin PowerShell Console

# Rename existing PSModule.psm1 to PSModule.psm1_backup
Rename-Item "$env:ProgramFiles\WindowsPowerShell\Modules\PowerShellGet\1.1.3.1\PSModule.psm1" "$env:ProgramFiles\WindowsPowerShell\Modules\PowerShellGet\1.1.3.1\PSModule.psm1_backup"

# Copy new PSModule.psm1 file from https://raw.githubusercontent.com/bmanikm/PowerShellGet/datetimeserializationfix/PowerShellGet/PSModule.psm1
Invoke-WebRequest -Uri https://raw.githubusercontent.com/bmanikm/PowerShellGet/datetimeserializationfix/PowerShellGet/PSModule.psm1 -OutFile "$env:ProgramFiles\WindowsPowerShell\Modules\PowerShellGet\1.1.3.1\PSModule.psm1" -Verbose

# Now open a new PowerShell Console and try following commands.
Get-InstalledModule | fl *
Get-Package -Provider PowerShellGet | fl * -Force

Install-Module posh-git -Repository PSGallery -Force
Get-Package -Provider PowerShellGet -Name posh-git | fl * -Force
Get-InstalledModule -Name posh-git | fl * -Force

# If the copied PSModule.psm1 file is not working fine, rename the backup file back to PSModule.psm1
Rename-Item "$env:ProgramFiles\WindowsPowerShell\Modules\PowerShellGet\1.1.3.1\PSModule.psm1_backup" "$env:ProgramFiles\WindowsPowerShell\Modules\PowerShellGet\1.1.3.1\PSModule.psm1" -Force
gluons commented 7 years ago

@bmanikm OK. This is output from you script: log.txt

PetRose commented 5 years ago

Had the same issue with my Win10 64bit, and I noticed I had a difference ($host) between CurrentCulture and CurrentUICulture (switching among different Keyboard layout and Language settings). I tried to set them equal, and voila: the Error did not occur. Neither with Update-Modulel nor Get-Module. So its indeed a Language/Locale 'thing' causing this. Thus I did not need to tweak the PSModule.psm1 and even if I could, I no longer had that line #7060 to patch due to later versions now on my developer laptop.