Search This Blog

Showing posts with label powershell. Show all posts
Showing posts with label powershell. Show all posts

Three Ways to Split String in PowerShell

This post is to summarize three ways to split a string in PowerShell.

In the following example
$t = “1000ABC2000abc"
[regex]$rx1 = “\d+”
[regex]$rx2 = “ABC"

  • Using a regex object’s split method
    • In this method, the regex works and the match is case-sensitive

      PS > $rx1.split($t)

      ABC
      abc

      PS > $rx2.split($t)
      1000
      2000abc


  • Using a string object’s split method
    • In this method, the regex does not work and the match is case-sensitive

      PS > $t.split($rx1)
      1000ABC2000abc

      PS > $t.split($rx2)
      1000
      2000abc


  • Using a string object’s split operator
    • In this method, the regex works and the match is case-insensitive

      PS > $t -split $rx1

      ABC
      abc

      PS > $t -split $rx2
      1000
      2000

Match a string ending with a dollar sign ($) and containing a variable in PowerShell

In my previous post, I can match a string ending with a dollar sign ($) using the single quote with the expression ‘\$$’. Because the single quote protects the PowerShell automatic variable $$ from being evaluated. But it brings up my next question, how about the same expression also includes other variable that should be evaluated. Like this example.

PS C:\Temp> $name = 'smith'
PS C:\Temp>
PS C:\Temp> 'contoso\john.smith$' -match "$name"
True
PS C:\Temp> 'contoso\john.smith$' -match '$name'
False

Obviously, I have to use the double quote to evaluate the variable $name before sending the expression to the regex engine. But I also need the single quote for the variable $$.

PS C:\Temp> 'contoso\john.smith$' -match '$name\$$'
False
PS C:\Temp> 'contoso\john.smith$' -match "$name\$$"
False

Here is my solution - using double quote with both the regex escape character backslash(\) and PowerShell escape character backpack(`).

PS C:\Temp> 'contoso\john.smith$' -match "$name\$`$"
True

Let me explain
  • Use double quote to evaluate the variable $name
  • Use `$ to prevent the automatic variable $$. Using the PowerShell escape character (`) because it’s the PowerShell evaluation, not regex evaluation. So do not use \$ on the second $.
  • After the variable evaluation, the expression becomes smith\$$. This is passed to the regex engine. As expected, this regex matches the string ending with smith$.

Match a string ending with a dollar sign ($) in PowerShell

I want to match a string ending with a dollar sign ($) (e.g. ‘contoso\john.smith$’) in PowerShell. Using the regular expression (regex) should be simple, like \$$.

However, I run into some problem in PowerShell. I posted my question in Reddit for help. With the comments from the community, I think I finally understand how to handle this issue. This blog post is to summarize my understanding.
  • -match operator uses the regular expression syntax.
  • The scape character in regex is the backslash(\). Normally the regular PowerShell escape character, the backtick(`), should not use in the regex expression. See my next post on using both scape characters (\ and `) in one expression.
  • To match a string ending with a dollar sign ($), the regex should be \$$. The first $ is for the literal $, so it is escaped by \. The second $ is an anchor which matches the end of a string, so it is not escaped by \.
  • However $$ is an automatic variable in PowerShell.
  • When the expression(\$$) is doubled-quoted, PowerShell evaluates the variable $$ first before sending to the regex engine. “\$$” becomes “\{value of $$}” when being parsed by the regex engine. So it returns False.
PS C:\Temp> 'contoso\john.smith$' -match "\$$"
False
  • When the expression(\$$) is single-quoted, PowerShell does not evaluate any variable. The expression \$$ is parsed by the regex engine. So it returns True.
PS C:\Temp> 'contoso\john.smith$' -match '\$$'
True

In the case, I can match a string ending with $ by using the single quote with the expression '\$$'. However, this will not work if the expression includes other variable that should be evaluated. I will post my solution in the next post.

Set Visual Studio Code (VS Code) Default Language Mode When New File Opened

Visual Studio Code is my default PowerShell script editor. It is free and available in Windows, macOS, and Linux.

By default, it uses text as the script language when a new file is opened. To make it recognize the PowerShell cmdlet, I have to manually change the language mode (press F1, type Change Language Mode, then select PowerShell form the list of the language) or first save to the file to ps1. This becomes inconvenience overtime.

Luckily, a new setting “files.defaultLanguage” is added. I didn’t backtrack when this setting was added. It’s available in the current release 1.14.0 as of this writing.

To configure the default language setting,

  • Open File, Preferences, Settings
  • Add the following to set PowerShell as the default language mode
    • “files.defaultLanguage": "powershell",
  • Save the setting.json file

