• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

Tachytelic.net

  • Sco Openserver
    • Sco Unix Support
    • SCO Openserver Installation ISOs
    • SCO Openserver Binaries
    • Add a Hard Drive to an Openserver 5 Virtual Machine
    • Install SCO Vision SQL-Retriever ODBC Driver on Windows 10
    • License Expired on Virtual SCO Openserver Installation
    • How to reset the root password on SCO Openserver 5
  • Scripting
    • PowerShell
      • Add leading zeros
      • Check if a File Exists
      • Grep with Powershell
      • Create Environment Variables
      • Test for open Ports
      • Append to a Text File
    • VBScript
      • Check if a File Exists
      • lpad and rpad functions
      • Windows Update E-Mail Notification
  • Office 365
    • Connect to Office 365 with PowerShell
    • Add or remove an email alias using Powershell
    • Change Primary email address of Active Directory user
    • How to hide an AD user from the Global Address List
    • How to hide mail contacts from the Global Address List
    • Change the primary email address for an account with PowerShell
    • Change Primary email address of an AD User
    • Grant a single user access to access to all calendars
    • Forward email to an external address using Powershell
    • Convert shared mailbox to user mailbox with Powershell
  • Get in Touch
  • About Me
    • Privacy Policy

Powershell

Check if File Exists with Powershell

May 1, 2019 by Paulie 2 Comments

It’s very easy to check if a file exists with Powershell and take an action if so, here are some examples:

Check if a file exists

$fileToCheck = "C:\tmp\test.txt"
if (Test-Path $fileToCheck -PathType leaf)
{
    #do some stuff
}

Delete file if it exists

$fileToCheck = "C:\tmp\test.txt"
if (Test-Path $fileToCheck -PathType leaf)
{
    Remove-Item $fileToCheck
}

An even shorter method….

$fileToCheck = "c:\tmp\test.txt"
Remove-Item $fileToCheck -ErrorAction Ignore

Check if a file exists and get the content

$fileToCheck = "C:\tmp\test.txt"
if (Test-Path $fileToCheck -PathType leaf) {Get-Content $fileToCheck}

Check if a file exists and print a message if it does or does not exist

$fileToCheck = "C:\tmp\test.txt"
if (Test-Path $fileToCheck -PathType leaf) 
{"File does Exist"}
else
{"File does not exist"}

Check if a file exists and show the properties of the file

$fileToCheck = "C:\tmp\test.txt"
if (Test-Path $fileToCheck -PathType leaf)
{
    $file = Get-Item $fileToCheck
    $file.FullName
    $file.LastAccessTime
    $file.Length
    $file.Extension
    #etc...
}

Check if a file exists and move it to a new location

$fileToCheck = "C:\tmp\test.txt"
$newPath = "c:\tmp\newFolder"
if (Test-Path $fileToCheck -PathType leaf) 
{
    Move-Item -Path $fileToCheck -Destination $newPath
    "$fileToCheck moved to $newPath"
}

It’s obvious from the above examples that Test-Path simply returns a Boolean (i.e. True or False) and executing it on its own will produce exactly that:

Image showing result from Powershell "Test-Path" to check if a file exists.

The PathType parameter is not strictly required, but it is useful if you want to be sure the check you are performing is actually a file, not a directory.

You can check for a directory by setting PathType to “container”

Filed Under: How To Tagged With: Powershell

How to grep with PowerShell

April 25, 2019 by Paulie 1 Comment

Unix and Linux have had the incredibly powerful grep tool for decades but windows has always been lacking. PowerShell brings the functionality of grep with the Select-String cmdlet.

Use Select-String to Grep a Single File

To grep a simple text file is as easy as:
Select-String -Path "D:\script\Lorem-Ipsum.txt" -Pattern 'Tachytelic'

You can also use a wildcard:
Select-String -Path "D:\script\*.txt" -Pattern 'Tachytelic'

Grep Recursively with Get-Childitem

Unlike grep, Select-String does not have the ability to search recursively, but you can pipe output to it from Get-ChildItem, like this:
Get-ChildItem -Path "D:\Script\*.txt" -Recurse | Select-String -Pattern 'tachytelic'

Piping to Select-String

Just like grep, you can pipe to Select-String like this:
Get-Content "D:\Script\Lorem-Ipsum.txt" |Select-String "tachytelic"

If you want to make it more like Unix/Linux, add an alias to the Select-String cmdlet:
Set-Alias -Name grep -Value Select-String

Then you can simply pipe to Select-String like this:
cat "D:\Script\Lorem-Ipsum.txt" |grep "tachytelic"

Loop through results from Select-String

Here is an example that greps for a string and uses the results in a loop to determine if some action should be taken:

$pattern = "tachytelic"
$files = Select-String -Path "d:\script\*.txt" -Pattern $pattern
foreach ($file in $files) {
  $filename=$file.Filename
    $item = get-item $file.Path
    "File '{0}' matches the pattern '{1}'" -f $item.FullName, $pattern
    "It was last modified on {0}" -f $item.LastWriteTime
 
  $response = Read-Host -Prompt "Set the archive bit on this file?" 
  If ($response -eq 'Y') {
    $item.attributes="Archive"
    }
}

