在bash脚本中运行PowerShell脚本

8
在PowerShell中,如何在Bash脚本中运行PowerShell脚本(.ps1)?我可以单独运行PowerShell脚本,使用命令 "& .\scriptfile.ps1",也可以单独运行Bash脚本。但是当我尝试在Bash脚本中运行PowerShell时,我会得到"file.ps1: 命令未找到"的错误提示。两个脚本都在同一路径下。

你运行了 .\scriptfile.ps1,但错误提示说找不到 file.ps1? - Doug Maurer
不,它运行得很好,没有错误。文件未找到的错误是当我在.sh脚本中运行它时出现的。 - hithesh
4个回答

10

你是否试图

.\scriptfile.ps1

那应该是:

./scriptfile.ps1

当从bash脚本调用PowerShell时,您需要像以下方式运行pwsh命令:

pwsh ./scriptfile.ps1

或者你的 Powershell 脚本文件的第一行应该像这样添加一个Shebang(解释器指令):

#!/usr/bin/env pwsh

请查看如何在PowerShell脚本中使用shebang符号?


我尝试运行 pwsh ./scriptfile.ps1,但是出现了“pwsh:找不到命令”的错误。 - hithesh
添加 #!/usr/bin/env pwsh,会给我返回: #!/usr/bin/env: 错误的解释器:没有那个文件或目录。 - hithesh
同时,pwsh ./scriptfile.ps1也失败了。pwsh不被识别为cmdlet的名称......等等。只有.\scriptfile.ps1本身运行时没有错误。但是,当它从.sh脚本内部运行时会失败。 - hithesh

8
我在Windows 10 Pro上使用git bash,这里是powershell。 可执行文件位于/c/WINDOWS/System32/WindowsPowerShell/v1.0/powershell.exe,并包含在我的$PATH中。 因此,我可以这样说:
powershell ./scriptfile.ps1
# or inline:
powershell 'my script'

在Windows上运行的Ubuntu bash中,我必须说
powershell.exe ./scriptfile.ps1

对我来说,只有 powershell ./scriptfile.ps1 能够正常工作。 powershell scriptfile.ps1 会出现错误,而 powershell 'scriptfile.ps1' 也会出现错误。 - Infineight

1
尝试更改权限并使用 chmod +x file.ps1 使其可执行。

我之前尝试过,但是出现了“chmod”不被识别为命令、函数、脚本文件等的错误提示。 - hithesh
你是以超级用户或根用户身份运行吗? - Risna Fadillah
我正在以管理员身份运行PowerShell。 - hithesh
当我运行$ which pwsh时,我再次收到相同的消息($未被识别为cmdlet的名称.....)。我还尝试了which pwsh。(which未被识别为cmdlet的名称等) - hithesh
@hithesh 看起来你是在 Powershell shell 内运行这些命令;尝试从默认的 shell (Bash、ZSH 等) 运行它们。 - Scott Simontis
@Scott Simontis 这是在 Windows PC 上。所以我只有 PowerShell,没有 bash 等等。 - hithesh

0
# Update the list of packages
sudo apt-get update
# Install pre-requisite packages.
sudo apt-get install -y wget apt-transport-https software-properties-common
# Download the Microsoft repository GPG keys
wget -q https://packages.microsoft.com/config/ubuntu/18.04/packages-microsoft-prod.deb
# Register the Microsoft repository GPG keys
sudo dpkg -i packages-microsoft-prod.deb
# Update the list of products
sudo apt-get update
# Enable the "universe" repositories
sudo add-apt-repository universe
# Install PowerShell
sudo apt-get install -y powershell
# Start PowerShell
pwsh


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接