[個人筆記] powerShell筆記與常用指令

  • 21516
  • 0
  • 2020-08-28

powerShell相關的筆記

紀錄一些可能未來還會用到的指令

基本上是參考這位的大大

https://marcus116.blogspot.com/2019/01/powershell-iis-application-poolwebsite.html

 

powerShell檔名請命名 ps1

右建點擊使用powerShell運行、或按編輯會進入powerShell專屬GUI視窗

或是去尋找 powerShell.exe 或 powershell_ise.exe (建議用 系統管理員 身分執行)

 

刪除bin obj 資料

try {Get-ChildItem .\ -include bin,obj -Recurse | foreach ($_) { remove-item $_.fullname -Force -Recurse }}catch{}

 

 刪除特定名稱的隱藏資料夾

try {Get-ChildItem -hidden .\ -include .vs,obj -Recurse | foreach ($_) { remove-item $_.fullname -Force -Recurse }}catch{}

 

 

執行某個ps1腳本檔案

powershell -file "C:/my_file.ps1"

 

 安裝特定Module模組

Install-Module -Name SqlServer

 

透過powerShell建立IIS站台

# 更換參數 1. 請把 XXXXXXXXXXXX 更換成你的站台名稱
# 更換參數 2. 請把 XXXXXXXXXXXX_PORT 更換成你的port編號

# import module
Import-Module WebAdministration
cd IIS:\AppPools\
 
建立website 以及 應用程式集區
cd D:\website
New-item -Name XXXXXXXXXXXX -ItemType directory
New-Item IIS:\Sites\XXXXXXXXXXXX -bindings @{protocol="http";bindingInformation=":XXXXXXXXXXXX_PORT:"} -physicalPath D:\website\XXXXXXXXXXXX
New-item IIS:\AppPools\XXXXXXXXXXXX | Set-ItemProperty -Name "managedRuntimeVersion" -Value "v4.0"

 

批次取代檔案名稱

#先移動到當前ps1檔案的路徑
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath

#找出符合關鍵字的檔案名
$DefaultFiles =  Get-ChildItem | Where-Object {$_.Name -like "*@3x*"}
ForEach($File in $DefaultFiles) 
{    
    $newname = ([String]$File).Replace("@3x","")
    Rename-item -Path $File $newname
}

 

觸發httpRequest

powershell Invoke-WebRequest -Uri "http://www.your-api.com" -Method GET

 

windows cmd 執行powershell指令 並取得返回的數值 (時間getDate)

for /f "delims=" %%a in ('powershell get-date((get-date^)^) -uformat "%%Y%%m%%d%%M%%S"') do set output_result=%%a
SET production_tags="_online_%output_result%"

 

WindowsServer機器 若出現錯誤訊息

无法加载文件 C:\Users\DH\Desktop\cs\rename.ps1,因为在此系统上禁止运行脚本

set-executionpolicy remotesigned  (在powerShell下執行)

 


SQL相關

透過ps產生tableSchema或table data (GUI介面的generate script)

 

Step 1.  先安裝powerShell模組 (管理員模式執行)

#首先在你的電腦安裝 powerShell模組
Install-Module -Name SqlServer -AllowClobber

 

Step 2. 執行這段powerShell指令 (請自行修改裡面的變數)

# Import the SqlServer module
Import-Module "SqlServer"  


#SQL連線字串
$Database = Get-SqlDatabase -ConnectionString "Server=192.168.1.1;Initial Catalog=CenterDB;Persist Security Info=False;User ID=sa;Password=123456;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=True;Connection Timeout=30;"


#指定要匯出哪張table (請注意資料量太大的table不適合使用此匯出功能)
$target_table_name = "GameMerchantJobSetting"


#宣告檔案路徑
$date = Get-Date
$dateText = $d.ToString("yyyyMMddHHmmss")
$FilePath = "C:\sql_test\Output_" + $target_table_name + "_" + $dateText + ".sql"


$scriptOptions = New-Object -TypeName Microsoft.SqlServer.Management.Smo.ScriptingOptions
$scriptOptions.NoCollation = $True
$scriptOptions.ScriptSchema = $False
$scriptOptions.ScriptData = $True


#根據上方設定 執行匯出指令
($Database.Tables | Where Name -eq $target_table_name).EnumScript($scriptOptions) | Out-File -FilePath $FilePath

 

 

透過powerShell 執行SQL指令

# Import the SqlServer module
Import-Module "SqlServer"  


#指定要匯出哪個DB、哪個table
$taget_DB_Name = "msdb"
$connString = "Server=192.168.1.1;Initial Catalog=" + $taget_DB_Name + ";Persist Security Info=False;User ID=sa;Password=123456;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=True;Connection Timeout=30;"

Invoke-Sqlcmd -ConnectionString $connString -Query "USE msdb ;  EXEC dbo.sp_start_job N'[版控] 自動部屬腳本';"

 

透過powerShell產生指令

# Import the SqlServer module
Import-Module "SqlServer"  


#指定要匯出哪個DB、哪個table
$taget_DB_Name = "CenterDB"
$target_sp_name = "USP_GetUsers"
$connString = "Server=192.168.1.1;Initial Catalog=" + $taget_DB_Name + ";Persist Security Info=False;User ID=sa;Password=123456;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=True;Connection Timeout=30;"


#SQL連線字串
$Database = Get-SqlDatabase -ConnectionString $connString


#宣告檔案路徑
$FilePath = "C:\Users\user\Documents\DBA_format\" +  $target_sp_name +  ".sql"
$proc = $Database.StoredProcedures | ?{ $_.Name -eq $target_sp_name} 



$prefixText = "USE "+ $taget_DB_Name + " "
$prefixText + $proc.ScriptHeader($true) + $proc.TextBody | Out-File -FilePath $FilePath

 

印出大於xxx mb的資料夾

$FolderArray = Get-ChildItem -Path "C:\xxxxxxxxxxxx"

foreach ($Folder in $FolderArray) 
{
    # retrieve all *.txt files in $Folder
    $TxtFiles = Get-ChildItem -Path $Folder -Recurse -file

    # get the file count
    $FilesInFolder = $TxtFiles.Count

    # calculate folder size
    $FolderSize = ($TxtFiles | Measure -Sum Length).Sum

    # write folder size to host
    $FolderSizeMB = [int]($FolderSize / 1MB)


    if( $FolderSizeMB -gt 100)
    {
        Write-Host "$Folder: $FolderSizeMB MB"
    }
}

 

關於sql的模組 可以google  Microsoft.SqlServer.Management.Smo.ScriptingOptions,查看有哪些參數可以設置