Category Archives: Powershell

Install Module with PowerShell: NuGet Unable to download, check your internet connection

While installing the NuGet PowerShell module, you will get the following error

WARNING: MSG:UnableToDownload «https://go.microsoft.com/fwlink/?LinkID=627338&clcid=0x409» «»
WARNING: Unable to download the list of available providers. Check your internet connection.
WARNING: Unable to download from URI 'https://go.microsoft.com/fwlink/?LinkID=627338&clcid=0x409' to ''.
Install-PackageProvider : No match was found for the specified search criteria for the provider 'NuGet'. The package provider requires 'PackageManagement' and 'Provider' tags. Please check if the specified package has the tags.
At line:1 char:1
+ Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (Microsoft.Power...PackageProvider:InstallPackageProvider) [Install-PackageProvider], Exception
+ FullyQualifiedErrorId : NoMatchFoundForProvider,Microsoft.PowerShell.PackageManagement.Cmdlets.InstallPackageProvider

To resolve the problem open a PowerShell window as Administrator and enter the following command.
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

This will resolve the problem temporarily as if you would run the command again, it will still prompt the same problem. To resolve the issue permanently, you need to update the registry by running the below command to update the registry.

Set-ItemProperty -Path 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord

Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord

Close all PowerShell windows and try again with the following command to confirm that the protocol has been updated.

[Net.ServicePointManager]::SecurityProtocol

(122)

Fix: The term ‘Get-MsolUser’ is not recognized as the name of a cmdlet

When connecting to your Office 365 services, you might get the below error saying for any Msol cmdlet like new-msoluser, connect-msolservices and other.

The term 'Get-MsolUser' is not recognized as the name of a cmdlet

To fix this, download and install the Microsoft Online Services Sign-In Assistant for IT Professionals RTW which can be downloaded from this link.

After the installation you can check the installation of the assistant from your control panel. After that open a PowerShell window As Administrator and type.

Install-Module MSOnline -Force

Once done, enter the below

Connect-MsolService

Sign in with your global admin account and presto!

(6889)

How to: Find the installation date of an operating system

Sometimes I would need to find the date when the operating system was installed. Thou it’s difficult to have everything in shape with your inventory, if you have missed this part when an Operating System was installed, here’s a PowerShell solution to that.

Open PowerShell as admin
Type $osdate = get-wmiobject win32_operatingsystem
Type $osdate.ConvertToDateTime($os.InstallDate) -f "MM/dd/yyyy"

This will give you the date when the Operating System was installed

On the other hand, if you wish to go through registry yourself, browse to the location below

HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\InstallDate

The result is in timestamp, so you need to convert it with this link.

(88)

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
}

(295)

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

(15144)

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()

(20135)

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

(739)

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

(579)

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.

(6769)

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.

(8873)