700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > linux运行powershell linux – 是否可以编写一个在bash / shell和PowerShell中运行的脚本?...

linux运行powershell linux – 是否可以编写一个在bash / shell和PowerShell中运行的脚本?...

时间:2022-01-14 12:02:28

相关推荐

linux运行powershell linux  – 是否可以编写一个在bash / shell和PowerShell中运行的脚本?...

我需要创建一个集成脚本来设置一些环境变量,使用wget下载文件并运行它.

挑战在于它需要是可以在Windows PowerShell和bash / shell上运行的SAME脚本.

这是shell脚本:

#!/bin/bash

# download a script

wget /my.script -O my.script

# set a couple of environment variables

export script_source=

export some_value=floob

# now execute the downloaded script

bash ./my.script

这与PowerShell中的情况相同:

wget /my.script -O my.script.ps1

$env:script_source=""

$env:some_value="floob"

PowerShell -File ./my.script.ps1

所以我想知道这两个脚本是否可以合并并在任一平台上成功运行?

我一直在试图找到一种方法将它们放在同一个脚本中,并让bash和PowerShell.exe忽略错误,但没有成功.

任何猜测?

解决方法:

有可能的;我不知道这是多么兼容,但PowerShell将字符串视为文本并最终显示在屏幕上,Bash将它们视为命令并尝试运行它们,并且两者都支持相同的函数定义语法.因此,将函数名称放在引号中,只有Bash会运行它,将“exit”放在引号中,只有Bash才会退出.然后编写PowerShell代码.

NB.这是有效的,因为两个shell中的语法重叠,并且您的脚本很简单 – 运行命令并处理变量.如果您尝试使用更高级的脚本(if / then,for,switch,case等)用于任何一种语言,另一种可能会抱怨.

将其保存为dual.ps1,以便PowerShell对它感到满意,chmod x dual.ps1因此Bash将运行它

#!/bin/bash

function DoBashThings {

wget /my.script -O my.script

# set a couple of environment variables

export script_source=

export some_value=floob

# now execute the downloaded script

bash ./my.script

}

"DoBashThings" # This runs the bash script, in PS it's just a string

"exit" # This quits the bash version, in PS it's just a string

# PowerShell code here

# --------------------

Invoke-WebRequest "/my.script.ps1" -OutFile my.script.ps1

$env:script_source=""

$env:some_value="floob"

PowerShell -File ./my.script.ps1

然后

./dual.ps1

在任何一个系统上

编辑:您可以通过使用不同的前缀注释代码块来包含更复杂的代码,然后让每种语言过滤掉自己的代码并对其进行评估(通常的安全警告适用于eval),例如:采用这种方法(纳入Harry Johnston的建议):

#!/bin/bash

#posh $num = 200

#posh if (150 -lt $num) {

#posh write-host "PowerShell here"

#posh }

#bash thing="xyz"

#bash if [ "$thing" = "xyz" ]

#bash then

#bash echo "Bash here"

#bash fi

function RunBashStuff {

eval "$(grep '^#bash' $0 | sed -e 's/^#bash //')"

}

"RunBashStuff"

"exit"

((Get-Content $MyInvocation.MyCommand.Source) -match '^#posh' -replace '^#posh ') -join "`n" | Invoke-Expression

标签:bash,linux,shell,powershell,windows

来源: https://codeday.me/bug/0727/1554025.html

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。