PowerShell - Win2k8 - Script - powershell

I'm making a script to add some user from a csv to my AD and it doesn't work for some reason that i can't find out ^^'.
I'm using the file ADlog to see where my code goes or not and it goes in the "else (Woot?)" so maybe it can't access to my AD thx to a mistake in my code or ... dunno
#connection to the Active Directory
$objOU=[ADSI]"LDAP://localhost:389/DC=maho,DC=lan"
if($objOU.Children -ne $null) {
# import data from the csv file
$dataSource=import-csv ("\user.csv")
ForEach($dataRecord in $dataSource) {
$ou=$dataRecord.service
#checking the existance of the UO
if(($objOU.Children | where {$_.Path -match "OU=$ou"}) -eq $null){
#if it doesn't, we creat it
$objOU = $objOU.create("organizationalUnit", "ou="+$ou)
$objOU.SetInfo()
"UO not there" | Add-Content C:\ADlog.txt
}
else {
#if it does exist we point on it to creat the new user
$objOU = $objOU.Children.Find("OU=$ou")
"WOOT ?" | Add-Content C:\ADlog.txt
}
$SamAccountName=$dataRecord.login
$GivenName=$dataRecord.fname
$sn=$dataRecord.lname
$cn=$GivenName + " " + $sn
$displayName=$cn
$description=$dataRecord.description
$UserPrincipalname=$SamAccountName +"#"+$DNS_DomainName
#we create the obj user in the AD
$objUser=$objOU.Create("User","CN="+$cn)
$objUser.Put("SamAccountName",$SamAccountName)
$objUser.Put("UserPrincipalName",$UserPrincipalName)
$objUser.Put("DisplayName",$Displayname)
$objUser.Put("Description",$description)
$objUser.Put("GivenName",$GivenName)
$objUser.Put("sn",$sn)
$objUser.SetInfo()
#$objUser.setPassword("")
#empty to make the user choise his own passwd
#we activate the account
$objUser.psbase.InvokeSet("AccountDisabled",$false)
$objUser.SetInfo()
#we check that the acc is created
if(($objOU.Children | where {$_.Path -match "CN=$cn"}) -ne $null) {
"User : "+$UserPrincipalName+" Ok" | Add-Content C:\ADlog.txt
}
$objOU=[ADSI]"LDAP://localhost:389/DC=maho,DC=lan"
}
Write-Host "Sucess!"
#Delete the reg key
Remove-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run"-Name "Unattend*"
}
else {
"Failure" | Add-Content C:\ADlog.txt
}

Check out This Scripting Guy article, pretty straight forward
http://blogs.technet.com/b/heyscriptingguy/archive/2011/12/22/use-powershell-to-read-a-csv-file-and-create-active-directory-user-accounts.aspx

Related

Powershell Script using for each to export only Valid AD Users to csv and suppress Users it cannot find in AD

