0

How to set Powershell variable into ps1 script before the execution of the script

example:

application execution path: powershell.exe -ExecutionPolicy Bypass -File "C:/script.ps1"

paramater: $WhichSite= "StackOverflow"

ps1 contains: curl -UseBasicParsing "http://www.$WhichSite.com"

I tried the example above to set the $WhichSite = "stackoverflow"

But it did not work

result expected of executing powershell.exe -ExecutionPolicy Bypass -File "C:/script.ps1": curl -UseBasicParsing "http://www.stackoverflow.com"

1 Answer 1

1

If I understand your question correctly, the best thing would be to pass a parameter to the script and then call the curl function from within. You might consider something like this inside of script.ps1:

    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [System.String]
        $WhichSite
    )
    
    Invoke-WebRequest -UseBasicParsing "Http://$WhichSite.com"

Then, to run the script from a PowerShell window, you can do:

./script.ps1 -WhichSite "stackoverflow"

You can set the execution policy for PowerShell for the current session by running:

Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process

So that you don't have to add it in front of your script execution everytime time.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the reply and the execution policy tip, Will it work also for numeric value and should I execute all together or separate the app execution path than the parameter C:\script.ps1 -WhichSite "stackoverflow" or app exec path: C:\script.ps1 parameter: -WhichSite "stackoverflow" cause I tried both did not work maybe cause the the value is number that's why it did not work
Apologies, I mistyped the execution string - if you change directory to be in the C:\ directory, the execution is ./script.ps1 -WhichSite "stackoverflow" It should be executed as I just typed it. Numbers should work as well, they'll just be converted to strings, not integers.
On second thought, you are probably better off using Invoke-WebRequest, I've updated my answer to reflect that. Eliminates potential PATH issues with curl.exe
Thanks for the help I tried it but still did not work, note that the parameter is numeric. the Invoke-WebRequest will not work since Internet explorer is disabled by GPO.
If you pass the parameter in quotes, such as "123", then it will be interpreted as a string. Invoke-WebRequest does not have a dependency on IE, I'm running the above snippet on a machine without IE installed it is appropriately returning the request data. How are you executing this script?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.