2010年9月21日 星期二

Powershell - some tip

  1. Let your computer can run powershell script : Set-ExecutionPolicy RemoteSigned
  2. 將使用者需要互動輸入的選項,自動帶入指令中 :
    因在build software時,會進入cygwin的環境中,並需輸入選項去build, 為將整個動作自動化
    1. 單一次選項時 :  sunny || .\login.bat ==> 執行login.bat時,會等待user輸入其名字再做login, 此時利用pipeline, powershell 會自動將 'sunny' input 
    2. 需多次輸入時 : 
      ps >@' [enter]
      >> input1 [enter]
      >> input2 [enter]
      >> '@  | command
    3. refer to : http://powershell.com/cs/blogs/tips/archive/2009/07/15/feeding-input-into-native-commands.aspx
  3. Execute powershell script (.ps1 file) as a command (可應用於task scheduler中) :
    powershell.exe -command "&{d:\ps\sample.ps1 arg1 arg2}"
  4. Print all System variable
    Get-ChildItem -Path Variable: `
           | Add-Member `
                  -Name Type `
                  -MemberType ScriptProperty `
                  -Value { $this.GetType().FullName } `
                  -PassThru `
           | Add-Member `
                  -Name DisplayValue `
                  -MemberType ScriptProperty `
                  -Value { (Get-Variable -Name $this.Name -Scope 1 -ValueOnly | Format-List -Property * | Out-String).Trim("`r`n") } `
                  -PassThru `
           | Sort-Object -Property Name `
           | Format-List -Property Name,Type,Description,Value,DisplayValue,Options `
           | Out-Host -Paging

2010年9月14日 星期二

Powershell - 執行外部命令

Summarize form source :
  1. Use [Diagnostic.Process]::Start a single line
    [Diagnostics.Process]::Start('C:\Vmware\vcbMounter.exe',"-h $host -u $user -p $password -s name:$machine -r $location -t $backuptype")
  2. Parameterize
    $application = 'C:\Vmware\vcbMounter.exe'

    $arguments = "-h {0} -u {1} -p {2} -s name:{3} -r {4} -t {5}" -f ($host, $user, $password, $machine, $location, $backuptype)
    [Diagnostics.Process]::Start('$application','$arguments')
  3. Use & replace [Diagnostic.Process]::Start
    $exe = "C:\Vmware\vcbMounter.exe"

    $host = "server"
    $user = "joe"
    $password = "cleartextpasswordsareanono:-)"
    $machine = "somepc"
    $location = "somelocation"
    $backupType = "incremental"
    & $exe -h $host -u $user -p $password -s "name:$machine" -r $location -t $backupType
  4. Get execution result
    $process = [Diagnostics.Process]::Start('$application','$arguments')

    the process object has a member HasExited that returns $true when the
    process has exited (pretty self explanatory there..)
    
    There is also a ExitCode property that has the exit code of the process.
    
    You could use a do while loop to check for the exit of the process.
    do {...} while (!$process.HasExited)
  5. Use $?, $LASTEXITCODE to get execution result
    $?

           Contains True if last operation succeeded and False otherwise.
    $LASTEXITCODE
           Contains the exit code of the last Win32 executable execution.
    EXAMPLE :
    PS> ping localhost
    Pinging jpsvista1.ntdev.corp.microsoft.com [::1] from ::1 with 32 bytes of data:
    Reply from ::1: time<1ms
    Reply from ::1: time<1ms
    Reply from ::1: time<1ms
    Reply from ::1: time<1ms
    Ping statistics for ::1:
        Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
    Approximate round trip times in milli-seconds:
        Minimum = 0ms, Maximum = 0ms, Average = 0ms
    PS> $lastexitcode

    0
    PS> ping asdfasdf
    Ping request could not find host asdfasdf. Please check the name and try again.
    PS> $lastexitcode
    1
An Example of mine : 1. 可提供將stdout寫到logfile  2.用write-progress 做執行經歷時間的輸出
    function startProcess ([string] $processname, [string] $arguments, [string]$logfile)
    {
    [String]$output=""
    $processStartInfo = New-Object System.Diagnostics.ProcessStartInfo;
    $processStartInfo.FileName = $processname;
    $processStartInfo.WorkingDirectory = (Get-Location).Path;
    if($arguments) { $processStartInfo.Arguments = $arguments }
    $processStartInfo.UseShellExecute = $false;
    if($logfile) {$processStartInfo.RedirectStandardOutput = $true}

    $process = New-Object System.Diagnostics.Process;
    $process.StartInfo=$processStartInfo
    $process.Start() 
    #$process = [System.Diagnostics.Process]::Start($processStartInfo);
    $startTime=get-Date
    $endTime=get-date
    do {
    Start-Sleep -Seconds 1
    $endTime=get-date
    $timeSpan=$endTime - $startTime
    Write-Progress -Activity "Building ... and timespan:" -Status $timeSpan  
    } while (!$process.HasExited)
    if($logfile) {$output=$process.StandardOutput.ReadToEnd() }
    $process.WaitForExit()
    $process.Close()
    if($logfile) {
    $output | Out-File $logfile ;
    "Start  at:$startTime" | Out-File $logfile -Append ;
    "End    at:$endTime" | Out-File $logfile -Append ;
    "Timespan :$timeSpan" | Out-File $logfile -Append ;
    }
    else {
    Write-Host "Start at:$startTime"
    Write-Host "End at:$endTime"
    Write-Host "Timespan : $timeSpan"
    }
    }

    2010年9月3日 星期五

    PowerShell - 如何執行遠端端機器的命令

    1. 在被執行端機器啟動 winrm, 並自動設定 : 執行winrm quickconfig
    過程如下:
    PS D:\>winrm quickconfig
    WinRM 未設定為在此電腦上接收要求。
    必須進行下列變更:
    設定 WinRM 服務類型為自動啟動。
    啟動 WinRM 服務。
    進行這些變更 [y/n]? y
    WinRM 已經更新以接收要求。
    WinRM 服務類型順利變更。
    WinRM 服務已啟動。
    此電腦上的 WinRM 尚未設定為允許存取以進行遠端管理。
    必須進行下列變更:
    在 HTTP://* 上建立 WinRM 接聽程式,以接受對於此電腦之任何 IP 的 WS-Man 要求。
    啟用 WinRM 防火牆例外。
    進行這些變更 [y/n]? y
    WinRM 已經更新,可用於遠端管理。
    已在 HTTP://* 上建立 WinRM 接聽程式,以接受對於此電腦之任何 IP 的 WS-Man 要求。
    WinRM 防火牆例外已啟用。
    1. 執行單一遠端指令: Remote-Invoke
      1. Invoke-Command -ComputerName server01 -ScriptBlock { get-host }
        在遠端電腦(server01) 執行指令 get-host
      2. invoke-command -filepath c:\scripts\test.ps1 -computerName server01在遠端電腦(server01) 執行powershell script file c:\scripts\test.ps1
      3. 其它可用 help Invoke-Command -example 得到更多說明
    2. 啟一個remote interaction session, 然後在console中可直接革連續執行指令,像linux的ssh
      1. 開啟一個在server01的remote session, 命名為 testRemote
        command : New-PSSession -Name remoteTest -ComputerName server01
      2. 進入 remoteTest的remote session
        command : Enter-PSSession -Name remoteTest 此時 command prompt會在最前加上遠端電腦的名稱,  [server01] PS D:>
      3. 以後此console就是遠端電腦的console
      4. 離開
        command : Exit-PSSession
    3. Trouble Shooting
      1. 一般要能啟動遠端命令必需是administrator或屬於administrator group, 如是一般user則需設定付予權限, 如下 :
        Set-PSSessionConfiguration Microsoft.Powershell -ShowSecurityDescriptorUI
        執行以上命令後, 在command line回答"Y", 隨後會出現一UI供設定權限,此時加入user, 並勾選 [Allow Execute(Invoke)], 最後再回答"Y", 重新啟動 WinRM service
      2. reference : http://www.ravichaganti.com/blog/?p=1181

    2010年9月2日 星期四

    iPhone功能強化 - 加入導航功能 (一)

    Install roqyBT (a bluetooth stack)
    1. use WinSCP put roqyBT installation file (mine is roqybt_0.9.9-2.deb)  to /private/var/tmp/
    2. open putty terminal 
    3. change the pwd to /private/var/tmp/ by type command : cd /private/var/tmp/
    4. run command  : dpkg -i roqybt_0.9.9-2.deb
    5. reboot iPhone
    Crack roqyBT 

    1. google cr-roqybt.ipa
    2. install it by using iTune
    3. start roqyBT from iPhone
    4. click [Licence Manager] 
    5. copy the Serial # : ??? 
    6. start cr-roqy
    7. Paste the Serial # copied to [Enter serila here ....]
    8. Click [General] button, it will show a license number, and already be copied to pasteboard
    9. start roqyBT again
    10. click [Licence Manager] 
    11. Paste license number to text field below Step 3
    Done! The Licence Manager is checked.