We help IT Professionals succeed at work.

Powershell code to explain

jskfan
jskfan used Ask the Experts™
on
Powershell code to explain
I have this powershell code below. I need someone to explain the text in bold put below the Code.

## csv file with machines and user names to process:
$csv = 'c:\Scripts\Computers.csv'
## Absolute local file path on the clients:
$filePath = 'C:\test.txt'

$pattern = '(-username\s+)\S+'
Import-Csv -Path $csv | ForEach-Object {
	$computer = $_.ComputerName.Trim()
	$newUser = $_.NewUsername.Trim()
	$fileUNC = "\\$($computer)\$($filePath.Replace(':', '$'))"
	Write-Host "Processing $($computer), new user '$($newUser)' ..." -NoNewline
	Try {
		$content = Get-Content -Path $fileUNC -ErrorAction Stop
		$content -replace $pattern, "`$1$($newUser)" | Set-Content -Path $fileUNC -Force -ErrorAction Stop
		Write-Host " OK" -ForegroundColor Green
	} Catch {
		Write-Host " FAILED: $($_.Exception.Message)" -ForegroundColor Red
	}
}

Open in new window





$pattern = '(-username\s+)\S+'
Import-Csv -Path $csv | ForEach-Object {
      $computer = $_.ComputerName.Trim()
      $newUser = $_.NewUsername.Trim()
      $fileUNC = "\\$($computer)\$($filePath.Replace(':', '$'))"
      Write-Host "Processing $($computer), new user '$($newUser)' ..." -NoNewline
      Try {
            $content = Get-Content -Path $fileUNC -ErrorAction Stop
            $content -replace $pattern, "`$1$($newUser)" | Set-Content -Path $fileUNC -Force -ErrorAction Stop
            Write-Host " OK" -ForegroundColor Green
      } Catch {
            Write-Host " FAILED: $($_.Exception.Message)" -ForegroundColor Red
      }
}
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
$pattern = '(-username\s+)\S+'
Will match the literal "-username", followed by at least one white-space (\s+), followed by at least one non-white-space.
The match found inside the brackets (the first capturing group) will be available as $1 in the replace later.

$computer = $_.ComputerName.Trim(), $newUser = $_.NewUsername.Trim()
The $_ is the loop variable of the csv being imported, that is, the current row being processed.
ComputerName and NewUsername are the column names in the csv, and can be accessed as properties of the loop variable.
The Trim() removes potential whitespace at the beginning or end of the strings

"\\$($computer)\$($filePath.Replace(':', '$'))"
Builds a UNC from the local path; in the local path, the : will be replaced with a $ to access the administrative share.

Write-Host "Processing $($computer), new user '$($newUser)' ..." -NoNewline
Eye candy - should be pretty straight forward what's happening. Just a status message.
The $() are subexpressions; technically, they're not required, because they're "simple" variables and will be identified and expanded as variables by PowerShell, but they are required as soon as object properties are access, so I prefer to always use subexpressions when embedding variables inside a string.

$content -replace $pattern, "`$1$($newUser)" | Set-Content -Path $fileUNC -Force -ErrorAction Stop
The main part of the script. This will replace any matches of the pattern formerly discussed with the matches in the capturing group 1 ($1), which will be "-username " (including trailing spaces), plus the new username from the csv.
So if the file contained
foo bar -username jdoe
The pattern will match the highlighted string. The cursive part will be in capturing group 1 (the $1).
The highlighted part will be replaced with the cursive partial match "-username ", plus the new name from the csv.

Write-Host " FAILED: $($_.Exception.Message)" -ForegroundColor Red
Eye candy again.
Here, the subexpression $() around $_.Exception.Message is actually required, otherwise PowerShell would stop parsing the variable at the first dot, instead of evaluating the properties.

Author

Commented:
$pattern = '(-username\s+)\S+'

so
 lowercase s+ : means at least one white space
uppercase S+ : mean at least one non-white space
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Not quite. "s+" means at least one literal "s". S+ (in .NET) is the same, because .NET RegEx are by default case insensitive.
The backslash before the s or S is vital! The character class "white-space" is \s, the character class "non-white-space" is \S.
The "+" is the (optional) quantifier indicating how often the previous group or character is repeated.

Author

Commented:
this expression between single quotes : '$($newUser)'
will it give error if there were no single quotes ?
meaning of  :   -NoNewline
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
will it give error if there were no single quotes ?
No; the single quotes are just that: literal single quotes in the output to indicate where the user name starts and ends.

-NoNewline means that Write-Host will write the string and then keep the cursor at the end of the same line (so that the second line indicating success or error can continue on the same line).

Author

Commented:
oBdA

Almost there:

      $fileUNC = "\\$($computer)\$($filePath.Replace(':', '$'))"

when accessing the admin share C$ manually we do this:
\\Computername\C$

so how do this :       $fileUNC = "\\$($computer)\$($filePath.Replace(':', '$'))"
Maps to this:
\\Computername\C$

I know the   $fileUNC  is just a variable  , $computer : will have the computer name  from the file. but what about this $ sign in bold: \\$($computer)


this one, I cannot interprete it:

$($filePath.Replace(':', '$'))"
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
That's not a stand-alone $ - the $(...) indicates a subexpression, as explained above in Write-Host "Processing $($computer), new user '$($newUser)' ..." -NoNewline. It tells PS to evaluate the command inside the brackets before doing anything else.
In the case of $($computer), it's just the content of the $computer variable.
In the case of $($filePath.Replace(':', '$')), the subexpression is $filePath.Replace(':', '$'), which replaces the : in the path to the file with a $.

Author

Commented:
Thank you for your help.

Author

Commented:
Thank you