Category Archives: Powershell

How to: Crop filenames with Powershell

Sometimes you would create some scripts to work with files and for example SQL creates backup files and it adds _backup_timestamp so it’s not easy to work with them in a script.

The below script will crop how much characters you want from the back. Simply change the $location (location of files) $extnsion (file extension) and $characterstoremove (number of characters to remove). This will crop the files to the length you need using Powershell.

$location = "C:\test"
$extension = ".bak"
$characterstoremove = -37
$filelist = (get-childitem $location | Where-Object {$_.mode -match "a"} | foreach-object {$_.name})
foreach ($file in $filelist)
{
$len = $file.length
$len = $len+" "+$characterstoremove
$newname = $file.substring(0,$len)
$newname = $newname + $extension
$newfilename = $location+"\"+$file
Rename-Item $newfilename $newname
clear-variable newname, len
}

(28)

How to: Remove Exchange mailbox export requests

After a number of exports or imports, you might need to clean up the failed, completed or other status when running the get-mailboxexportrequest report in PowerShell. To clean these open the Exchange PowerShell and run the below.

Clean Export requests
Get-MailboxExportRequest -Status Completed | Remove-MailboxExportRequest
Get-MailboxExportRequest -Status Failed | Remove-MailboxExportRequest

Clean Import requests
Get-MailboxImportRequest -Status Completed | Remove-MailboxExportRequest
Get-MailboxImportRequest -Status Failed | Remove-MailboxExportRequest

(148)

Fix: PowerShell does not wait before starting the next command

When creating a Powershell script and executing something in the middle of the script it does not wait until that process finishes and continues executing the script.

This can be a pain since you might have something executing after the script which depends on the executable you run.

So, when you are executing the file and you want Powershell to wait before continuing you must add the following for it to wait until it finishes.

&Myfile.exe | Out-Null

By adding the Out-Null after your script, it will wait until the MyFile.exe finishes before continuing executing.

This method can be used for the Start-Process as below

Start-Process MyFile.exe -NoNewWindow -Wait

Or you can use this to the Wait For Exit parameter

$proc = Start-Process -NoWindow
$proc.WaitForExit()

(36)

How to: Check if port is open with Powershell

For sys admins it is important to know if ports of certain applications are open for monitoring. One simple solution is to have a monitoring software, but if you want a cheap and cheerful solution, you can use Powershell. This can be done by the below script.

The below script will check the server/port and if the port is open, it will just print on screen saying “PORT IS OPEN – OK” and if the port is not open or the service is down, it will send and email.

Feel free to change or add to this script. You can easily put this in a loop to check all the services in your enterprise.

#PARTS THAT CAN BE CHANGED
$MailServer = "mail.mydomain.com"
$MailTo = "sysadmin@mydomain.com"
$MailFrom = "IT <noreply@mydomain.com>"
$MailBody = "Please note that the server is not reachable in this test that runs every 10 minutes. Please check the status of the server."
$MailSubject = "** PORT IS NOT REACHABLE FOR SERVER 1 **"
$Server = "SQLSRV01"
$Server_port = "1433"
#PARTS THAT CAN BE CHANGED

$socket = New-Object Net.Sockets.TcpClient
$ErrorActionPreference = 'SilentlyContinue'

#Server and port
$socket.Connect($Server,$Server_Port)
$ErrorActionPreference = 'Continue'

if ($socket.Connected) {
Write-Host "POST IS OPEN - OK"
$socket.Close()
}
else
{
send-mailmessage -To $MailTo -from $MailFrom -Subject $MailSubject -body $MailBody -smtpserver $MailServer -BodyAsHtml -Encoding ([System.Text.Encoding]::UTF8)
}

$socket = $null

(405)

How to: Powershell list all computers in Active Directory

Sometimes you would need to have a list of all the computers joined to the domain in your infrastructure. Instead of going through all the Organizational Units (OUs) in your AD infrastructure and listing all the computers, you can easily use the below Powershell Script.

CLS
Import-Module ActiveDirectory
$ComputerName = get-ADComputer -Filter * | Select -Expand Name
Foreach ($CN in $ComputerName)
{  write-host $CN}

This will type a list of all the computers joined in your AD infrastructure.  Save it to a file with extension PS1 and run it. If you would like to save the output to file simply run the file by adding > filename.txt and replace the write-host with write-output

(485)

How to: Uninstall an application with Powershell using GPO

Sometimes you would need to automate an uninstall of an application through Group Policies (GPO). This can be done by running a PowerShell script. Firstly create a PowerShell script as below:

$appplication = Get-WmiObject -Class Win32_Product | Where-Object
{$_.Name -match "My Application Name"}
$application.Uninstall()

Save the file and create a new GPO and set the script to load by setting up the Computer Configuration/ Policies/ Windows Settings/ Scripts/ Startup.

(5608)

How to: Set PowerShell execution policy to unrestricted using GPO

Most often when you have to execute some PowerShell scripts through the GPO and you end up with an error on execution saying that the Execution Policy does not allow you to run un-signed script.

So you would need to create a new GPO to set the Execution Policy. Create a new  GPO and edit it.

Goto Computer Configuration/ Policies/ Administrative Templates/ Windows Components/ Windows PowerShell

Double-click on Turn on Script Execution
Click on Enabled
Select Allow All Scripts

Move the GPO onto the respective OU, wait until the refresh or simple run gpupdate /force on the computers.

(7863)