.NET Logo
Welcome Guest Search | Active Topics | Members | Log In | Register

powershell ครั้งที่ 11 Options · View
paedotnet
Posted: Thursday, December 27, 2007 4:15:48 PM

Rank: มือเทพ
Groups: Member

Joined: 12/6/2007
Posts: 345
Location: bkk

การใช้ new-object
New-Object คำสั่งนี้เราสามารถใช้สร้าง object ได้ เช่นถ้าเราต้องการใส่ข้อมูลใน cell ของ Excel เราก็เขียนได้ดังนี้

$i = New-Object  -comObject Excel.Application
$i.Visible =$true
$j = $i.Workbooks.Add()
$k =$j.WorkSheelts.Item(1)
$k.Cells.Item(1,1) =" hello"

 

การใช้ New-Object เพื่อสร้างคลาส DateTime


$d = New-Object  -TypeName System.DateTime
$d

ผลลัพธ์จะแสดง วันเดือนปีและเวลา

ถ้าต้องการดู method หรือ property ของ System.DateTime ก็ใช้คำสั่ง Get-Member


$d  |  Get-Member

การหารายละเอียดเกี่ยวกับEnvironment Variable ก็ใช้
 

Get-ChildItem  env:


ผลลัพธ์จะแสดงรายละเอียดของ Environment variable


$env:os


จะแสดง os

การสร้างคลาสของ String


$str  = New-Object -TypeName System.String -ArgumentList "Hello"
$str


ผลลัพธ์จะมีคำว่า Hello ออกมา

การหาขนาดstring ใช้ Length


$str.Length

การแสดงตัวอักษรตัวใหญ่ใช้ ToUpper()


$str.ToUpper()

แสดงเมธอดและ property


$str | Get-Member

การแสดง member  ทั้งหมดของคลาส


[System.String].GetMembers()

การใช้งาน GetMethods()

 

[System.DateTime].GetMethods()


การติดต่อ กับ ฐานข้อมูล โดยใช้ DataAdapter

 

$con = New-Object System.Data.SqlClient.SqlConnection
$con.ConnectionString = "Server =.\SqlExpress;Database=Northwind;Integrated Security =SSPI"
$com =New-Object  System.Data.SqlClient.SqlCommand
$com.CommandText ="SELECT * FROM Customers"
$com.Connection =$con
$da  = New-Object  System.Data.SqlClient.SqlDataAdapter
$da.SelectCommand =$com
$ds =New-Object System.Data.DataSet
$da.Fill($ds,"customers")
$ds.Tables["customers"]

ผลลัพธ์จะได้ดังรูป


การติดต่อกับฐานข้อมูลโดยใช้ SqlDataReader

$con = New-Object System.Data.SqlClient.SqlConnection("Server=.\SqlExpress;Database=Northwind;Integrated Security=SSPI")
$com =New-Object System.Data.SqlClient.SqlCommand
$com.Connection =$con
$com.CommandType =[System.Data.CommandType]'Text'
$com.CommandText = "SELECT * FROM Customers"
$con.Open()
$reader = $com.ExecuteReader()
$reader | Foreach-Object {
Write-Host $_.Item(0)
}
 


[With great power comes great responsibility]
Users browsing this topic
Guest


Forum Jump
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.

Main Forum RSS : RSS

YAFVision Theme Created by Jaben Cargman (Tiny Gecko)
Powered by Yet Another Forum.net version 1.9.1.8 (NET v2.0) - 3/29/2008
Copyright © 2003-2008 Yet Another Forum.net. All rights reserved.


Sponsored by