Friday 20 February 2015

Display first n lines, lines in middle or last n lines of a file with powershell.

Display first n lines, lines in middle or last n lines of a file with powershell.

Sometimes we need some specific content for a file, may be a version number , config details that lies in a specific file or config file.

We will be using the PowerShell cmdlets to achieve this.

Create a file with 10 lines with 1..10 and name it as file.txt



Now we use the cmdlet Get-content and get the required output using select.

Getting first 5 lines


Getting last 5 lines


Skipping first 3 lines and displaying rest..

Display some line in the middle say line 5,



This could be a useful approach to get the data fast across infrastructure with the help of PS remoting.

Tuesday 17 February 2015

PowerShell to Remove Characters in a String

How to remove characters in a string using powershell

Lets start of with examples, and we have to use the –Replace operator, create a regular expression pattern that includes what you want to remove and then write the results back to the variable.

Note: here we are over writing the variable with the replaced characters.

$string = '{Abcde123**$45}'

$string =  $string -replace '[{}]','' # this will remove the {}

$string = $string -replace '12','' # this will remove 12

$string = $string -replace '12','{}' # this will replace 12 with {}

$string = $string -replace '\$','' # this would remove the $ sign Note: the \ before the $ after replace command.

Lets try one by one in PowerShell.





Get AD User expiration date from PowerShell


 Get AD User expiration date from PowerShell


To get the user expiration date on Active Directory from Powershell with proper formatting.

Try the below cmdlet.

Get-ADUser -Identity xxxxxx –Properties "DisplayName", "msDS-UserPasswordExpiryTimeComputed" | Select-Object -Property "Displayname",@{Name="ExpiryDate";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}






How to execute powershell Script from CMD

How to execute powershell Script from CMD

To execute PowerShell scripts in windows CMD prompt we have to use the argument -File.

Example
Open Notepad and copy/paste the below code and save it as print.ps1 extension ( be very careful and try not saving it as .ps1.txt )

Write-output "hello world!"

Then open the windows command prompt and assume that the script has been saved in temp folder, give the below line for the code to execute.


powershell -File "c:\temp\print.ps1"

Now, you could try more complicated stuff in your PowerShell Script.

Make AD User password Expire using Powershell.

Make AD User password Expire using Powershell.


If you want to make a user to change password the next time, use the below cmdlet.


#make user password expire
Get-ADUser -Identity (username) | Set-ADUser -ChangePasswordAtLogon:$true