How to avoid “You cannot call a method on a null-valued expression” error when file might be empty?












1















I want to open a file, replace some content, and append to another file. I wrote a Powershell script:



(Get-Content file.txt).replace("abc", "def") | Add-Content other.txt


This works fine, unless file.txt is empty. Then it gives an error




You cannot call a method on a null-valued expression.




Why does it give that error? And how can I avoid it?



I expected opening an empty file to return empty rather than null, as it would in unix



cat file.txt | sed -r s/abc/def/g >> other.txt









share|improve this question





























    1















    I want to open a file, replace some content, and append to another file. I wrote a Powershell script:



    (Get-Content file.txt).replace("abc", "def") | Add-Content other.txt


    This works fine, unless file.txt is empty. Then it gives an error




    You cannot call a method on a null-valued expression.




    Why does it give that error? And how can I avoid it?



    I expected opening an empty file to return empty rather than null, as it would in unix



    cat file.txt | sed -r s/abc/def/g >> other.txt









    share|improve this question



























      1












      1








      1


      0






      I want to open a file, replace some content, and append to another file. I wrote a Powershell script:



      (Get-Content file.txt).replace("abc", "def") | Add-Content other.txt


      This works fine, unless file.txt is empty. Then it gives an error




      You cannot call a method on a null-valued expression.




      Why does it give that error? And how can I avoid it?



      I expected opening an empty file to return empty rather than null, as it would in unix



      cat file.txt | sed -r s/abc/def/g >> other.txt









      share|improve this question
















      I want to open a file, replace some content, and append to another file. I wrote a Powershell script:



      (Get-Content file.txt).replace("abc", "def") | Add-Content other.txt


      This works fine, unless file.txt is empty. Then it gives an error




      You cannot call a method on a null-valued expression.




      Why does it give that error? And how can I avoid it?



      I expected opening an empty file to return empty rather than null, as it would in unix



      cat file.txt | sed -r s/abc/def/g >> other.txt






      .net powershell






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 21 '18 at 13:54







      Colonel Panic

















      asked Nov 21 '18 at 12:20









      Colonel PanicColonel Panic

      81k61301393




      81k61301393
























          3 Answers
          3






          active

          oldest

          votes


















          3














          Use PowerShell's -Replace operator instead of the Replace method of the returned String (being null for an empty file).



          (Get-Content file.txt) -Replace "abc", "def" | Add-Content other.txt





          share|improve this answer

































            0














            $path = "test.txt"
            $path2 = "test2.txt"

            try{
            $content = (Get-Content $path).replace("abc", "def") | Add-Content $path2
            Write-Host "Successfully added content" -ForegroundColor Green
            }catch{
            if(!$content){
            Write-Host "$path is empty" -ForegroundColor Yellow
            }else{
            throw $_
            }
            }


            I think you should always work with try/catch when running cmdlets..



            Hope this helps






            share|improve this answer































              0














              Give this a shot:



              (Get-Content file.txt).replace("abc", "def") | Add-Content other.txt -erroraction SilentlyContinue


              There are other options for the type of erroraction, so just use tab completion to view them and test them if SilentlyContinue does not do what you're looking for!



              EDIT: If you need to know that something has failed because it is empty, please view Bernard's answer. Otherwise this one liner should work as well, just depends on what your needs are.






              share|improve this answer

























                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53411902%2fhow-to-avoid-you-cannot-call-a-method-on-a-null-valued-expression-error-when-f%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                3 Answers
                3






                active

                oldest

                votes








                3 Answers
                3






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                3














                Use PowerShell's -Replace operator instead of the Replace method of the returned String (being null for an empty file).



                (Get-Content file.txt) -Replace "abc", "def" | Add-Content other.txt





                share|improve this answer






























                  3














                  Use PowerShell's -Replace operator instead of the Replace method of the returned String (being null for an empty file).



                  (Get-Content file.txt) -Replace "abc", "def" | Add-Content other.txt





                  share|improve this answer




























                    3












                    3








                    3







                    Use PowerShell's -Replace operator instead of the Replace method of the returned String (being null for an empty file).



                    (Get-Content file.txt) -Replace "abc", "def" | Add-Content other.txt





                    share|improve this answer















                    Use PowerShell's -Replace operator instead of the Replace method of the returned String (being null for an empty file).



                    (Get-Content file.txt) -Replace "abc", "def" | Add-Content other.txt






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 21 '18 at 17:48

























                    answered Nov 21 '18 at 17:29









                    pfxpfx

                    5,270121934




                    5,270121934

























                        0














                        $path = "test.txt"
                        $path2 = "test2.txt"

                        try{
                        $content = (Get-Content $path).replace("abc", "def") | Add-Content $path2
                        Write-Host "Successfully added content" -ForegroundColor Green
                        }catch{
                        if(!$content){
                        Write-Host "$path is empty" -ForegroundColor Yellow
                        }else{
                        throw $_
                        }
                        }


                        I think you should always work with try/catch when running cmdlets..



                        Hope this helps






                        share|improve this answer




























                          0














                          $path = "test.txt"
                          $path2 = "test2.txt"

                          try{
                          $content = (Get-Content $path).replace("abc", "def") | Add-Content $path2
                          Write-Host "Successfully added content" -ForegroundColor Green
                          }catch{
                          if(!$content){
                          Write-Host "$path is empty" -ForegroundColor Yellow
                          }else{
                          throw $_
                          }
                          }


                          I think you should always work with try/catch when running cmdlets..



                          Hope this helps






                          share|improve this answer


























                            0












                            0








                            0







                            $path = "test.txt"
                            $path2 = "test2.txt"

                            try{
                            $content = (Get-Content $path).replace("abc", "def") | Add-Content $path2
                            Write-Host "Successfully added content" -ForegroundColor Green
                            }catch{
                            if(!$content){
                            Write-Host "$path is empty" -ForegroundColor Yellow
                            }else{
                            throw $_
                            }
                            }


                            I think you should always work with try/catch when running cmdlets..



                            Hope this helps






                            share|improve this answer













                            $path = "test.txt"
                            $path2 = "test2.txt"

                            try{
                            $content = (Get-Content $path).replace("abc", "def") | Add-Content $path2
                            Write-Host "Successfully added content" -ForegroundColor Green
                            }catch{
                            if(!$content){
                            Write-Host "$path is empty" -ForegroundColor Yellow
                            }else{
                            throw $_
                            }
                            }


                            I think you should always work with try/catch when running cmdlets..



                            Hope this helps







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 21 '18 at 12:37









                            Bernard MoeskopsBernard Moeskops

                            27826




                            27826























                                0














                                Give this a shot:



                                (Get-Content file.txt).replace("abc", "def") | Add-Content other.txt -erroraction SilentlyContinue


                                There are other options for the type of erroraction, so just use tab completion to view them and test them if SilentlyContinue does not do what you're looking for!



                                EDIT: If you need to know that something has failed because it is empty, please view Bernard's answer. Otherwise this one liner should work as well, just depends on what your needs are.






                                share|improve this answer






























                                  0














                                  Give this a shot:



                                  (Get-Content file.txt).replace("abc", "def") | Add-Content other.txt -erroraction SilentlyContinue


                                  There are other options for the type of erroraction, so just use tab completion to view them and test them if SilentlyContinue does not do what you're looking for!



                                  EDIT: If you need to know that something has failed because it is empty, please view Bernard's answer. Otherwise this one liner should work as well, just depends on what your needs are.






                                  share|improve this answer




























                                    0












                                    0








                                    0







                                    Give this a shot:



                                    (Get-Content file.txt).replace("abc", "def") | Add-Content other.txt -erroraction SilentlyContinue


                                    There are other options for the type of erroraction, so just use tab completion to view them and test them if SilentlyContinue does not do what you're looking for!



                                    EDIT: If you need to know that something has failed because it is empty, please view Bernard's answer. Otherwise this one liner should work as well, just depends on what your needs are.






                                    share|improve this answer















                                    Give this a shot:



                                    (Get-Content file.txt).replace("abc", "def") | Add-Content other.txt -erroraction SilentlyContinue


                                    There are other options for the type of erroraction, so just use tab completion to view them and test them if SilentlyContinue does not do what you're looking for!



                                    EDIT: If you need to know that something has failed because it is empty, please view Bernard's answer. Otherwise this one liner should work as well, just depends on what your needs are.







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Nov 21 '18 at 12:39

























                                    answered Nov 21 '18 at 12:23









                                    cet51cet51

                                    668421




                                    668421






























                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53411902%2fhow-to-avoid-you-cannot-call-a-method-on-a-null-valued-expression-error-when-f%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        MongoDB - Not Authorized To Execute Command

                                        in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

                                        How to fix TextFormField cause rebuild widget in Flutter