在Red Hat Linux服务器上执行一个.ps1 PowerShell脚本

7
我可以帮你进行翻译。以下是翻译的结果,保留了HTML标签。

我有一个.ps1 PowerShell脚本在Windows上执行,但我的所有数据都在Linux服务器上,是否有可能以某种方式在Red Hat服务器上执行PowerShell脚本?

PowerShell脚本如下:

Clear-Host
$path="D:\Deep Backup 26-04-2013\New folder"
$systemname=Read-Host 'Enter System Name'



$files=Get-ChildItem $path -Recurse -Force -Include *_Registrar.zip*,*.reg.zip*


$counter=1

foreach($file in $files)
{
    $name=$file.name
    [void][system.reflection.Assembly]::LoadFrom("C:\Program Files\MySQL\MySQL Connector Net 6.5.4\Assemblies\v2.0\MySql.Data.dll")
    $dbconnect=New-Object MySql.Data.MySqlClient.MySqlConnection
    $dbconnect.ConnectionString="server=localhost;userid=root;password=nPr123*;database=test3;"
    $dbconnect.Open()

    $sql="insert into eid values('"+$name + "','"+$systemname+"')"


    $command=new-object MySql.Data.MySqlClient.MySqlCommand($sql,$dbconnect)
    $command.ExecuteNonQuery()


}
 $sql="insert into eid_unique
       select distinct Packet_name, System_name from eid a
       where not exists (select 1 from eid_unique b
       where a.Packet_name=b.Packet_name);"


    $command=new-object MySql.Data.MySqlClient.MySqlCommand($sql,$dbconnect)
    $command.ExecuteNonQuery()
$dbconnect.close()

2
你最好用bash/ruby/python/perl来实现这个。 - Andy Arismendi
即使在答案中提到了“Pash”,也没有办法加载.NET dll(在您的示例中是MySql.Data.dll)...正如Andy Arismendi所提到的,您需要将脚本重新实现为其他脚本语言。 - Tomas Panik
我也赞成坚持使用平台的“本地”语言的建议。 - Ansgar Wiechers
@Tomas - 这里有一个Mono MySQL绑定(否则我就不会提到这个选项了)http://www.mono-project.com/MySQL - holtavolt
6个回答

10

微软在原来问题提出四年后,发布了适用于Linux的PowerShell,并且它是开源的:https://github.com/PowerShell/PowerShell

在Linux环境下,您可以使用以下语法:(script.ps1,可执行文件)

#!/usr/bin/powershell -Command

write-host -fore Green "executing PowerShell!";

5

Pash是一个跨平台的Mono克隆版PowerShell,目前处于积极开发中。 只需下载并使用xbuild进行构建,然后运行即可。 与Windows上的PowerShell类似,您可以执行脚本:

& '/path/to/script.ps1'

该代码库已于2019年2月4日被所有者归档。现在它只能以只读方式访问。 - ggorlen

2
安装 PowerShell 后,很容易:

点击此处

thufir@dur:~/powershell$ 
thufir@dur:~/powershell$ ./hello_world.ps1
hello world
done
thufir@dur:~/powershell$ 
thufir@dur:~/powershell$ cat hello_world.ps1 
#!/usr/bin/pwsh -Command


echo "hello world"
"done"


thufir@dur:~/powershell$ 

不确定为什么是 pwsh 而不是 powershell,但这就是 Linux。

1

你也可以轻松在Linux上安装

,保留HTML,不做解释。
snap install powershell --classic

这个版本的“powershell”应用程序使用经典约束发布,因此可能会在安全沙盒之外执行任意系统更改,这可能会使您的系统面临风险。

0

听起来Pash可能适合你。


1
有趣,但看起来它似乎没有得到积极的维护。 - Ansgar Wiechers

0

我想分享一个帮助我的简单方法。请按照官方的 Microsoft 文档进行操作。这个问题有两个步骤。

  • 安装 PowerShell(在您的操作系统上)
  • 运行 PowerShell 脚本

安装 PowerShell:

以下 URL 将帮助您在计算机上安装 PowerShell。

要确认您的安装,请打开终端并运行 pwsh(这是针对 Mac 的)。您将看到以下内容:

enter image description here

运行PowerShell脚本:

接下来,在PowerShell终端中运行以下命令。将my-script.ps1替换为您的脚本名称:

./my-script.ps

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