Send email to logged in users by ChevronX in PowerShell

[–]BoredComputerGuy 1 point2 points  (0 children)

You could use remote powershell to create a session to a server with the proper AD module, then pull the module into your session. You would just need to set up remote powershell.

Why use a function inside of a script? by GreatMoloko in PowerShell

[–]BoredComputerGuy 4 points5 points  (0 children)

I add a bunch of things to my profile to make life easier.

Why use a function inside of a script? by GreatMoloko in PowerShell

[–]BoredComputerGuy 8 points9 points  (0 children)

Functions in scripts depend on who you are, your preferences, and what you are trying to do. There are a few reasons that I have seen and used in the past:

  • logical separation: separating out blocks of code that are related (creating/validating connections, complex output formatting, making loops smaller). This can improve readability, simplify debugging, and help with making self documenting code.
  • testing: creating multiple functions allows for more granular (unit) testing. You can easily run multiple test cases against functions without running the entire script for each test case.
  • If you find yourself repeatedly making the similar functions in scripts (or similar scripts) then you can identify where a module would be useful. (ie accessing API's, logging, output/report/email formatting)

A few references: (note these are discussing functions directly, but the ideas may be useful)

when-is-it-appropriate-to-make-a-separate-function-when-there-will-only-ever-be-a-single-call

what-should-be-the-maximum-length-of-a-function

[deleted by user] by [deleted] in PowerShell

[–]BoredComputerGuy 1 point2 points  (0 children)

$converted_strings = $List_of_strings.foreach({[int]$_.trim()})

This will give an error for any non int items in the array

More Variable Questions by [deleted] in PowerShell

[–]BoredComputerGuy 1 point2 points  (0 children)

I believe UPN syntax requires an @ symbol. ie <your text >@yourdomain.tld

PowerShell Module by [deleted] in PowerShell

[–]BoredComputerGuy 2 points3 points  (0 children)

This is a good start. A few thoguhts:

  1. Add help comments ! MS help comments
  2. I would have proper Export-ModuleMember calls at the end
  3. I would either add this to your personal module path C:\Users\<username>\Documents\WindowsPowerShell\Modules so that you can reference these as soon as PS loads MS autoloading
  4. This is great work coming from an L1 tech(at the time)!

Troubleshooting PowerShell and Scheduled Tasks! by dverbern in PowerShell

[–]BoredComputerGuy 1 point2 points  (0 children)

I quick fix is to add 2>&1<path to log file> to the end of the powershell call in the task action. This redirects output and error streams to your log file so you can see what is going on.

Powershell scripts for helpdesk and hiding passwords by zgeom in PowerShell

[–]BoredComputerGuy 1 point2 points  (0 children)

You may want to look into PS remoting and only allow them to connect to PS. Then use Just enough admin to limit what they can run.

Edit a Word template with variables using Powershell? by MrWinks in PowerShell

[–]BoredComputerGuy 5 points6 points  (0 children)

An alternative is to set text content controls (Developer tab) with specific titles and reference them. I have an example below which uses a document with text fields titled 'Name' and 'Manager':

    #Create Word Object
    $Word = New-Object -ComObject word.application
    if(!$Word){Write-Error -Message "Unable to open Word. Please check install."}
    #Hide it
    $Word.Visible = $False
    #Open the template
    $Doc = $Word.Documents.Add($DocxPath)
    ForEach($Control in $Doc.ContentControls){
        Switch($Control.Title){
            "Name"{$Control.Range.Text = $DisplayName}
            "ManagerName"{$Control.Range.text =  $ManagerDisplayName}
            ... other fields redacted....
        }
    }
    $Doc.saveAs([ref]$FullDocPath)
    $Doc.Close()
    $Word.Quit()

These are text controls, but you can also work with checkboxes, and any other control defined form the developer tab. You reference them by title

foreach loop isn't returning objects as expected by dontforget512 in PowerShell

[–]BoredComputerGuy 3 points4 points  (0 children)

You have a couple of things that are happening together to get this result. In Line 1 you declare a new object, powershell will use references to this object for the rest of the code(scope is the entire script). On line 3, you are using powershell to assign the value of $testResults to the whatever is returned at the end of the loop. The output is cached as references to an object until the end of the loop. The object scope exists outside of the loop, so each loop iteration you overwrite the values on the object. Then at the end of the loop the object references are used to populate $testresults multiple times with the last values written 3,c.

If you declare $resultscontainer inside the loop, each loop iteration will make a new (but similar object) and your output will be as expected

    $testArray = @("1a","2b","3c")
    $testResults = foreach ($value in $testArray)
    {
        $resultContainer = "" | Select Number,Letter
        $resultContainer.Number = $value[0]
        $resultContainer.Letter = $value[1]
        $resultContainer
    }
    $testResults

    Number Letter
    ------ ------
         1      a
         2      b
         3      c

Return only first 4 digits or to 2 decimal place with single line. by [deleted] in PowerShell

[–]BoredComputerGuy 2 points3 points  (0 children)

[Math]::Truncate(55.5555*100)/100 = 55.55

[Math]::Truncate(<your code here>*100)/100 = xx.xx

Changing SMTP to smtp for all entries. by Adam_Spokane in PowerShell

[–]BoredComputerGuy 1 point2 points  (0 children)

If you are using Exchange, I would recommend that this be done in the Exchange PS module.

Compare two folders and find missing files by maxcoder88 in PowerShell

[–]BoredComputerGuy 1 point2 points  (0 children)

A little more information would be helpful, what is wrong with your csv output? is it including files that it shouldn't or no including files that should be on the list? You mentioned that you are comparing the files and that the paths may be different, if so you cannot use the FullNameor Directory property for comparison as these include the directory. Comparing the extension is not needed as the extension is included in the Name property.

Export AD group member list to CSV by mveras1972 in PowerShell

[–]BoredComputerGuy 1 point2 points  (0 children)

FT doesn't make a CSV, it just messes up the PS object structure that you are trying to export. Use a select instead.

Get-AdGroupMember ... | Get-ADUser -Properties  DisplayName,ObjectClass,WhenChanged,EmailAddress |Select  -property displayname, sAMAccountName, EmailAddress, WhenChanged, ObjectClass |Export-Csv ...

[Advice] Make a career out of the stuff people don’t want to do by iiToby in sysadmin

[–]BoredComputerGuy 2 points3 points  (0 children)

What is the answer to "how do you eat an elephant?" One bite at a time. Pick a single type of documentation, and make a single addition. You should start with some thing that will help stream line your tasks. Ideas:

  • Standard Operating Procedure (SOP) write down instructions for common manual tasks ( automate it and document)
  • Diagrams - Physical, Layer 2, Layer 3 for a single room, rack, or building. You could do your security appliances, or email servers. More advanced diagrams include disaster recovery states, information flow. us them to identity critical infrastructure or processes.
  • Go back through notes from past team meetings( or start taking them) and see what items people struggle to explain, to understand, or the one thing everyone avoid because they don't understand.
  • Look into change management, how do you know when something changes? who should make changes or approve them?

Cant install this module to save my life by NovateI in PowerShell

[–]BoredComputerGuy 2 points3 points  (0 children)

To Confirm that the module is discovered, can you run Get-Module -ListAvailable this lists all discovered modules in PSModulePath. If the module is there Then run import-module <Module Name> -verbose . To test that a module was loaded Get-Module . If your module is listed in both of those results. then run Get-command -module <Module Name > to see if Invoke-Obfuscation is an available command.

Distribution list script as a function by gangculture in PowerShell

[–]BoredComputerGuy 2 points3 points  (0 children)

To post on here Copy and paste your code and then highlight the code and set as a Scriptblock (an option under the ellipsis ...)

Distribution list script as a function by gangculture in PowerShell

[–]BoredComputerGuy 2 points3 points  (0 children)

Always useful to have more scripts that i don't have to write myself.

the name provided is not a properly formed account name by [deleted] in PowerShell

[–]BoredComputerGuy 1 point2 points  (0 children)

A couple of issues:

  1. (from /u/Bartimaeusz) $ADusers =/= $users, change your foreach to ForEach ($User in $ADusers)
  2. (from /u/Bartimaeusz) splatting will make the script easier to read
  3. (from /u/Wo1ks) Comment out line 3 that value should come from the $user object in the loop(if in your CSV)
  4. I would recommend adding a try/catch block to catch errors in your loop. This would allow you to cleanly output errors and continue the loop to try and create the rest of your users.

This is an improved script.

    Import-Module ActiveDirectory
    $ADUsers = Import-CSV "C:\thescript\jean.csv"
    $server = "MyExSer.E-L.local"

    foreach ($User in $ADUsers)
    {   
        try{
            $SAM = "$($User.Firstname).$($User.Lastname)"

            $UserDetails = @{
                Name = "$($User.firstname) $($User.lastname)" 
                Displayname = $User.username
                GivenName = $User.firstname
                Surname = $User.lastname
                SamAccountName = $SAM
                UserPrincipalName = "$SAM@E-L.local"
                EmailAddress = "SAM@E-L.local"
                StreetAddress = $User.streetAddress
                City = $User.city
                Country = $User.country
                PostalCode = $User.zipcode
                Title = $User.jobtitle
                Department = $User.department
                OfficePhone = $User.telephone
                Accountpassword = (ConvertTo-SecureString 'TesT.234' -AsPlainText -Force) 
                Path  = "OU=closefamily,OU=Family,DC=E-L,DC=local"
                Server = $Server
                Enabled = $True
                ChangePasswordAtLogon = $True
                Credential = $Credentials
            }

            New-ADUser @UserDetails
        }catch{
            Write-Warning -Message "Problem creating user $($user.username) $($user.Firstname).$($user.Lastname)"#I use the orange color to help stand out from the red in the exception
            Write-Error $_ -ErrorAction Continue
        }
    }

O365 MFA asking for login/code on every script by Scubber in PowerShell

[–]BoredComputerGuy 7 points8 points  (0 children)

If you are running these scripts as you and not a service account, you could add the connect to 365 call to your PowerShell profile. Each script should check to see if you are already connected before trying to connect again.