Good day all, I'm trying to write a script that will check if a User is valid and export the results to a .csv file. I'm using the "for each" and erroraction -silentlycontinue cmdlet to check a list of Users from a .csv file and then verify on the Microsoft Teams admin center if that is a Valid User.
The problem I'm having is if I add the "$errorActionpreference" cmdlet which suppresses errors (or Users Not Found on Screen) the results in the CSV File are empty, If I remove the $errorAction cmdlet (hashed out in the script below), then it works fine by exporting the valid Users BUT it spits out a lot of errors on the screen.
The scripts just need to suppress error messages for invalid Users, Move to the next User in the csv file, and finally export the results of the valid Users to another csv file.
$path = Read-Host -Prompt "`nEnter the path of .csv file:"
if (Test-Path -Path $path) { break }
Write-Host "Wrong file or path specified. Please enter the correct
path to file!" -ForegroundColor Red
Write-Host "File has been located in the path specified!" -
ForegroundColor Green
$CsvFilePath = Import-CSV -Path $path
# $ErrorActionPreference = "silentlycontinue"
$results = foreach ($Users in $CsvFilePath) {
$User = $Users.UserPrincipalName
Get-CsOnlineUser $User | Select-Object UserPri*, LineURI,
TeamsUpgradeE*,IsSipEnabled, Enterprise*,
#{l="AssignedPlan";e={$_.AssignedPlan
- join "; "}}, #{l="FeatureTypes";e={$_.FeatureTypes -join ";
"}}
}
# $ErrorActionPreference = "silentlycontinue
#Export Results: Prompt for Path, If file does not exist, create it!#
$resultspathfilelocation = Read-Host -Prompt "`nEnter file path
to export results of
the Post Checks: "
$FileName = "$resultspathfilelocation"
if(Get-Item -Path $FileName -ErrorAction Ignore){
Write-Host "File found in directory specified!"
}
else{
New-Item -Verbose $FileName -ItemType File
}
$results | Export-Csv $resultspathfilelocation
Instead of trying to ignore the errors, why not just handle them properly?
$Results = foreach ($Users in $CsvFilePath) {
Try {
$User = $Users.UserPrincipalName
$ThisUser = Get-CsOnlineUser $User -ErrorAction Stop
# Output as custom object
[pscustomobject]#{UPN = $User
TeamsUpgradeEffectiveMode = $ThisUser.TeamsUpgradeEffectiveMode
IsSipEnabled = $ThisUser.IsSipEnabled
AssignedPlan = ($ThisUser.AssignedPlan -join "; ")
FeatureTypes = ($ThisUser.FeatureTypes -join "; ")
Error = ''}
}
Catch {
# User not found or error, output object with blank fields except for error
[pscustomobject]#{UPN = $User
TeamsUpgradeEffectiveMode = ''
IsSipEnabled = ''
AssignedPlan = ''
FeatureTypes = ''
Error = $_.Exception.Message}
}
}

Export and filter 365 Users Mailboxes Size Results Sort by Total Size form High to Low

