# 如何透過PowerShell連線微軟內部資料庫(WID) ###### tags: `PowerShell` `資料庫` 2022/01/04 本篇文章解決以下問題 - PS如何取得檔案內容 - PS如何連線到微軟內部資料庫(WID) - PS如何執行SQL語法 - PS如何匯出csv,並拿掉開頭註解 - 批次檔(bat)如何呼叫PS檔案(ps1) 網路有提到但個人沒嘗試成功 - 使用SQL Server Studio來開啟微軟內部資料庫(WID) 直接上程式 前四個問題的解答都在這 ```bash= # WID2012+ $ConnectionString = 'server=\\.\pipe\MICROSOFT##WID\tsql\query;database=SUSDB;trusted_connection=true;' # WID2008 # $ConnectionString = 'server=\\.\pipe\MSSQL$MICROSOFT##SSEE\sql\query;database=SUSDB;trusted_connection=true;' $SQLConnection= New-Object System.Data.SQLClient.SQLConnection($ConnectionString) $SQLConnection.Open() $SQLCommand = $SQLConnection.CreateCommand() # 直接使用SQL語法 # $SQLCommand.CommandText = 'SELECT database_id, name, user_access_desc, state_desc from Sys.Databases' # 使用外部SQL檔案 $SQLCommand.CommandText = (Get-Content -path C:\scripts\WSUSGetComputer\GetComputerStatus.sql) $SqlDataReader = $SQLCommand.ExecuteReader() $SQLDataResult = New-Object System.Data.DataTable $SQLDataResult.Load($SqlDataReader) $SQLConnection.Close() # 將結果儲存到csv中 $SQLDataResult | export-csv C:\scripts\WSUSGetComputer\tofile.csv -notypeinformation ``` 如果要使用SQL Server Studio來開啟的話, 前面需要多加`np:` ``` np:\\.\pipe\MICROSOFT##WID\tsql\query ``` 但我一直沒成功... 另外若要透過批次檔(\*.bat)呼叫PowerShell檔案(\*.ps1)的話, ``` powershell.exe set-executionpolicy remotesigned -File C:\Users\SE\Desktop\ps.ps1 ```