To set other supported languages as the default

  • Delete “powershell” in the line
  • Press Ctrl + Spacebar to select the option from the list

Use Get-FolderItem.ps1 to Fix PathTooLongException

When using Get-ChildItem to list all files in a folder and its subfolders, it returns the “PathTooLongException” error. This happens when the file path is more than 260 characters.

There are several ways to work around this issue. See this Technet Wiki.

Personally, I found the Get-FolderItem.ps1 script is the easiest one.

  1. Download the script from Microsoft Script Center Repository
  2. Right-click on the script and select Properties, then click Unblock
  3. Launch a PowerShell session
  4. Load the Get-FolderItem function into the session by entering “. <path>\Get-FolderItem.ps1”. (make sure there is a space between the “.” and the script)
  5. Enter “Get-FolderItem –Path <path>” to list all files in the folder and its subfolders
  6. Another use case “Get-FolderItem –Path <path> | Where {$_.LastWriteTime –gt “MM/DD/YYYY” } | Select FullName | Ft –autosize | Out-File c:\temp\modified.file.log.txt –width 4096

For more information about the Get-FolderItem.ps1 script, see this.

Prevent PowerShell Out-File Truncating Output

When trying to list the full path of all files in a folder and its subfolders, the Out-File cmdlet truncats the path for files with the long path.

It turns out that Out-File outputs the data with the same width of the PowerShell console (see Using the Out-File Cmdlet).

To work around the issue, include the –width parameter and specify a different line width(e.g. –width 4096). This outputs every line with 4096 characters long (pedding with spaces).

To output line width to match the longest output, add Ft –autosize before Out-File. For example:

Get-ChildItem -File -Recurse -Path Z:\ | where {$_.LastWriteTime -gt "MM/DD/YYYY"} | select FullName | Ft -autosize | Out-File c:\temp\modified.file.txt -Width 4096

Get-ADUser

Get-ADUser can get one or more Active Directory users; it’s part of Active Directory Module for Windows PowerShell.  It’s similar to Get-QADUser in Quest’s ActiveRoles Management Shell (However, ActiveRoles Management Shell can be installed on the older operating system)

Active Directory Module for Windows PowerShell is part of the Remote Server Administration Tools (RSAT) feature on a Windows Server 2008 R2 server; and it’s part of the RSAT feature on a Windows 7 computer (download).  However, it’s not available to install on any older operating system, including Windows Server 2008.

Basic usage of Get-ADUser

  • Get-ADUser –Filter { } or Get-ADUser –Filter *
  • Get-ADUser –Filter { } –SearchBase “DC=xxx,DC=com”
  • Get-ADUser –Filter { } –Properties * | Get-Member   # to get all the properties; be aware of the property name is different than Get-QADUser cmdlet.
  • Get-ADUser –Filter {} –Properties <propertyname1,propertyname2>  # to get the non-default properties to the pipeline

PowerShell Credential Input

$cred = Get-Credential

will prompt the user entering the credential that can be used in other PowerShell script.

image

Or $cred = Get-Credential –Credential domain_name\user_name

to fill in the default user name.

image

Use $WhatIfPreference in PowerShell to Prevent Accidents

  • The default value of $WhatIfPreference variable is $false.
  • Adding “$WhatIfPreference = $true” to a script or the PowerShell profile
  • Now every cmdlet that supports a whatif switch will execute as the whatif switch is on
  • To overwrite the setting in a particular cmdlet, add –whatif:false in the cmdlet

PowerShell ExecutionPolicy Bypass

Windows PowerShell v.2 supports a bypass execution policy.  It can be used to overwrite the computer execution policy setting in batch script.

image

The computer execution policy is restricted.  A PowerShell script can not be executed.

image

With the bypass option, the script is able to execute.

PowerShell: Avoid Bank Lines at End of a Text File

Use System.IO.File .NET Framework class’s Write AllText static method.

[System.IO.File]::WriteAllText(string path, string contents)

or [System.IO.File]::WriteAllText(string path, string contents, System.Text.Encoding encoding)

e.g. [system.io.file]::WriteAllText(“c:\fso\ioascii.txt”, $count, [System.Text.Encoding]::ascii)

More info: [system.io.file] | get-member –static WriteAllText | fl *

[system.text.encoding] | get-member –static –MemberType property

Reference: http://blogs.technet.com/b/heyscriptingguy/archive/2011/09/19/avoid-blank-lines-at-end-of-a-text-file-with-powershell.aspx

PowerGUI Script Editor Add-ons

  • Script Editor Essentials: add View White Space, Word Wrap and Virtual White Space menu items to the Edit | Advanced menu …
  • ExpandAlias: expand aliases in the code pane to the full cmdlet name.
  • Script Template: insert a header for new documents.
  • PShellExec: secure/encrypt scripts and execute them right inside the editor

