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 = "\\ServerA\D$";
 5 
 6 net use $serverDrive $password /user:$username
 7 
 8 Copy-Item $serverDrive\test.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:\CI\Script\test.ps1"

其中“test.ps1”的內容為:

1 $copyDir="D:\"+(Get-Date -format yyyy.MM.dd)+".txt";
2 
3 Copy-Item D:\test.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:\localhost\client\trustedhosts *
b:Set-item wsman:localhost\client\trustedhosts –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:\CI\Config\Credential.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:\CI\Script\tes.sql";
7 
8 Sqlcmd  -S $server -d $databaseName -U $username -P $password -i $sqlScriptDir

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM