日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

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

發布時間:2025/3/15 47 豆豆
生活随笔 收集整理的這篇文章主要介紹了 linux运行powershell,linux – 是否可以编写一个在bash / shell和PowerShell中运行的脚本?... 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

我需要創建一個集成腳本來設置一些環境變量,使用wget下載文件并運行它.

挑戰在于它需要是可以在Windows PowerShell和bash / shell上運行的SAME腳本.

這是shell腳本:

#!/bin/bash

# download a script

wget http://www.example.org/my.script -O my.script

# set a couple of environment variables

export script_source=http://www.example.org

export some_value=floob

# now execute the downloaded script

bash ./my.script

這與PowerShell中的情況相同:

wget http://www.example.org/my.script -O my.script.ps1

$env:script_source="http://www.example.org"

$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 http://www.example.org/my.script -O my.script

# set a couple of environment variables

export script_source=http://www.example.org

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 "http://www.example.org/my.script.ps1" -OutFile my.script.ps1

$env:script_source="http://www.example.org"

$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/20190727/1554025.html

新人創作打卡挑戰賽發博客就能抽獎!定制產品紅包拿不停!

總結

以上是生活随笔為你收集整理的linux运行powershell,linux – 是否可以编写一个在bash / shell和PowerShell中运行的脚本?...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。