Which produces output like this:
Example output from Powershell providing grep functionality

grepping in Powershell seems to be incredibly fast, I have not conducted any testing against the performance of GNU Grep, but I don’t think you will be disappointed by the performance.

Filed Under: How To Tagged With: Powershell

Use PowerShell to Set Environment Variables

March 11, 2019 by Paulie 3 Comments

Setting environment variables in PowerShell is easy. This post will show you how to create a PowerShell environment variable which is scoped:

  • Locally to your current PowerShell session.
  • To your user profile and available to all other processes that you execute
  • To the machine, and accessible to all processes that run on that system.

Set a locally scoped Environment Variable

To create an environment variable that is local to your current PowerShell session, simply use:

$env:SiteName = 'tachytelic.net'

Then you can check the value of the environment variable with this code:

Get-ChildItem Env:SiteName

Image showing how to set a local Environment Variable in Powershell

This method is fine, but the variable will vanish when the PowerShell process ends.

Set an Environment Variable scoped to the User

To set an environment variable which will be available to all processes that your account runs, use the following:

[System.Environment]::SetEnvironmentVariable('siteName','tachytelic.net',[System.EnvironmentVariableTarget]::User)

Now you can see the variable is set from the Environment variables section of the system properties:

Image showing currently set User Environment Variables

Set an Environment Variable scoped to the Machine

To create an environment variable visible to every process running on the machine:

[System.Environment]::SetEnvironmentVariable('siteName','tachytelic.net',[System.EnvironmentVariableTarget]::Machine)

Note: This command will probably fail unless you run PowerShell as an administrator.

The new PowerShell System environment variable is visible:

Image showing system environment variable added by PowerShell

It’s quite interesting that the PowerShell environment variables are stored in a drive, which you can access using:

Set-Location Env:
Get-ChildItem

For more information on how PowerShell environment variable work, read the Microsoft documentation here.

Filed Under: Scripts & Utilities Tagged With: Powershell

How to connect to Office 365 with PowerShell

December 22, 2018 by Paulie 2 Comments

Many of the posts on this blog and others will require you to connect to Office 365 with PowerShell. The web admin interface for Office 365 is very good, but there are times when PowerShell is more suited. So this post shows you how it is done and the problems you might come up against. I will go through each step in detail and then post complete code.

Connect to Office 365 with PowerShell

  1. Open a PowerShell session
  2. Store your Credentials in a variable:
    $Cred = Get-Credential
  3. Enter your Office 365 Credentials when prompted:
    Image showing dialog of Office 365 Credentials used to connect to Office 365
  4. Create a new PowerShell session from the Office 365 Server:
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $Cred -Authentication Basic -AllowRedirection

    Image showing import of PowerShell session from Office 365

  5. Import the session:
    Import-PSSession $Session

    If you do not receive any errors on this step, continue to step 6. You may receive the error:

    Import-PSSession : Files cannot be loaded because running scripts is disabled on this system.

    If you do get this error, you need to change your PowerShell Execution Policy.

  6. Now you can run any commands you need.
  7. When you have finished, remove the session you created in step 2:
    Remove-PSSession $Session

Complete code to connect to Office 365 with PowerShell

$Cred = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $Cred -Authentication Basic -AllowRedirection
Import-PSSession $Session
# Run any commands you want here
Remove-PSSession $Session

Change PowerShell Execution Policy

If you received this error when you tried to execute step 5:

Import-PSSession : Files cannot be loaded because running scripts is disabled on this system.

Then you need to change your PowerShell execution policy. To connect to Office 365 with Powershell your execution policy to at least Remote signed:

  1. Open PowerShell as an administrator:
    Image showing how to run PowerShell as an administrator to change execution policy
  2. In your PowerShell window run the command:
    Set-ExecutionPolicy RemoteSigned
  3. Choose “Y” when prompted to change the execution policy.

You will now be able to connect to Office 365 with Powershell.

Filed Under: How To Tagged With: Office 365, Powershell

Office 365: How to add or remove an email alias using Powershell

December 19, 2018 by Paulie 4 Comments

Use the Powershell cmdlet Set-Mailbox to check email aliases assigned to Office 365 accounts, add aliases or remove aliases. Additionally the handy form underneath will generate the correct Powershell commands for you.

Check current email aliases assigned to an Office 365 account:

Get-Mailbox mailboxName | select -ExpandProperty emailaddresses | Select-String -Pattern "smtp"

Add an email alias to an Office 365 account:

Set-Mailbox mailboxName -EmailAddresses @{Add='[email protected]'}

Remove an email alias from an Office 365 account:

Set-Mailbox MailboxName -EmailAddresses @{Remove=’[email protected]’}

Or you can just use the form below and the required Powershell will be generated for you….








Now that you have got multiple email aliases, here is how to configure Outloook so that you can send from an alias.

Filed Under: How To, Office 365 Tagged With: Exchange, Office 365, Powershell

  • « Go to Previous Page
  • Go to page 1
  • Go to page 2
  • Go to page 3
  • Go to page 4
  • Go to page 5
  • Interim pages omitted …
  • Go to page 8
  • Go to Next Page »

Primary Sidebar

Link to my LinkedIn Profile

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 107 other subscribers.

Go to mobile version