iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 6
0
自我挑戰組

PowerShell 30天練功做網管平台系列 第 6

06_在PowerShell中調整資料儲存格式及輸出方式

第5天因為各種資訊格式的不一樣,挨踢狗雖然沒有具體產出的進度,但在讀了不少線上文件後,也額外發現幾件事:

  •   是可以用變數來儲存PowerShell的cmdlet給出來的結果
  •   可以直接用 變數.{property} 把特定值叫出來
  •   有些變數輸出的是好幾組數值, 那可以用變數[0..] 像一般叫array那樣叫出內容.
  •   可以用拼的方式, 把多組內容拼成一行

今日成果: 將電腦硬體基本資訊及網路資詢組成一行後, 放到一個CSV檔中
https://ithelp.ithome.com.tw/upload/images/20181021/20111755h8HHxGYwfd.jpg

怎麼在PowerShell中用變數

教科書1中其實也有說明,但是好像天書。最後我看了原廠的另一個資源後,就會了個大概。今天的成果用到以下幾個知識點:

  1. 以 $ 給變數命名,後面接指令,$變數名 就會儲存指令所輸出的結果。
    例如前一天有提到,用Get-CIMINSTANCE -Class Win32_NetworkAdapterConfiguration可以取得網路相關的細部資訊,實際的指令是:

    Get-CIMINSTANCE -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=$true | Select-Object -Property [a-z]* -ExcludeProperty IPX*,WINS* | Format-Table -Property IPAddress
    

    則可以用以下方式來指定,用變數$NetDetail來存輸出的一大堆資料:

    $NetDetail=Get-CIMINSTANCE -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=$true | Select-Object -Property [a-z]* -ExcludeProperty IPX*,WINS*
    
  2. 用 $變數.{property} 就可以把特定值叫出來,例如前面的例子裡,如果我們對其中一個叫IPAddress的資料感興趣,就可以用 $NetDetail.IPAddress 來叫出資料。
    https://ithelp.ithome.com.tw/upload/images/20181021/20111755dFbcgzc8Ns.jpg

  3. 如果變數本身和他字屬性都是陣列型的資料,那可以用 [0..] 的方式來叫結果:
    例如這裡用到的$NetDetail.IPAddress兩個值都是矩陣;所以試用以下方式來呼叫,並觀察輸出結果的差異。

    $NetDetail.IPADDRESS
    $NetDetail[0].IPADDRESS
    $NetDetail[0].IPADDRESS[0]
    

    https://ithelp.ithome.com.tw/upload/images/20181021/201117558BbmvBXP4M.jpg

在PowerShell中拼出字串輸出成EXCEL

  1. 先檢查改寫果的語法是不是都是我要的資料。

    得到的結果不錯:
    https://ithelp.ithome.com.tw/upload/images/20181021/20111755vaWdHGMSN7.jpg

    $myDateTime="{0:yyyy-MM-dd HH.mm.ss.fff}" -f (get-date)
    $HWDetail=Get-CimInstance -ClassName Win32_ComputerSystem | Select-Object -Property [a-z]* -ExcludeProperty "CIM*"
    $HWinfo="$($HWDetail.name);$($HWDetail.dOMAIN);$($HWDetail.username;)"
    $NetDetail=Get-CIMINSTANCE -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=$true | Select-Object -Property [a-z]* -ExcludeProperty IPX*,WINS*
          $NetInfo="$($NetDetail[0].IPAddress[0]);$($NetDetail[0].IPSubnet[0]);$($NetDetail[0].DefaultIPGateway);$($NetDetail[0].MACAddress);$($NetDetail[0].DNSServerSearchOrder);$($NetDetail[0].DNSHostName)"
    $myDateTime
    $HWinfo
    $NetInfo
    
  2. 輸出excel file

    "LogTims;PCName;Domian;UseName;IPAddress;SubnetMask;DefaultGW;MAC;DNSServer;DNS" | out-file .\Documents\myPS\asset.csv
    "$myDateTime;$HWinfo;$NetInfo" | out-file .\Documents\myPS\asset.csv -Append
    

上一篇
05_卡關
下一篇
07_讀別部電腦的資料
系列文
PowerShell 30天練功做網管平台14
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言