Posts

Showing posts from December, 2019

Scheduled task in Windows Task Scheduler - part 3

This is the last part of Task Scheduler - security context which is created using New-ScheduledTaskPrincipal. Usually, we are using S4U logon type for any server scheduled task + Highest Run Level. S4U details as per MS documentation: Use an existing interactive token to run a task. The user must log on using a service for user (S4U) logon. When an S4U logon is used, no password is stored by the system and there is no access to either the network or encrypted files. You can find more information in this page:     https://docs.microsoft.com/en-us/windows/win32/taskschd/principal-logontype For any user ID that you specified to run the scheduled task, it requires "Log on as a batch job" or "Log on as a service". You can find the details here:     https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/log-on-as-a-batch-job     https://docs.microsoft.com/en-us/windows/security/threat-protection/...

Trigger an URL without waiting for its result

To trigger an URL, you simply execute the following command (curl is alias of Invoke-WebRequest):    curl "http://localhost:62037/run_proc.aspx" If the page requires longer time to complete, then, this command will block other process. To avoid it, we use Start-Job command to execute the curl command:   Start-Job -Name syncCourse -ScriptBlock { curl "http://localhost:62037/run_proc.aspx" } To view the job status, run the following command:   Get-Job Notes: the job is running in your current "session" - meaning, if you open another Powershell console, Get-Job will return empty result.

Executing DOS command with Powershell

It's best that we can write all scripts in Powershell.... that will be very nice. But, sometimes, it's more "convenient" to write the DOS command. To execute DOS command, we use "cmd /c" + the DOS command:    cmd /c "dir d:" We may execute the DOS command using Invoke-Expression:    $cmd = "dir d:\temp3"    Invoke-Expression -Command $cmd OR, to execute the Robocopy to copy the file from one folder to another:    $src = "d:\temp3\test"    $dst = "d:\temp3\test2"    $cmd = "robocopy $src $dst /S /E /COPYALL /DCOPY:T /R:10 /W:10 /NP /TEE"    Invoke-Expression -Command $cmd

Restart IIS appPool

During the development of new web apps, we often perform testing with different system setup (where the values are stored in the database). And we have many web app that runs on it's own appPool. Restarting the appPool manually takes quite a while. To avoid the cumbersome steps to restart all the necessary appPool, we came out with a script (shown below). It's convenient and never miss out any of the appPool that cripple the test case. Import-Module WebAdministration cd IIS:\AppPools $l = Get-ChildItem | where name -Like '*myApps*' | select name foreach ($a in $l) {     Write-Host "Restart appPool $($a.name).."     Restart-WebAppPool $($a.name) } Write-Host "Done"

Executing another Powershell script

To execute another ps file, just type the ps file name. Write-Output "Running test1.ps...." Write-Output "" # method #1 - run the hardcoded script file # #    .\test1.ps1 # # method #2 - run the script file name stored in a variable. $ps_file = "$PSScriptRoot\test1.ps1" & $ps_file

Install PowerShell WMF 5.1

Here is the Powershell WMF 5.1 installation files:     https://docs.microsoft.com/en-us/powershell/scripting/wmf/setup/install-configure?view=powershell-6#download-and-install-the-wmf-51-package In case you landed in different download page, please take note the "Windows 2012 R2" is different from "Windows 2012" (without "R2")     https://hemantmahajan08.wordpress.com/2017/08/16/update-powershell-to-5-1-on-windows-server-2012r2/

Create scheduled task in Windows Task Scheduler - part 2

The following script demo how to create daily & weekly tasks. $task_folder = "\myTasks\" $ps_script_file = "d:\temp5\test-script.ps1" <########################################### this is task #3 - DAILY ###########################################> $task_name = "myTask3" ## The first line will show err if $task_folder does not exist. ## The second line will not show any err if $task_folder does not exists. #$exist = Get-ScheduledTask -TaskPath $task_folder | Where-Object {$_.TaskName -eq $task_name} $exist = Get-ScheduledTask | where {$_.TaskPath -eq "\myTasks\" -and $_.TaskName -eq $task_name } if (!$exist)  {             $axn = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-ExecutionPolicy Bypass ""$ps_script_file"""         $sch = New-ScheduledTaskTrigger -Daily -At 5pm     Register-ScheduledTask -TaskName $task_name  -TaskPath $ta...

Declaring C# like Class type

Basically, if you are familiar with C# programming language, you will find it quite straight forward to do this in Powershell. The following sample code explains the basic of declaring class in PowerShell: # references: #  https://devblogs.microsoft.com/scripting/powershell-5-create-simple-class/ #  https://xainey.github.io/2016/powershell-classes-and-concepts/ # declare a new object type - the same way like C# class MyObject {     # instance fields     [string]$name     [string]$code     [int32]$age         # static fields     static [int]$objCount     # constructor     MyObject ([string]$n){         $this.name = $n         # increase the number of instance that has been created.         [MyObject]::objCount++;   ...

Parsing text into object

The result from a DOS command is text lines which does not have a "real" column. If you want to analyze the result, you must parse the text yourself. For example, we want to find out the IP to physical addresses, we use the following command:     arp -a The result looks like this: Interface: 192.168.1.100 --- 0x5   Internet Address      Physical Address      Type   192.168.1.1           18-31-bf-53-7a-24     dynamic     192.168.1.255         ff-ff-ff-ff-ff-ff     static      224.0.0.22            01-00-5e-00-00-16     static      224.0.0.251           01-00-5e-00-00-fb     sta...

Matching a string against a list of predefined strings

To match an input string against a list of predefined strings, we use -MATCH parameter. To demo how this works, we wrote a function that will check whether the input string is matching the weekday in the predefined format. Our weekday format:     "_" + "first 3 character of weekday text" So, our function will look like this (you may copy the script below into a ps1 file and execute it): # returns true if the weekday param is matching the predefined file name convention. function Is-weekday() {     param (         [string]$wd     )     if ($wd -match "_mon|_tue|_wed|_thu|_fri|_sat|_sun") {         return $true     }     return $false } # To test if it works, run the following line: $weekday = "_wed" Is-weekday $weekday # result on screen: Ttrue # Let says we remove the underscore symbol from $weekday, we will get Fal...

Create scheduled task in Windows Task Scheduler

Windows Task Scheduler is a utility that helps to execute any process periodically. For example, you want to sync your working files on daily basis, scanning virus, process some data, etc. A task has the following components: Action or multiple actions - which is the process that you want to run periodically. We use New-ScheduledTaskAction to create new action object. Trigger - which is the time to run the process and it can have multiple timing. We use New-ScheduledTaskTrigger to create new trigger. Security context - any process must run in a valid security context. We can set the context using New-ScheduledTaskPrincipal. The following script creates an on demand task which requires user to manually trigger the task. $task_folder = "\myTasks\" $task_name = "myTask2" # this can be any Powershell script. $ps_script_file = "d:\temp5\test-script.ps1" ## The first line will show err if $task_folder does not exist. ## The second line will not...