Install Active Directory Module for Windows PowerShell

See Mike Pferiffer’s Blog below.  Notes Active Directory Web Services (ADWS) or Active Directory Management Gateway Service is required to use Active Directory Module.  Quest Software ActiveRoles Management Shell for Active Directory’s Get-QADUser without this requirement.

 

With the release of PowerShell 2.0, we now have a PowerShell module that we can use to administer Active Directory. The Active Directory Module for Windows PowerShell runs on Windows Server 2008 R2 and on Windows 7 and relies on a web service that is hosted on one or more domain controllers in your environment. In this post I'll go over what you need in order to install and use the Active Directory Module for PowerShell, also known as AD PowerShell.

Setting up your Domain Controllers

In order to use the Active Directory Module for Windows PowerShell on 2008 R2 and Windows 7, you first need to be running Active Directory Web Services (ADWS) on at least one Domain Controller. To install Active Directory Web Services (ADWS) you'll need one of the following:

1. Windows Server 2008 R2 AD DS

You can load Active Directory Web Services (ADWS) on a Windows Server 2008 R2 Domain Controller when you install the AD DS role. The AD PowerShell module will also be installed during this process. Active Directory Web Services (ADWS) will be enabled when you promote the server to a DC using DCPromo.

2. Active Directory Management Gateway Service

If you cannot run Windows Server 2008 R2 Domain Controllers, you can install the Active Directory Management Gateway Service. Installing this will allow you to run the same Active Directory web service that runs on Windows Server 2008 R2 DC's. You can download the Active Directory Management Gateway Service here. Make sure you read the instructions carefully, there are several hotfixes that need to be applied depending on the version of Windows you are running. You can install the Active Directory Management Gateway Service on DC's running the following operating systems:

  • Windows Server 2003 R2 with Service Pack 2
  • Windows Server 2003 SP2
  • Windows Server 2008
  • Windows Server 2008 SP2

Note: You can also use AD PowerShell to manage AD LDS instances on Windows Server 2008 R2. If you plan on using AD LDS, Active Directory web services will be installed with the AD LDS role, the AD PowerShell module will also be installed during this process. The ADWS service will be enabled when your LDS instance is created.

Once you've got Active Directory web services up and running on your Domain Controller(s), you'll notice you now have an ADWS service as shown here:

At this point, you should be ready to install the AD PowerShell module. You can run AD PowerShell on all versions of Windows Server 2008 R2 (except the Web Edition) and on Windows 7.

Installing the Active Directory Module for Windows PowerShell on 2008 R2 member servers

You can install the Active Directory Module on Windows 2008 R2 member servers by adding the RSAT-AD-PowerShell feature using the Server Manager. I usually use the ServerManager module to do this because it is quick and easy. To install the feature using the ServerManager module, launch PowerShell and run the following commands:

Import-Module ServerManager
Add-WindowsFeature RSAT-AD-PowerShell

Remember, this only needs to be done on Windows Server 2008 R2 member servers. The RSAT-AD-PowerShell feature will be added to 2008 R2 DC's during the DCPromo process.

Installing the Remote Server Administration Tools (RSAT) feature on Windows 7

In order to install the Active Directory Module for Windows PowerShell you need to download the RSAT tools for Windows 7here. Once this is installed you are still not finished, you need to enable the Active Directory module. Navigate to Control Panel > Programs and Features > Turn Windows Features On or Off and select Active Directory Module for Windows PowerShell as show here:

Once you have Active Directory web services running on at least one domain controller and the AD PowerShell module is installed, you are ready to run the AD PowerShell module. You can do this in one of two ways. First, you can access the "Active Directory Module for Windows PowerShell" shortcut in Administrative Tools as shown here:

Right click the shortcut and select "Run as administrator" in order to start PowerShell with elevated permissions.

You can also simply import the AD PowerShell module in your existing PowerShell session. Just use the Import-Module ActiveDirectory command:

Import-Module ActiveDirectory

That's all that needs to be done to get up and running...I will get into using the AD PowerShell cmldets in future posts so keep an eye out for that.

PowerShell working with paths that contain wildcards - square brackets

Use the –LiteralPath parameter available to suppress all pattern matching behavior.  But Rename-Item cmdlet does not have the –LiteralPath parameter.  A workaround is to use Move-Item cmdlet to rename files.

See Windows PowerShell in Action, page 309 – 312, and http://sandbox.manning.com/thread.jspa?messageID=62599

Use WinSCP to Transfer Files in vCSA 6.7

This is a quick update on my previous post “ Use WinSCP to Transfer Files in vCSA 6.5 ”. When I try the same SFTP server setting in vCSA 6.7...