Continuing from my previous question:
I have Powershell script that exports Mailboxes Size Results to CSV file.
The Results contain "Total Size" column that display results, and follow by Name.
However, i want the exported CSV file to filter and display only "greater then" 25GB Results, from high to low.
Like that:
Now, there is the traditional way to use excel to filter to Numbers in the CSV results- after the powershell export.
But, i want to have it in the CSV file, so i do not have to do it over and over again.
Here's the script:
Param
(
[Parameter(Mandatory = $false)]
[switch]$MFA,
[switch]$SharedMBOnly,
[switch]$UserMBOnly,
[string]$MBNamesFile,
[string]$UserName,
[string]$Password
)
Function Get_MailboxSize
{
$Stats=Get-MailboxStatistics -Identity $UPN
$IsArchieved=$Stats.IsArchiveMailbox
$ItemCount=$Stats.ItemCount
$TotalItemSize=$Stats.TotalItemSize
$TotalItemSizeinBytes= $TotalItemSize –replace “(.*\()|,| [a-z]*\)”, “”
$TotalSize=$stats.TotalItemSize.value -replace "\(.*",""
$DeletedItemCount=$Stats.DeletedItemCount
$TotalDeletedItemSize=$Stats.TotalDeletedItemSize
#Export result to csv
$Result=#{'Display Name'=$DisplayName;'User Principal Name'=$upn;'Mailbox Type'=$MailboxType;'Primary SMTP Address'=$PrimarySMTPAddress;'IsArchieved'=$IsArchieved;'Item Count'=$ItemCount;'Total Size'=$TotalSize;'Total Size (Bytes)'=$TotalItemSizeinBytes;'Deleted Item Count'=$DeletedItemCount;'Deleted Item Size'=$TotalDeletedItemSize;'Issue Warning Quota'=$IssueWarningQuota;'Prohibit Send Quota'=$ProhibitSendQuota;'Prohibit send Receive Quota'=$ProhibitSendReceiveQuota}
$Results= New-Object PSObject -Property $Result
$Results | Select-Object 'Display Name','User Principal Name','Mailbox Type','Primary SMTP Address','Item Count',#{Name = 'Total Size'; Expression = {($_."Total Size").Split(" ")[0]}},#{Name = 'Unit'; Expression = {($_."Total Size").Split(" ")[1]}},'Total Size (Bytes)','IsArchieved','Deleted Item Count','Deleted Item Size','Issue Warning Quota','Prohibit Send Quota','Prohibit Send Receive Quota' | Export-Csv -Path $ExportCSV -Notype -Append
}
Function main()
{
#Check for EXO v2 module inatallation
$Module = Get-Module ExchangeOnlineManagement -ListAvailable
if($Module.count -eq 0)
{
Write-Host Exchange Online PowerShell V2 module is not available -ForegroundColor yellow
$Confirm= Read-Host Are you sure you want to install module? [Y] Yes [N] No
if($Confirm -match "[yY]")
{
Write-host "Installing Exchange Online PowerShell module"
Install-Module ExchangeOnlineManagement -Repository PSGallery -AllowClobber -Force
}
else
{
Write-Host EXO V2 module is required to connect Exchange Online.Please install module using Install-Module ExchangeOnlineManagement cmdlet.
Exit
}
}
#Connect Exchange Online with MFA
if($MFA.IsPresent)
{
Connect-ExchangeOnline
}
#Authentication using non-MFA
else
{
#Storing credential in script for scheduling purpose/ Passing credential as parameter
if(($UserName -ne "") -and ($Password -ne ""))
{
$SecuredPassword = ConvertTo-SecureString -AsPlainText $Password -Force
$Credential = New-Object System.Management.Automation.PSCredential $UserName,$SecuredPassword
}
else
{
$Credential=Get-Credential -Credential $null
}
Connect-ExchangeOnline -Credential $Credential
}
#Output file declaration
$ExportCSV=".\MailboxSizeReport_$((Get-Date -format yyyy-MMM-dd-ddd` hh-mm` tt).ToString()).csv"
$Result=""
$Results=#()
$MBCount=0
$PrintedMBCount=0
Write-Host Generating mailbox size report...
#Check for input file
if([string]$MBNamesFile -ne "")
{
#We have an input file, read it into memory
$Mailboxes=#()
$Mailboxes=Import-Csv -Header "MBIdentity" $MBNamesFile
foreach($item in $Mailboxes)
{
$MBDetails=Get-Mailbox -Identity $item.MBIdentity
$UPN=$MBDetails.UserPrincipalName
$MailboxType=$MBDetails.RecipientTypeDetails
$DisplayName=$MBDetails.DisplayName
$PrimarySMTPAddress=$MBDetails.PrimarySMTPAddress
$IssueWarningQuota=$MBDetails.IssueWarningQuota -replace "\(.*",""
$ProhibitSendQuota=$MBDetails.ProhibitSendQuota -replace "\(.*",""
$ProhibitSendReceiveQuota=$MBDetails.ProhibitSendReceiveQuota -replace "\(.*",""
$MBCount++
Write-Progress -Activity "`n Processed mailbox count: $MBCount "`n" Currently Processing: $DisplayName"
Get_MailboxSize
$PrintedMBCount++
}
}
#Get all mailboxes from Office 365
else
{
Get-Mailbox -ResultSize Unlimited | foreach {
$UPN=$_.UserPrincipalName
$Mailboxtype=$_.RecipientTypeDetails
$DisplayName=$_.DisplayName
$PrimarySMTPAddress=$_.PrimarySMTPAddress
$IssueWarningQuota=$_.IssueWarningQuota -replace "\(.*",""
$ProhibitSendQuota=$_.ProhibitSendQuota -replace "\(.*",""
$ProhibitSendReceiveQuota=$_.ProhibitSendReceiveQuota -replace "\(.*",""
$MBCount++
Write-Progress -Activity "`n Processed mailbox count: $MBCount "`n" Currently Processing: $DisplayName"
if($SharedMBOnly.IsPresent -and ($Mailboxtype -ne "SharedMailbox"))
{
return
}
if($UserMBOnly.IsPresent -and ($MailboxType -ne "UserMailbox"))
{
return
}
Get_MailboxSize
$PrintedMBCount++
}
}
#Open output file after execution
If($PrintedMBCount -eq 0)
{
Write-Host No mailbox found
}
else
{
Write-Host `nThe output file contains $PrintedMBCount mailboxes.
if((Test-Path -Path $ExportCSV) -eq "True")
{
Write-Host `nThe Output file available in $ExportCSV -ForegroundColor Green
$Prompt = New-Object -ComObject wscript.shell
$UserInput = $Prompt.popup("Do you want to open output file?",`
0,"Open Output File",4)
If ($UserInput -eq 6)
{
Invoke-Item "$ExportCSV"
}
}
}
#Disconnect Exchange Online session
Disconnect-ExchangeOnline -Confirm:$false | Out-Null
}
. main
How can i achieve that?
It's a bit of an unfortunate scenario, but if you're outputting the results to the file on each iteration, you have 2 options:
At the end of the script, read the output file, filter the >25gb mailboxes, sort the objects, then output again
Instead of writing the user mailbox to the file each user, save to a
variable instead. At the end, filter, sort, then export to file
Without going too far into the code...
Option 1
Might be simplest, as you're working off two input sizes already. After you've retrieved all mailboxes and gotten all statistics, read the exported csv file and filter + sort the data. Then, export the info back to the file, overwriting. Something like
$tempImport = Import-CSV $exportCSV | Where-Object {($_.'Total Size' -ge 25) -and ($_.Unit -eq "GB")} | Sort-Object 'Total Size' -descending
$tempImport | Export-CSV $exportCSV -noTypeInformation
PowerShell may not like overwriting a file read-in on the same command, hence the saving as a temp variable.
Option 2
Create a live variable storing all mailbox data, and write the information at the end of the script instead of opening the file to append data each iteration. Then, at the end of the script, filter and sort before exporting.
$global:largeMailboxes = #() # definition to allow reading through all functions
Then, instead of exporting to CSV each time, add the result to the above variable
$tvar = $null
$tvar = $Results | Select-Object 'Display Name','User Principal Name','Mailbox Type','Primary SMTP Address','Item Count',#{Name = 'Total Size'; Expression = {($_."Total Size").Split(" ")[0]}},#{Name = 'Unit'; Expression = {($_."Total Size").Split(" ")[1]}},'Total Size (Bytes)','IsArchieved','Deleted Item Count','Deleted Item Size','Issue Warning Quota','Prohibit Send Quota','Prohibit Send Receive Quota'
$global:largeMailboxes += $tvar
#
# Alternatively, only add the mailbox if it's larger than 25GB, to avoid adding objects you don't care about
if ($TotalItemSizeinBytes -ge 26843545600) # This is 25 GB, better to make a variable called $minSize or such to store this in, in case you want to change it later.
{
# Above code to add to global variable
}
Once all mailboxes have been added, sort the object
$global:largeMailboxes = $global:largeMailboxes | Sort-Object 'Total Size' -descending
Then export as needed
$global:largeMailboxes | Export-CSV $exportCSV -NoTypeInformation

Powershell - Make a menu out of text file

In my adventure trying to learn Powershell, I am working on an extension on a script I have made. The idea is to make script there by adding ".iso" files into a folder. It will use that content in a menu so that I later can use it to select an iso file for a WM in Hyper-V
This is my version of how it will get the content in the first place
Get-ChildItem -Path C:\iso/*.iso -Name > C:\iso/nummer-temp.txt
Add-Content -Path C:\iso/nummer.txt ""
Get-Content -Path C:\iso/nummer-temp.txt | Add-Content -Path C:\iso/nummer.txt
When this code is run it will send an output like what i want. But my question is how do I use this output in a menu?
This is the best practice way to do so in powershell :
#lets say your .txt files gets this list after running get-content
$my_isos = $('win7.iso','win8.iso','win10.iso')
$user_choice = $my_isos | Out-GridView -Title 'Select the ISO File you want' -PassThru
#waiting till you choose the item you want from the grid view
Write-Host "$user_choice is going to be the VM"
I wouldn't try to make it with System.windows.forms utilities as i mentioned in my comment, unless you want to present the form more "good looking".
If you don't want to go for a graphical menu, but rather a console menu, you could use this function below:
function Show-Menu {
Param(
[Parameter(Position=0, Mandatory=$True)]
[string[]]$MenuItems,
[string] $Title
)
$header = $null
if (![string]::IsNullOrWhiteSpace($Title)) {
$len = [math]::Max(($MenuItems | Measure-Object -Maximum -Property Length).Maximum, $Title.Length)
$header = '{0}{1}{2}' -f $Title, [Environment]::NewLine, ('-' * $len)
}
# possible choices: digits 1 to 9, characters A to Z
$choices = (49..57) + (65..90) | ForEach-Object { [char]$_ }
$i = 0
$items = ($MenuItems | ForEach-Object { '{0} {1}' -f $choices[$i++], $_ }) -join [Environment]::NewLine
# display the menu and return the chosen option
while ($true) {
cls
if ($header) { Write-Host $header -ForegroundColor Yellow }
Write-Host $items
Write-Host
$answer = (Read-Host -Prompt 'Please make your choice').ToUpper()
$index = $choices.IndexOf($answer[0])
if ($index -ge 0 -and $index -lt $MenuItems.Count) {
return $MenuItems[$index]
}
else {
Write-Warning "Invalid choice.. Please try again."
Start-Sleep -Seconds 2
}
}
}
Having that in place, you call it like:
# get a list if iso files (file names for the menu and full path names for later handling)
$isoFiles = Get-ChildItem -Path 'D:\IsoFiles' -Filter '*.iso' -File | Select-Object Name, FullName
$selected = Show-Menu -MenuItems $isoFiles.Name -Title 'Please select the ISO file to use'
# get the full path name for the chosen file from the $isoFiles array
$isoToUse = ($isoFiles | Where-Object { $_.Name -eq $selected }).FullName
Write-Host "`r`nYou have selected file '$isoToUse'"
Example:
Please select the ISO file to use
---------------------------------
1 Win10.iso
2 Win7.iso
3 Win8.iso
Please make your choice: 3
You have selected file 'D:\IsoFiles\Win8.iso'

Powershell error with else statement

I am trying to write a script that will remove old queues from users HKLM (will eventually delete from HKCU by mounting ntuser.dat but I am not there yet).
The problem I am having is that I am only iterating through one sid under SOFTWARE\Microsoft\Windows NT\CurrentVersion\Print\Providers\Client Side Rendering Print Provider\ and I get the following error message:
The term 'else' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is corr
ect and try again.
Has anyone ran into this issue before?
#defining my object that will be used throughout the script. Will be used to log everything
$objQueueData=[pscustomobject]#{
computername=""
computerstatus=""
Registrystatus=""
SID=""
Does_It_Have_2003_Queues=""
User_SID_Status=""
user=""
UNC_2003_Queues=""
}
#$QueueDataCollection=[pscustomobject]#{
#queuecollection=$QueueData
#}
#reading the list of workstations
Get-Content "P:\PowerShell\jm\DeletePrintQueues\Workstations.txt" | ForEach-Object{
$strComputerName = $_
#check if the workstation is up
IF (Test-Connection -ComputerName $strComputerName -count 2 -quiet)
{
#$objUser= Get-ChildItem c:\users
#$strUserName=$objUser.Name
$objQueueData.computername=$strComputerName
$objQueueData.computerstatus="Machine is up"
DeleteHklm $strComputerName
}
else
{
#We are here because the computer could not be reached
Write-Host "Machine down" $strComputerName
$objQueueData.computername =$strComputerName
$objQueueData.computerstatus = "Machine Down"
$objQueueData.Registrystatus ="Machine Down"
$objQueueData.SID = "Machine Down"
$objQueueData.Does_It_Have_2003_Queues="Machine Down"
$objQueueData.User_SID_Status="Machine Down"
$objQueueData.user="Machine Down"
$objQueueData.UNC_2003_Queues="Machine Down"
$objQueueData | Export-Csv P:\powershell\jm\results2.csv -NoTypeInformation -Append
}
}
function DeleteHKLM {
param ([string]$computername)
try{
If($strHklm = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine',$strcomputername ))
{
#executes when it can open HKLM
$objqueuedata.RegistryStatus = "Was able to open the registry"
#set the path of the registry
$PrinterRegKey = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Print\\Providers\\Client Side Rendering Print Provider'
#$PrinterRegKey
$regPrinterRef = $strHklm.OpenSubKey($PrinterRegKey)
#debug
Write-Host "regprinterref is: "$regPrinterRef
}
If($regPrinterRef)
{
#This executes if there are Printers present in the registry
#region Loop thru all child keys. These contain the calculable UNC paths to 2003
$regPrinterRef.GetSubKeyNames() | ForEach-Object{
#debug
Write-Host "The sid is: " $_
#concatinating to get to the connections key
#$PrinterRegKey
$strPrinterpath =$PrinterRegKey+"\\"+ $_ + "\\Printers\\Connections"
#debug
Write-Host "The printer keys for SID are located in: "
$strPrinterPath
if ($strPrinterpath -notlike "*servers*")
{
#this value is the sid
# $_ will give us the sids. Here I am storing the SIDs into strUserSID to use later on
$strUserSID = $_
#debug
# $strUserSID
# The logic below will convert SID to username
#pass the SID to the secrity principal SID being struserSID
$objSID = New-Object System.Security.Principal.SecurityIdentifier("$strUserSID")
#using a try catch to filter out deleted SIDs, otherwise powershell will throw an error saying it is null
Try{
$strUser = $objSID.Translate( [System.Security.Principal.NTAccount]).Value
$objQueueData.User_SID_Status ="Valid SID"
$strUser
}
Catch{
#$strUserID = $objSID.Value
$objQueueData.User_SID_Status ="Invalid SID"
$objQueueData.User = "Invalid SID"
$objQueueData.Does_it_Have_2003_Queues ="Invalid SID"
$objQueueData.UNC_2003_Queues = "Invalid SID"
$objQueueData | Export-Csv P:\powershell\jm\results1.csv -NoTypeInformation -Append
#exit
}
$regPrinterDetails = $Strhklm.OpenSubKey($strPrinterPath)
$regPrinterDetails.GetSubKeyNames() |ForEach-Object{
#looping through each key at the connections level to search for the 2003 print server names
if($_ -like "*sarspprt2*")
{
$objQueueData.Does_It_Have_2003_Queues = "Yes"
#this value is the printer if it exists
# $_ will give us the printers. Here I am storing the printers into strUserPrinters to user later on
$strUserPrinters = $_
Write-Host "struserprinters value is " $_
#$strUserPrinters
$blnHasOldQueues = $true
#The code below is to build the printer UNC to make it more legible
$intPrinterLength= $strUserPrinters.Length
$strPrintServer= $strUserPrinters.Substring(2,10)
#Doing the -13 because we have to limit the length of the substring statement to the length minus the starting poistion of the substring
$strPrinterShareName =$strUserPrinters.Substring(13,$intPrinterLength-13)
$strPrintUNC = "\\"+$strPrintServer+"\"+$strPrinterShareName
$objQueueData.UNC_2003_Queues = $strPrintUNC
$objQueueData.User = $strUser
$objQueueData | Export-Csv P:\powershell\jm\results.csv -NoTypeInformation -Append
$strkeytodelete=$strPrinterPath+"\\"+$_
$strkeytodelete
#delete 2003 Key
Remove-Item -Path '$strkeytodelete' -Recurse
}
elseif($_ -notlike "*sarspprt2*")
{
#Write-host "No 2003 Queues Detected"
#Write-host "no 2003 Queues detected" $strUserSID,$strUser,$strPrintUNC
$objQueueData.User = $strUser
$objQueueData.Does_it_Have_2003_Queues = "No 2003 Queues Detected for this user or vsarspprt* queue"
$objQueueData.UNC_2003_Queues = "No 2003 Queues Detected for this user or vsarspprt* queue"
$objQueueData | Export-Csv P:\powershell\jm\results.csv -NoTypeInformation -Append
}
# Write-Host $strServer $blnHasOldQueues $strUserSID $strUserPrinters
}
}
}
else
{
#Write-Host "No Printers in the Registry"
$objQueueData.computername=""
$objQueueData.computerstatus=""
$objQueueData.Registrystatus=""
$objQueueData.SID=""
$objQueueData.Does_It_Have_2003_Queues=""
$objQueueData.User_SID_Status=""
$objQueueData.user=""
$objQueueData.UNC_2003_Queues=""
}
}
}
catch{
# Write-Host "cant read registry"
$_.Exception.Message
}
}
You have an extra curly brace on line 153. If you move that to after line 165 it should work, although I can't test it right now. I got in the habit of systematically collapsing my if-else statements to ensure that they all match up with eachother.

Powershell output formatting?

I have a script that scans for a specific folder in users AppData folder. If it finds the folder, it then returns the path to a txt file. So we can see the computer name and username where it was found.
I would like to be able to format the what is actually written to the text file, so it removes everything from the path except the Computer and User names.
Script:
foreach($computer in $computers){
$BetterNet = "\\$computer\c$\users\*\AppData\Local\Google\Chrome\User Data\Default\Extensions\gjknjjomckknofjidppipffbpoekiipm"
Get-ChildItem $BetterNet | ForEach-Object {
$count++
$betternetCount++
write-host BetterNet found on: $computer
Add-Content "\\SERVERNAME\PowershellScans\$date\$time\BetterNet.txt" $_`n
write-host
}
}
The text files contain information like this
\\computer-11-1004S10\c$\users\turtle\AppData\Local\Google\Chrome\User Data\Default\Extensions\gjknjjomckknofjidppipffbpoekiipm
\\computer-1004-24S\c$\users\camel\AppData\Local\Google\Chrome\User Data\Default\Extensions\gjknjjomckknofjidppipffbpoekiipm
\\computer-1004-23S\c$\users\rabbit\AppData\Local\Google\Chrome\User Data\Default\Extensions\gjknjjomckknofjidppipffbpoekiipm
If you have each line in a form of the string $string_containing_path then it is easy to split using split method and then add index(1) and (4) that you need:
$afterSplit = $string_containing_path.Split('\')
$stringThatYouNeed = $afterSplit[1] + " " + $afterSplit[4]
You can also use simple script that will fix your current logs:
$path_in = "C:\temp\list.txt"
$path_out= "C:\temp\output.txt"
$reader = [System.IO.File]::OpenText($path_in)
try {
while($true){
$line = $reader.ReadLine()
if ($line -eq $null) { break }
$line_after_split_method = $line.Split('\')
$stringToOutput = $line_after_split_method[1] + " " + $line_after_split_method[4] + "`r`n"
add-content $path_out $stringToOutput
}
add-content $path_out "End"
}
finally {
$reader.Close()
}
If you split your loop into two foreach loops, one for computer and user directory it would be easier to output the name of the user directory.
$output = foreach($computer in $computers){
$UserDirectories = Get-ChildItem "\\$computer\c$\users\" -Directory
foreach ($Directory in $UserDirectories) {
$BetterNet = Get-ChildItem (Join-Path $Directory.fullname "\AppData\Local\Google\Chrome\User Data\Default\Extensions\gjknjjomckknofjidppipffbpoekiipm")
Add-Content "\\SERVERNAME\PowershellScans\$date\$time\BetterNet.txt" "$computer $($Directory.name)`r`n"
write-host BetterNet found on: $computer
$BetterNet
}
}
$output.count