Jenkins+PowerShell持续集成环境搭建(四)常用PowerShell命令

0. 修改执行策略

Jenkins执行PowerShell脚本,需要修改其执行策略。以管理员身份运行PowerShell,执行以下脚本:

1 Set-ExecutionPolicy Unrestricted

1. Test-Path

确定文件或文件夹是否存在,如:

1 $testDir="D:NewDir"
2 if((Test-Path $testDir) -ne $true)
3 {
4     md $testDir
5 }

2. Copy-Item/Remove-Item

拷贝/删除文件或文件夹,如:

1 $testDir="D:NewDir"
2 if(Test-Path $testDir)
3 {
4     Remove-Item $testDir -Recurse -Force
5 }

3. Cmd

调用Cmd.exe,如通过Cmd调用7z进行压缩/解压缩:

1 $projectDir="D:NewDir";
2 $compressedName="NewDir.7z";
3 
4 cd $projectDir
5     
6 $cmdargs = "7z a "+$compressedName+" -w .*"
7 cmd /c $cmdargs

4. Net use

访问共享文件夹,如:

 1 $username="Victor";
 2 $password="******";
 3 
 4 $serverDrive = "\ServerAD$";
 5 
 6 net use $serverDrive $password /user:$username
 7 
 8 Copy-Item $serverDrive	est.txt -Destination D:NewDir
 9 
10 net use $serverDrive /delete /y

5. Invoke-Command

在本地或远程主机执行命令,如:

1 $username="Victor";
2 $password="******";
3 
4 $pass = ConvertTo-SecureString -AsPlainText $password -Force
5 $credential= New-Object System.Management.Automation.PSCredential -ArgumentList $username,$pass
6 
7 $serverName="ServerA"
8 Invoke-Command -ComputerName $serverName -Credential $credential -FilePath "D:CIScript	est.ps1"

其中“test.ps1”的内容为:

1 $copyDir="D:"+(Get-Date -format yyyy.MM.dd)+".txt";
2 
3 Copy-Item D:	est.txt -Destination $copyDir

注意:运行此命令需要添加信任主机

Step 1:在主机B上Run as Administrator打开PowerShell
Step 1.1:启用远程:Enable-PSRemoting -Force
Step 1.2:添加信任主机:下面a为允许所有主机,b为添加单个主机或主机列表
a:Set-Item wsman:localhostclient rustedhosts *
b:Set-item wsman:localhostclient rustedhosts –value 主机名
Step 1.3:重启WinRM服务:Restart-Service WinRM
Step 2:在主机A上打开PowerShell
Step 2.1:测试连接:Test-WsMan B
Step 2.2:如果连接成功即可使用”Invoke-Command“命令执行相应脚本

6. System.Net.WebClient.DownloadString

使用该方法可以间接实现通过Jenkins访问url,示例:

1 $url="http://blog.ityes.net"
2 
3 (New-Object System.Net.WebClient).DownloadString($url);

7. System.Xml.XmlDocument.Load

读取XML文件,如:

1 [String]$xmlDocDir = "D:CIConfigCredential.xml";
2 $xmlDoc = New-Object "System.Xml.XmlDocument";
3 $xmlDoc.Load($xmlDocDir);
4 
5 $username=$xmlDoc.Root.Credential.GetAttribute("Username");
6 $password=$xmlDoc.Root.Credential.GetAttribute("Password");

其中“Credential.xml”的内容为:

1 <?xml version="1.0" encoding="utf-8"?>
2 <Root>
3     <Credential Username="Victor" Password="******"></Credential>    
4 </Root>

8. Sqlcmd

使用 ODBC 执行 Transact-SQL 批处理,如:

1 $server="DbServer";
2 $databaseName="DbName";
3 $username="Victor";
4 $password="******";
5 
6 $sqlScriptDir="D:CIScript	es.sql";
7 
8 Sqlcmd  -S $server -d $databaseName -U $username -P $password -i $sqlScriptDir
原文地址:https://www.cnblogs.com/victorbu/p/6047611.html