How to copy paste code in powershell 5

This topic contains 4 replies, has 2 voices, and was last updated by  SABYASACHI MOHAPATRA 5 months, 2 weeks ago.

  • Author
    Posts
  • #69643

    I want o run code in powershell 5 installed wjindows server 2016 to show be ayatem uptime.How to save script from current powershell terminal and get the answer. for example
    function Get-Uptime {
    $os = Get-WmiObject win32_operatingsystem
    $uptime = (Get-Date) – ($os.ConvertToDateTime($os.lastbootuptime))
    $Display = "Uptime: " + $Uptime.Days + " days, " + $Uptime.Hours + " hours, " + $Uptime.Minutes + " minutes"
    Write-Output $Display
    }
    I want the exact steps to execute this in powershell.

  • #69645

    Brian Douglas
    Participant

    Hi,
    I'm not sure if I understand your question but if you want to run the function just save it in a .ps1 file and call the function:

    function Get-Uptime {
     $os = Get-WmiObject win32_operatingsystem
     $uptime = (Get-Date) – ($os.ConvertToDateTime($os.lastbootuptime))
     $Display = "Uptime: " + $Uptime.Days + " days, " + $Uptime.Hours + " hours, " + $Uptime.Minutes + " minutes"
     Write-Output $Display
     }
    Get-Uptime
    

    Then open a powershell window and run the script: .\uptime.ps1

  • #69672

    yes I was able to run it that way as you have mentioned.In one of the online tutorials I had seen the cutting and pasting of the code in the powershell console itself which means a >> symbol after every line of code.We need to press ctrl+c to get out of this mode?!Can we call the function without saving it to a file?

  • #69676

    Brian Douglas
    Participant

    you can copy paste the complete function into a powershell window and press enter to run it. This will only load the function into the current session. You can run the function by typing get-uptime in the console window.

    • #69895

      PS C:\> function Get-Uptime { $os = Get-WmiObject win32_operatingsystem $uptime =
      (Get-Date) – ($os.ConvertToDateTime($os.lastbootuptime)) $Display = "Uptime: " + $Upt
      ime.Days + " days, " + $Uptime.Hours + " hours, " + $Uptime.Minutes + " minutes" Writ
      e-Output $Display }Get-Uptime
      You cannot call a method on a null-valued expression.
      At line:1 char:26
      + ... Uptime { $os = Get-WmiObject win32_operatingsystem $uptime = (Get- ...
      + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo : InvalidOperation: (:) [], RuntimeException
      + FullyQualifiedErrorId : InvokeMethodOnNull

      I am getting the above error when I run the script in powershell. I am able to run it successfully on powershell ise. what is the above error pointing to?

You must be logged in to reply to this topic.