英文:
Set powershell variable in ps1 script by a paramater
问题
如何在执行脚本之前将Powershell变量设置为ps1脚本
示例:
应用程序执行路径:
powershell.exe -ExecutionPolicy Bypass -File "C:/script.ps1";
参数:
$WhichSite= "StackOverflow";
ps1包含:
curl -UseBasicParsing "http://www.$WhichSite.com";
我尝试了上面的示例将$WhichSite = "stackoverflow"
但没有成功
执行powershell.exe -ExecutionPolicy Bypass -File "C:/script.ps1"的预期结果:
curl -UseBasicParsing "http://www.stackoverflow.com";
英文:
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
得分: 1
如果我理解你的问题正确,最好的方法是将参数传递给脚本,然后从内部调用curl函数。你可以考虑在script.ps1中使用类似以下的内容:
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[System.String]
$WhichSite
)
Invoke-WebRequest -UseBasicParsing "Http://$WhichSite.com"
然后,要在PowerShell窗口中运行脚本,可以执行以下命令:
./script.ps1 -WhichSite "stackoverflow"
你可以通过运行以下命令来为当前会话设置PowerShell的执行策略:
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process
这样,你就不必每次在脚本执行前都添加它。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论