close

因為要查一個排程,想請 IT 幫我們把線上 server 的排程清單都匯出來,看到微軟的教學有這篇:"Weekend Scripter: Use PowerShell to Document Scheduled Tasks",可以用 Windows PowerShell 把工作排程器上的資訊一口氣匯出做成 Excel。

但如果排程名稱有包含中文,匯出的 Excel 會出現亂碼,因此需要將導出的 CSV 編碼調整為 UTF-8,參考《Powershell Script to export Active Directory users to CSV 中文亂碼處理方式及數字補零》,做了以下設定:

  Export-Csv -Path "CSV檔路徑" -NoTypeInformation -encoding utf8

CSV 編碼後就好了,什麼 chcp 950 通通都不用設。也可以正常在 Excel 打開來。

所以總結起來就是這樣:

  1. 打開編輯器,在裡面貼進下列 PowerShell script:
    # 因為我只想要查自訂的排程,所以沒讓它往下查 Windows 自建的排程
    $taskPath = "\"
    # 指定匯出的 CSV 檔案位置與檔名
    $outcsv = "D:\taskdef.csv"
    # 利用 "Get-ScheduledTask" 查詢所有排程
    Get-ScheduledTask -TaskPath $taskPath |
        ForEach-Object { [pscustomobject]@{
        # 利用 ForEach-Object 把每一個排程的屬性取出
        Name = $_.TaskName
        Path = $_.TaskPath
        LastResult = $(($_ | Get-ScheduledTaskInfo).LastTaskResult)
        NextRun = $(($_ | Get-ScheduledTaskInfo).NextRunTime)
        Status = $_.State
        Command = $_.Actions.execute
        Arguments = $_.Actions.Arguments }} |
            Export-Csv -Path $outcsv -NoTypeInformation -encoding UTF8
     
  2. 檔名存成副檔名為 ps1(第三個字為數字一)的格式,例如我存成 "taskexport.ps1"
     
  3. 打開 PowerShell 視窗,輸入以下指令:
    powershell "D:\taskexport.ps1"
    上述雙引號裡的是 PowerShell script 的檔案路徑,必須是絕對路徑
    若未填寫絕對路徑,會出現以下錯誤訊息:
    taskexport.ps1 : 無法辨識 'taskexport.ps1' 詞彙是否為 Cmdlet、函數、指令檔或可執行程式的名稱。請檢查名稱拼字是否正確。
    如果包含路徑的話,請確認路徑是否正確,然後再試一次。
    位於 線路:1 字元:1
    + taskexport.ps1
    + ~~~~~~~~~~~~~~
        + CategoryInfo          : ObjectNotFound: (taskexport.ps1:String) [], CommandNotFoundException
        + FullyQualifiedErrorId : CommandNotFoundException

     
  4. 執行完畢後,就可以在步驟一的 PowerShell script 裡指定的路徑得到 csv 檔。

PowerShell 還滿好玩的,改天想來做個 AD 狀態查詢小工具。

arrow
arrow

    小攻城師 發表在 痞客邦 留言(0) 人氣()