locked
You cannot call a method on a null-valued expression. RRS feed

  • Question

  • $in = [string]$args
    
    $files = Get-ChildItem *.properties
    $fileExists = $false
    
    $dict = @{}
    
    foreach ($file in $files) {
        if ([System.IO.Path]::GetFileName($file) -eq $in) {
            $fileExists = $true
            $data = [System.IO.Path]::GetFileName($file)
        }
    }
    
    if ($fileExists) {
        foreach($line in Get-Content $data) {
            $words = $line.split('=', 2)
            $dict.add($words[0].Trim(), $words[1].Trim())
             
        }
    } else {
        Write-Host "Doesn't exists"
    }
    When i try to run this code. I am getting You cannot call a method on a null-valued expression. this error. Where I am doing wrong? 
    Tuesday, March 12, 2019 7:39 AM

All replies

  • If you don't like us to guess you should provide the complete error message you've got (formatted as code as well please).

    Live long and prosper!

    (79,108,97,102|%{[char]$_})-join''

    Tuesday, March 12, 2019 8:31 AM
  • "complete error message"

    \_(ツ)_/

    Tuesday, March 12, 2019 11:20 AM
  • I strongly suggest that you start by learning basic PowerShell.  Your code is just a bunch of very bad guesses.  There are too many mistakes to even know where to begin.

          Microsoft Virtual     Academy - Getting Started with Microsoft PowerShell

          PowerShell Documentation

          PowerShell Style   Guidelines


    \_(ツ)_/

    Tuesday, March 12, 2019 11:23 AM
  • To begin with "$args" is an array.  Use Param instead.

    Param(
         [string]$InFile
    )

    To get a file by name:

    if($file = Get-Item $InFile){
        # file found process file
    }else{
        # file not found
    }
    


    \_(ツ)_/

    Tuesday, March 12, 2019 11:27 AM
  • Hi,

    Was your issue resolved?

    If you resolved it using our solution, please "mark it as answer" to help other community members find the helpful reply quickly.

    If you resolve it using your own solution, please share your experience and solution here. It will be very beneficial for other community members who have similar questions.

    If no, please reply and tell us the current situation in order to provide further help.

    Best Regards,

    Lee


    Just do it.

    Sunday, March 31, 2019 1:19 PM
  • What's the full error message?  The split failing would cause that, with words[1] being $null.
    • Edited by JS2010 Sunday, March 31, 2019 2:30 PM
    Sunday, March 31, 2019 2:30 PM