MS PowerShell Script Basic

1. Execution policy

– Restricted
– Unrestricted
RemoteSigned
AllSigned
– Bypass

 

> get-executionpolicy

Restricted

 

> set-executionpolicy unrestricted ; you must be as an Administrator.

Warning message ~

" The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose you to the security risks described in the about_Execution_Policies help topic.

Do you want to change the execution policy?

Yes(y), No(n) and Suspend(S)

 

 2. Running Script

 

*.ps1

 

The most common (default) way to run a script is by calling it:

PS C:\> & "C:\Belfry\My first Script.ps1"

If the path does not contain any spaces, then you can omit the quotes and the ‘&’ operator

PS C:\> C:\Belfry\Myscript.ps1

If the script is in the current directory, you must indicate this using .\ (or ./ will also work)

PS C:\> .\Myscript.ps1

 

 3. Examples

 

 

ex) Define Date(Yesterday)

$yesterday = (Get-Date).AddDays(-1).ToString("yyy_mm_dd")

Write-host = $yesterday

 

ex) Find a specific folder

Dir ([Environment]::GetFolderPath("Cookies"))

 

ex) Find a specific folder and delete the folder (force)

Dir ([Environment]::GetFolderPath("Cookies")) | del -force

 

 ex) Delete(force) cookies that is older than yesterday.

Dir ([Environment]::GetFolderPath("Cookies")) | where-object {$_.LastWriteDate -ge (Get-Date).addDays(-2) } | del -force

 

 ex) Find a membership from object list

Dir $obj | get-member | more

 

ex) Kill a process

C:\> Get-Process xxxxx | Stop=Process

 

ex) Find a service that is currently running.

C:\> Get-Service | where { $_.status -eq ‘running’}

 

To check PowerShell version

PS C:\> $PSVersionTable

 

 

 

 

 

Leave a Reply