Shortcut that will launch & run Office 365 PowerShell command line commands

I am looking for a way where I can click on a single file icon that will launch the Windows Power Shell and run the following commands:

$UserCredential = Get-Credential
Connect-MsolService -Credential $UserCredential

So I will be prompted to and will be able to logon to Office 365 with my administrator account.

What is the best way to do this?
IT GuyNetwork EngineerAsked:
Who is Participating?
Jeremy WeisingerSenior Network Consultant / EngineerCommented:
You can accomplish this a few ways. Here's two of them.

1. Save your script to a file (.ps1) and then create a .bat file that will launch powershell and run the file. e.g.:
powershell.exe -noexit -executionpolicy bypass -file C:\Office365.ps1

Open in new window

2. Convert your script to an encoded command and run that from the batch file. e.g.
 a. Encode your script:
$command = '@
$LiveCred = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri -Credential $LiveCred -Authentication Basic -AllowRedirection
Import-PSSession $Session
Connect-MsolService -Credential $LiveCred

$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)

Open in new window

Then take the output string and put it in the batch file:

Open in new window

ITSysTechSenior Systems AdministratorCommented:
You can do this by creating a file like Office 365.ps1 (create a .txt file and rename it) and put in the script, then to run it you right click the file and chose "Run with Powershell".
Save this is Office365.cmd or Whatever.cmd
It's PowerShell at heart, but wrapped in batch for easier execution.
You can add more Powershell commands that you want to automatically run below the first two lines.
@PowerShell.exe -NoExit -Command "Invoke-Expression -Command ((Get-Content -Path '%~f0' | Select-Object -Skip 2) -join [environment]::NewLine)"
@exit /b %Errorlevel%
$UserCredential = Get-Credential -Message "Please enter the Office 365 credentials"
"Hello, $($UserCredential.UserName)" | Write-Host -ForegroundColor Yellow
Connect-MsolService -Credential $UserCredential

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.