Pass an argument from a .bat file to PowerShell script


  1. Posts : 110
    Windows 10 Pro 64
       #1

    Pass an argument from a .bat file to PowerShell script


    I have subscribed to a push notification service in order to be able to send push notifications to my phone.
    Here is the PowerShell script:
    Code:
    $uri = "https://api.pushover.net/1/messages.json"
    $parameters = @{
      token = "token"
      user = "user"
      message = "Push Message"
    }
    $parameters | Invoke-RestMethod -Uri $uri -Method Post
    I have not included the actual token or user values, but when I do, and I call this from a .bat file, it works.
    Here is the .bat file:
    Code:
    Powershell.exe -executionpolicy remotesigned -File  C:\Users\Stan\Desktop\PushOverPS.ps1
    
    
    What I want to be able to do is insert a text message into the .bat file and pass it to the powershell script. The text could be a literal string or a file reference.
    How would I do either?
    Thanks.
    Windows 10 Pro 18363.1139
      My Computer


  2. Posts : 5,333
    Windows 11 Pro 64-bit
       #2

    Arguments can be passed to scripts when they are started. Each value passed along to a script can be examined using formal parameters. The script name itself is represented by the parameter %0. The parameter %1 represents the first argument passed in to the script, %2 the second, and so on until %9 for the ninth argument. For example, if you create a script called Check-sys and then use the following command to call the script:


    Code:
    check-sys mailer1 full actual

    You would find that the related parameter values are:

    %0 — check-sys

    %1 — mailer1

    %2 — full

    %3 — actual
      My Computer


  3. Posts : 110
    Windows 10 Pro 64
    Thread Starter
       #3

    Answer


    Thank you for the suggestion, but it did not quite get me there. What I did was change the .bat file to-
    Powershell.exe -executionpolicy remotesigned -File C:\Users\Stan\Desktop\PushOverPS.ps1 "Hello There"

    I changed the PS script to-
    Code:
    $uri = "https://api.pushover.net/1/messages.json"
    $parameters = @{
      token = ""
      user = ""
      message = $args[0]
    }
    $parameters | Invoke-RestMethod -Uri $uri -Method Post
    Which works. I will actually be constructing the .bat file from another application, so I will just insert the text message at that time.
      My Computer


 

  Related Discussions
Our Sites
Site Links
About Us
Windows 10 Forums is an independent web site and has not been authorized, sponsored, or otherwise approved by Microsoft Corporation. "Windows 10" and related materials are trademarks of Microsoft Corp.

© Designer Media Ltd
All times are GMT -5. The time now is 09:43.
Find Us




Windows 10 Forums