Monday 31 August 2020

Sunday 30 August 2020

美丽的草原我的家

powershell 21 change file content on remote computer

original remote file

remote file after update

PS C:\Windows\System32> $contents = invoke-command -session $session -scriptblock {
>>     $fileName = "C:\Users\zchen\Desktop\abc.txt"
>>     (Get-Content -Path $fileName) |
>>         ForEach-Object {$_ -Replace 'line2', $Env:COMPUTERNAME} |
>>             Set-Content -Path $fileName
>>     Get-Content -Path $fileName
>> }

PS C:\Windows\System32> $contents
line1
DESKTOP-K1RH4M9
line3

reference:

Saturday 29 August 2020

modern farming

powershell 20 cpu stress test on remote computer

before stress test

during stress test

after stress test

 
invoke-command -session $session -scriptblock {
    function stress-cpu {
        [cmdletbinding()]
        param(
            [parameter(mandatory = $true)][int]$NumHyperCores
        )

        Write-Output "============= CPU Stress Test Started: $(get-date) ============="
        Write-Warning "This script will potentially max your CPU utilization!"
        $Prompt = Read-Host "Are you sure you want to proceed? (Y/N)"

        if ($Prompt -eq 'Y') {
            Write-Warning "To cancel execution of all jobs, close the PowerShell Host Window."
            Write-Output "Hyper Core Count: $NumHyperCores" 
            Measure-Command {
                foreach ($loopnumber in 1..$NumHyperCores) {
                    Start-Job -ScriptBlock {
                        $result = 1
    
                        foreach ($number in 1..214748369) {
                            $result = $result * $number
                        }
                    }
                }

                Wait-Job *
                Clear-Host
                Receive-Job *
                Remove-Job * 
            }
        }
        else {
            Write-Output "Cancelled!"
        }
    }

    stress-cpu -NumHyperCores 8
}

-------------------------------------
#stop test

invoke-command -session $session -scriptblock {
    get-job | Stop-Job
}

Excavator Factory

Thursday 27 August 2020

powershell 19 uninstall program on remote computer

invoke-command -session $session -scriptblock {
    Function Get-InstalledSoftware {...
}
       
    $uninstallCmd = Get-InstalledSoftware | where-object {$_.name -like "*notepad++*"}`
}

Name             : Notepad++ (64-bit x64)
Version          : 7.8.8
ComputerName     : DESKTOP-K1RH4M9
InstallDate      :
UninstallCommand : C:\Program Files\Notepad++\uninstall.exe
RegPath          : HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall\Notepad++
PSComputerName   : 192.168.0.24
RunspaceId       : 8c303d60-de06-4ccb-b710-089894bed654
------------------------------------------------------

invoke-command -session $session -scriptblock {
    Function Get-InstalledSoftware {...
}
       
    $uninstallCmd = Get-InstalledSoftware | where-object {$_.name -like "*notepad++*"}`
    
    Start-Process -Wait -FilePath $uninstallCmd.UninstallCommand -ArgumentList "/S" -PassThru 
}

 NPM(K)    PM(M)      WS(M)     CPU(s)      Id  SI ProcessName                        PSComputerName
 ------    -----      -----     ------      --  -- -----------                        --------------
      3     0.68       1.71       0.05    9880   0 uninstall                          192.168.0.24
------------------------------------

Function Get-InstalledSoftware {
    Param(
        [Alias('Computer','ComputerName','HostName')]
        [Parameter(
            ValueFromPipeline=$True,
            ValueFromPipelineByPropertyName=$true,
            Position=1
        )]
        [string]$Name = $env:COMPUTERNAME
    )
    Begin{
        $lmKeys = "Software\Microsoft\Windows\CurrentVersion\Uninstall","SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
        $lmReg = [Microsoft.Win32.RegistryHive]::LocalMachine
        $cuKeys = "Software\Microsoft\Windows\CurrentVersion\Uninstall"
        $cuReg = [Microsoft.Win32.RegistryHive]::CurrentUser
    }
    Process{
        if (!(Test-Connection -ComputerName $Name -count 1 -quiet)) {
            Write-Error -Message "Unable to contact $Name. Please verify its network connectivity and try again." -Category ObjectNotFound -TargetObject $Computer
            Break
        }
        $masterKeys = @()
        $remoteCURegKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($cuReg,$Name)
        $remoteLMRegKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($lmReg,$Name)
        foreach ($key in $lmKeys) {
            $regKey = $remoteLMRegKey.OpenSubkey($key)
            foreach ($subName in $regKey.GetSubkeyNames()) {
                foreach($sub in $regKey.OpenSubkey($subName)) {
                    $masterKeys += (New-Object PSObject -Property @{
                        "ComputerName" = $Name
                        "Name" = $sub.GetValue("displayname")
                        "SystemComponent" = $sub.GetValue("systemcomponent")
                        "ParentKeyName" = $sub.GetValue("parentkeyname")
                        "Version" = $sub.GetValue("DisplayVersion")
                        "UninstallCommand" = $sub.GetValue("UninstallString")
                        "InstallDate" = $sub.GetValue("InstallDate")
                        "RegPath" = $sub.ToString()
                    })
                }
            }
        }
        foreach ($key in $cuKeys) {
            $regKey = $remoteCURegKey.OpenSubkey($key)
            if ($regKey -ne $null) {
                foreach ($subName in $regKey.getsubkeynames()) {
                    foreach ($sub in $regKey.opensubkey($subName)) {
                        $masterKeys += (New-Object PSObject -Property @{
                            "ComputerName" = $Name
                            "Name" = $sub.GetValue("displayname")
                            "SystemComponent" = $sub.GetValue("systemcomponent")
                            "ParentKeyName" = $sub.GetValue("parentkeyname")
                            "Version" = $sub.GetValue("DisplayVersion")
                            "UninstallCommand" = $sub.GetValue("UninstallString")
                            "InstallDate" = $sub.GetValue("InstallDate")
                            "RegPath" = $sub.ToString()
                        })
                    }
                }
            }
        }
        $woFilter = {$null -ne $_.name -AND $_.SystemComponent -ne "1" -AND $null -eq $_.ParentKeyName}
        $props = 'Name','Version','ComputerName','Installdate','UninstallCommand','RegPath'
        $masterKeys = ($masterKeys | Where-Object $woFilter | Select-Object $props | Sort-Object Name)
        $masterKeys
    }
    End{}

Wednesday 26 August 2020

powershell 18 download and install program on remote computer

remote desktop starts

 $session = new-pssession -computername 192.168.0.24 -credential $credential

#download notepad++ on remote desktop
PS C:\Windows\System32> invoke-command -session $session -scriptblock {
>>     $url = "https://github.com/notepad-plus-plus/notepad-plus-plus/releases/download/v7.8.8/npp.7.8.8.Installer.x64.exe"
>>     $outFile = 'C:\Users\public\Desktop\npp.7.8.8.Installer.x64.exe'
>>     [System.Net.ServicePointManager]::SecurityProtocol=[System.Net.SecurityProtocolType]::Tls12
>>     Invoke-WebRequest -Uri $url -Method Get -OutFile $outFile
>> }

#verify program downlaoded
PS C:\Windows\System32> $downloadComplete = invoke-command -session $session -scriptblock {
>>     $outFile = 'C:\Users\public\Desktop\npp.7.8.8.Installer.x64.exe'
>>     Test-Path $outFile
>> }
PS C:\Windows\System32> $downloadComplete
True

notepad++ downloaded
#install notepad in the background
PS C:\Windows\System32> invoke-command -session $session -scriptblock {                                           >>     $outFile = 'C:\Users\public\Desktop\npp.7.8.8.Installer.x64.exe'                                                 >>     Start-Process -Wait -FilePath $outFile -ArgumentList "/S" -PassThru                                              >> } 
                                                                                                                                                               NPM(K)    PM(M)      WS(M)     CPU(s)      Id  SI ProcessName                        PSComputerName                     ------    -----      -----     ------      --  -- -----------                        --------------                          8     1.44       3.70       0.28    1460   0 npp.7.8.8.Installer.x64            192.168.0.24    

notepad++ intstalled on remote computer

Money Affirmations | Listen Before You Sleep

Tuesday 25 August 2020

powershell 17 transfer file between remote and local computers

 PS C:\Windows\System32> $session = new-pssession -computername 192.168.0.24 -credential $credential                     PS C:\Windows\System32>  $session

 Id Name            Transport ComputerName    ComputerType    State         ConfigurationName     Availability
 -- ----            --------- ------------    ------------    -----         -----------------     ------------            1 Runspace1       WSMan     192.168.0.24    RemoteMachine   Opened        Microsoft.PowerShell     Available 

remote desktop before transfer
#transfer file to remote
Copy-Item -Path C:\Users\bob\Desktop\redux.txt -Destination 'C:\Users\Public\Desktop' -ToSession $session

file copied to remote desktop
#check if file exist on remote
PS C:\Windows\System32> $fileExistOnRemote = invoke-command -session $session -scriptblock {Test-Path 'C:\users\public\desktop\redux.txt'}

PS C:\Windows\System32> $fileExistOnRemote
True 

#delete file on remote
PS C:\Windows\System32>  invoke-command -session $session -scriptblock {Remove-Item 'C:\users\public\desktop\redux.txt'}

file is deleted on remote

PS C:\Windows\System32> $fileExistOnRemote = invoke-command -session $session -scriptblock {Test-Path 'C:\users\public\desktop\redux.txt'}

PS C:\Windows\System32> $fileExistOnRemote
False 

remote D drive contains 2 png files
#transfer from remote to local
PS C:\Windows\System32> Copy-Item -FromSession $session -path 'd:\*.png' -Destination 'C:\Users\bob\Desktop'

all png files are copied to local desktop

reference:
copy file to remote

delete file on remote

check file existence

copy file from remote

copy file with specific extension

connect to remote

Monday 24 August 2020

seafood tub Singapore

试飞员李刚


试飞员是科学的探险家,是飞行理论的探索者,飞机设计的参与者,飞行的先行者。

powershell 16 export remote computer security logs as csv

PS C:\Windows\System32> Enable-PSRemoting -Force  
PS C:\Windows\System32> Set-Item wsman:\localhost\client\trustedhosts *

PS C:\Windows\System32> Restart-Service WinRM
PS C:\Windows\System32> test-netconnection -computername 192.168.0.24 -port 5985

ComputerName     : 192.168.0.24
RemoteAddress    : 192.168.0.24
RemotePort       : 5985
InterfaceAlias   : Wi-Fi 2
SourceAddress    : 192.168.0.18
TcpTestSucceeded : True

PS C:\Windows\System32> $credential=get-credential

PS C:\Windows\System32> $session = new-pssession -computername 192.168.0.24 -credential $credential
PS C:\Windows\System32> $session

 Id Name            Transport ComputerName    ComputerType    State         ConfigurationName     Availability
 -- ----            --------- ------------    ------------    -----         -----------------     ------------
  9 Runspace9       WSMan     192.168.0.24    RemoteMachine   Opened        Microsoft.PowerShell     Available

#obtain security logs of remote computer for last hour
$securityLogs = invoke-command -session $session -scriptblock {
    Get-EventLog Security | where TimeWritten -gt (get-date).AddHours(-1)
}

$securityLogs | Export-Csv ~\desktop\report.csv

security logs saved on desktop

reference:

Sunday 23 August 2020

powershell 15 timer event

PS C:\Users\bob> $timer = New-Object Timers.Timer
PS C:\Users\bob> $timer | Get-Member -type Event
   TypeName: System.Timers.Timer

Name     MemberType Definition
----     ---------- ----------
Disposed Event      System.EventHandler Disposed(System.Object, System.EventArgs)
Elapsed  Event      System.Timers.ElapsedEventHandler Elapsed(System.Object, System.Timers.ElapsedEventArgs)

#manually check if timer event fires
PS C:\Users\bob> Register-ObjectEvent -InputObject $timer -EventName Elapsed
PS C:\Users\bob> Get-Event
PS C:\Users\bob> $timer.Interval = 5000
PS C:\Users\bob> $timer.AutoReset = $false
PS C:\Users\bob> $timer.Enabled = $true
PS C:\Users\bob> Get-Event

ComputerName     :
RunspaceId       : da9405ad-7c81-49cb-aa86-2dae09280e3c
EventIdentifier  : 1
Sender           : System.Timers.Timer
SourceEventArgs  : System.Timers.ElapsedEventArgs
SourceArgs       : {System.Timers.Timer, System.Timers.ElapsedEventArgs}
SourceIdentifier : f27b201f-c07d-4566-8a3c-7965f88d8ec3
TimeGenerated    : 2020-08-23 1:40:15 PM
MessageData      :

PS C:\Users\bob> Get-Event | Remove-Event

PS C:\Users\bob> Get-EventSubscriber

SubscriptionId   : 1
SourceObject     : System.Timers.Timer
EventName        : Elapsed
SourceIdentifier : f27b201f-c07d-4566-8a3c-7965f88d8ec3
Action           :
HandlerDelegate  :
SupportEvent     : False
ForwardEvent     : False

PS C:\Users\bob> Get-EventSubscriber | Unregister-Event

#synchronously wait for event to fire, user control is disabled while waiting
 PS C:\Users\bob> Register-ObjectEvent -InputObject $timer -EventName Elapsed -SourceIdentifier "WaitingForTimer"
PS C:\Users\bob>
PS C:\Users\bob> $timer.Interval = 10000
PS C:\Users\bob> $timer.AutoReset = $false
PS C:\Users\bob> $timer.Enabled = $true
PS C:\Users\bob> Wait-Event "WaitingForTimer"

ComputerName     :
RunspaceId       : da9405ad-7c81-49cb-aa86-2dae09280e3c
EventIdentifier  : 2
Sender           : System.Timers.Timer
SourceEventArgs  : System.Timers.ElapsedEventArgs
SourceArgs       : {System.Timers.Timer, System.Timers.ElapsedEventArgs}
SourceIdentifier : WaitingForTimer
TimeGenerated    : 2020-08-23 1:50:41 PM
MessageData      :

Get-Event | Remove-Event
Get-EventSubscriber | Unregister-Event

#asynchronously fire event, while waiting for timer, other task can be done
PS C:\Users\bob> $timer.Interval = 2500
PS C:\Users\bob> $timer.AutoReset = $true
PS C:\Users\bob> $timer.Enabled = $true
PS C:\Users\bob>
PS C:\Users\bob> Register-ObjectEvent -InputObject $timer -EventName Elapsed -SourceIdentifier "Async Timer" -Action {Write-Host "Timer fired at " ([System.DateTime]::Now)}

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
1      Async Timer                     NotStarted    False                                Write-Host "Timer fired …

PS C:\Users\bob> Timer fired at  2020-08-23 2:00:37 PM
                 Timer fired at  2020-08-23 2:00:40 PM
                 Timer fired at  2020-08-23 2:00:42 PM
                 ...
                 get-event
                 Timer fired at  2020-08-23 2:00:57 PM
                  ...
                 Get-EventSubscriber

                 SubscriptionId   : 3
                 SourceObject     : System.Timers.Timer
                 EventName        : Elapsed
                 SourceIdentifier : Async Timer
                 Action           : System.Management.Automation.PSEventJob
                HandlerDelegate  :
                SupportEvent     : False
                ForwardEvent     : False
                ...
PS C:\Users\bob> Timer fired at  2020-08-23 2:07:57 PM
                 Timer fired at  2020-08-23 2:07:59 PM
                 Timer fired at  2020-08-23 2:08:02 PM
               > Unregister-Event -SourceIdentifier "Async Timer"
PS C:\Users\bob>

reference:

Saturday 22 August 2020

探访夏粮丰收区

seaborn 5 boxplot

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import signal
sns.set(style="darkgrid")

tips = sns.load_dataset("tips")
tips.head()

  total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4

sns.catplot(x="day", y="total_bill", kind="box", data=tips);

sns.catplot(x="day", y="total_bill", hue="smoker", kind="box", data=tips);

tips["weekend"] = tips["day"].isin(["Sat", "Sun"])
tips.head()

total_bill tip sex smoker day time size weekend
0 16.99 1.01 Female No Sun Dinner 2 True
1 10.34 1.66 Male No Sun Dinner 3 True
2 21.01 3.50 Male No Sun Dinner 3 True
3 23.68 3.31 Male No Sun Dinner 2 True
4 24.59 3.61 Female No Sun Dinner 4 True

sns.catplot(x="day", y="total_bill", hue="weekend",
            kind="box", dodge=False, data=tips);

diamonds = sns.load_dataset("diamonds")
diamonds.head()

  carat cut color clarity depth table price x y z
0 0.23 Ideal E SI2 61.5 55.0 326 3.95 3.98 2.43
1 0.21 Premium E SI1 59.8 61.0 326 3.89 3.84 2.31
2 0.23 Good E VS1 56.9 65.0 327 4.05 4.07 2.31
3 0.29 Premium I VS2 62.4 58.0 334 4.20 4.23 2.63
4 0.31 Good J SI2 63.3 58.0 335 4.34 4.35 2.75

len(diamonds)
53940

sns.catplot(x="color", y="price", kind="boxen",
            data=diamonds.sort_values("color"));