Jump to content

[Powershell] Does anyone have a script which .....


Recommended Posts

Posted

Just thought it would be useful to have a general thread for people to share Powershell scripts to save people having to redo all the work.

 

I don't have any script needs at the minute but I've got a stack of scripts that might be useful to people and usually more free time than I know what to do with so filling it with Powershell probably isn't a bad thing.

  • 2 weeks later...
Posted
Just thought it would be useful to have a general thread for people to share Powershell scripts to save people having to redo all the work.

 

I don't have any script needs at the minute but I've got a stack of scripts that might be useful to people and usually more free time than I know what to do with so filling it with Powershell probably isn't a bad thing.

 

Isn't there a Microsoft Scripts library online?

 

Here it is: https://technet.microsoft.com/en-us/scriptcenter/bb410849.aspx

 

I tend to look here when I need something (which is not that often).

 

Gareth

Posted
True but if there isn't anything there that you need then someone else in the community may have made something close enough that you can adapt it.

 

I wasn't criticising the idea, just saying that there is a site out there as well. Maybe someone could set up a repository for community scripts.

 

GJE

Posted
What scripts do you have? I am starting to work on some scripts.

 

Many thanks

 

Currently I've got a bunch of AD scripts (Creating one or many users, full Intake process including folder/OU creation, end of year process, removing one or many users), some for O365, SCCM pre-stage computers and checking status of SCEP clients, DPM reporting and a handy GUI for running scripts with parameter input.

  • 1 month later...
Posted

As requested by @Garacesh here is the script I've got for creating VMs. Need to update the help for it but I'll get to that next week. Some minor things about the script:

 

1) It can accept input from the pipeline, so you can do things like Import-CSV -Path "C:\folder\file.csv" | .\Create-VM.ps1 and it will create all the VMs for you (see CSV format at the bottom for what I use currently)

2) Invoke-Expression is bad and I should feel bad, but it works for setting the RAM size and VHD size and I feel a little better about it by using the ValidateRange option for the parameter so you can only enter numbers in that range.

3) I'm wanting to add in some better validation of the $OS option using ValidateScript but I haven't played around with that yet and I wanted to keep it reasonably simple for a simple test environment, if I ever get a SAN/NAS set up to host my VMs and ISOs then I'll rework that but it's easy enough to change.

 

 

<#
.Synopsis
  Script for creating VMs and configuring their settings.
.DESCRIPTION
  Script will create VMs and configure the settings for it, including create VHD, mount the VHD and ISO (if needed).
  Script takes input from the pipeline such as from Import-Csv. 
.EXAMPLE
  Example of how to use this cmdlet
.EXAMPLE
  Another example of how to use this cmdlet
#>
[CmdletBinding()]
[Alias()]
[OutputType([int])]
Param
(
   # Name of VM to create
   [Parameter(Mandatory=$true,
               ValueFromPipelineByPropertyName,
               Position=0)]
   [string]$Name,
   # Startup Memory for VM
   [Parameter(ValueFromPipelineByPropertyName)]
   [validaterange(512,3096)]
   $Memory = 512,
   #Generation of VM to create
   [Parameter(ValueFromPipelineByPropertyName)]
   [ValidateSet(1,2)]
   [int]$Generation = 2,
   #Switch to connect VM
   [Parameter(ValueFromPipelineByPropertyName)]
   [string]$Switch = "HyperVSwitch",
   #VHD Size
   [parameter(ValueFromPipelineByPropertyName)]
   [validateRange(10,40)]
   $VHDSize = 15,
   #OS iso to mount
   [parameter(ValueFromPipelineByPropertyName)]
   [string]$OS
)


Process
{
   If (Get-VM -Name $Name -ErrorAction SilentlyContinue)
   {
       Write-Error "Can't create VM as one already exists with the name $Name"
   }
   else
   {
       #Try creating the VM using basic settings
       try 
       {
           $Memory = Invoke-Expression -command "$($Memory)MB"
           New-VM -Name $Name -MemoryStartupBytes $Memory  -BootDevice CD -NoVHD -SwitchName $Switch -Path "C:\ProgramData\Microsoft\Windows\Hyper-V" -Generation $Generation


       }
       catch [system.Exception]
       {
           Write-Error "Error creating VM due to $($_.Exception.Message)"
           exit
       }


       #Try to set up VHD
       try
       {
           $VHDPath = "c:\Users\Public\Documents\Hyper-v\Virtual Hard Disks\$name.vhdx"
           if ((Test-Path $VHDPath) -ne $true)
           {
               $VHDSize = Invoke-Expression -Command "$($VHDSize)GB"
               New-VHD -Path $VHDPath -SizeBytes $VHDSize -Dynamic
           }
           if ($Generation -eq 1)
           {
               add-VMHardDiskDrive -VMName $Name -Path "C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks\$Name.vhdx"
           }
           else
           {
               add-VMHardDiskDrive -VMName $Name -Path "C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks\$Name.vhdx"
           }
       
       }
       catch [system.exception]
       {
           Write-Error "Error creating VHD or assigning it to VM due to $($_.Exception.Message)"
           exit
       }
       #try to set up DVD drive for iso
       try
       {
           if ($OS -eq "Win8")
           {
               Set-VMDvdDrive -VMName $Name -Path "C:\Users\Halbarad\Desktop\Windows 8.1\win8.ISO"
           }
           elseif ($OS -eq "Server")
           {
               Set
               -VMDvdDrive -VMName $Name -Path "C:\Users\Halbarad\Desktop\Server 2012 R2\Server.ISO"
           }
           else
           {
               if ($OS -match "*.iso")
               {
                   Add-VMDvdDrive -VMName $Name -Path $OS
               }
               else
               {
                   Throw "$OS not a valid ISO file."
               }
           }
       }
       catch [system.exception]
       {
           Write-Error "Error adding VM DVD Drive for VM $name caused by $($_.Exception.Message)"
           exit
       }
   }
}


 

And the csv format I'm using:

 

name,memory,generation,switch,vhdsize,os
dc01,1024,2,hypervswitch,25,Server
fs01,1024,2,hypervswitch,25,Server
win8,1024,2,hypervswitch,15,Win8

  • Thanks 1
Posted
Anyone have a powershell script which allows granting full access to a folder (and subfolders) for everyone...and won't fail because it needs admin privilege, (i am running as admin). If you're not comfortable posting in public feel free to inbox me.
Posted (edited)
Anyone have a powershell script which allows granting full access to a folder (and subfolders) for everyone...and won't fail because it needs admin privilege, (i am running as admin). If you're not comfortable posting in public feel free to inbox me.

 

Grab the NTFS Security Module and it makes that super easy.

 

Edit: Code would look something like this:

 

Add-Ace -Path "\\someserver\somefolder" -Account Everyone -AccessRights FullControl
Get-childitem -path "\\someserver\somefolder" -Recurse | Enable-Inheritance

Edited by halbaradkenafin
  • Thanks 1
Posted
Grab the NTFS Security Module and it makes that super easy.

Ooh, cool - I hate CACLS/iCACLS/XCACLS/WitchCackles.

 

Another job for next week - migrate permissions scripts to Powershell! :(

  • 2 weeks later...
Posted

I put together a script a while ago to find out which users had logged in to a PC by checking the Event Log, it worked reasonably well but I wasn't entirely happy with it. "Luckily" someone asked if I had a script for the same reason and I figured I'd update it and clean it up. So here it is for anyone to use, I've called it Get-LoginSuccess and that's what it's called in the examples but call it whatever you want really. The help does need a little updating for what the script does now but it's still reasonably accurate.

 

 

It can query a single PC (must be switched on) and either look for all instances of a single user logging in or every user who logged in and when within a set time frame. It can also query your DCs for every computer a user has logged in to but this takes a while depending on number of DCs and number of clients/users as it trawls through the event logs, I ran it earlier and it took about 1.5 hours to report back based on 3 DCs and about 500 users and devices. You'll need the AD module available on the machine to query DCs as it uses Get-ADDomainController to find all them in the environment but can be reworked to a static list. Event logs on the DCs may not go back as far as you'd like so it's probably better to query a specific machine (or two or whatever) if you only need to check a few or over a long time period (more than a few days).

 

 

 

 

<#
.Synopsis
  Checks the event log of the domain controllers and report any successful login attempts
for a particular user and which computers they logged in to. Needs to run as Administrator to access the log.
.DESCRIPTION
  Checks the event log of the domain controllers and report any successful login attempts
for a particular user and which computers they logged in to.Uses Get-WinEvent and filtering on ID 4624
between the dates provided. Then collates the Eventlogs into XML, which is searched for the username and
that is stored along with the IP and computer name (from DNS lookup) and output to the user.


This script can take quite a while to run due to the number of event log entries that are logged on each server,
testing was showing times of 10+ minutes to query each server when looking at the results for just one day. 
Further investigation required to attempt to streamline the process to reduce this time.


.EXAMPLE
  Get-LoginSuccess -Username "test.user" -StartDate "10/01/2015" -EndDate "11/01/2015"


  This will get all login successes by user test.user on the dates 10/01/2015 and 11/01/2015. If the second date is in the future then
  it will only get them from any days that have actually happened.


.EXAMPLE
  Get-LoginSuccess -Username "test.user"


  This will get all login successes by user test.user for the current day.


.EXAMPLE
  Get-LoginSuccess -ComputerName "test-computer"


  This will get all login successes by each user who logged into test-computer for the current day.


.EXAMPLE
  Get-LoginSuccess -ComputerName "test-computer" -StartDate "10/01/2015"


  This will get all login successes by each user who logged into test-computer from the start date till today.


.EXAMPLE
  Get-LoginSuccess -ComputerName "test-computer" -StartDate "10/01/2015" -EndDate "15/01/2015"


  This will get all login successes by each user who logged into test-computer from the start date till the specified end date.


.EXAMPLE
  Get-LoginSuccess -ComputerName "test-computer" -Username "test.user" -StartDate "10/01/2015" -EndDate "15/01/2015"


  This will get all login successes by specified userlogging into test.computer from the start date till the specified end date.


#>
[cmdletbinding()]
param 
(
   [Parameter(Mandatory=$True,HelpMessage='Computer to check',ValueFromPipelineByPropertyName,
       position=0,ParameterSetName="Computer")]
   [Alias('Computer Name','Computer','Device','Device Name')]
   [string]$ComputerName = "wsh-b103-td2",
[Parameter(Mandatory=$false,HelpMessage="Username to search for",
       ValueFromPipelineByPropertyName,Position=0,ParameterSetName='IndividualUser')]
   [Parameter(HelpMessage="Username to search for",
       ValueFromPipelineByPropertyName,Position=1,ParameterSetName='Computer')]
   [alias('user','name')]
   [string]$Username,
[string]$StartDate = $(Get-Date -format dd/MM/yyyy),
[string]$EndDate
)
Process 
{
   if ($EndDate -eq '' -or $EndDate -eq $StartDate) 
   {
    $EndDate = Get-Date -date ((Get-date $StartDate).AddDays(1)) -format dd/MM/yyyy
   }
   else
   {
       $EndDate = Get-Date -Date $EndDate -Format dd/MM/yyyy
   }
   
   if ($EndDate -lt $StartDate) 
   {
    Write-error "End date ($EndDate) must be after start date ($StartDate). Please try again with the correct dates."
       Exit
   }
   
   $EventOutput =@()
   $EventLog = @()


   Switch ($PSCmdlet.ParameterSetName)
   {
       "IndividualUser" {
           $Controllers = Get-ADDomainController -filter *
           Foreach ($Controller in $Controllers)
           {
               Write-Verbose "Getting event data for $StartDate until $EndDate from $($Controller.Name)"
               $EventLog += Get-WinEvent -FilterHashTable @{logname='security';id=4624;StartTime=$StartDate;EndTime=$EndDate} -ComputerName "$($Controller.Name)"
               Foreach ($Event in $EventLog)
               {
                   $SingleEventOutput = New-Object -TypeName PSObject -Property @{'Username'='';'Computer'='';'Date'="$($Event.TimeCreated)"}
                   write-Verbose "Converting to XML"
                   $EventLogXML = [xml]$Event.ToXML()
                   Write-Verbose "Parsing XML and finding required entries"
                   $ValidEntry = 0
                foreach ($Property in $EventLogXML.Event.EventData.Data) 
                   {
	                if ($Property.Name -eq "TargetUserName" -and $Property.'#text' -eq $Username) 
                       {
		                $SingleEventOutput.Username = $Property.'#text'
                           $ValidEntry++
	                }
	                elseif ($Property.Name -eq "IpAddress" -and $Property.'#text' -notmatch "::ffff:" -and $Property.'#text' -notmatch "" -and $ValidEntry -eq 1) 
                       {
                           Write-Verbose "Getting computer name from IP Address"
		                $PCName = nslookup (($Property.'#text').substring(7))
		                $SingleEventOutput = (($PCName[3]).substring(9))
                           $ValidEntry++
	                }
                }
                   if ($ValidEntry -eq 2) {
                       $EventOutput += $SingleEventOutput
                   }
               }
           }
       }


       "Computer" {
           Write-Verbose "Getting event data for $StartDate until $EndDate"
           $EventLog += Get-WinEvent -FilterHashTable @{logname='security';id=4624;StartTime=$StartDate;EndTime=$EndDate} -ComputerName $ComputerName
           Foreach ($Event in $EventLog)
           {
               $SingleEventOutput = New-Object -TypeName PSObject -Property @{'Username'='';'Computer'="$Computername";'Date'="$($Event.TimeCreated)"}
               write-Verbose "Converting to XML"
               $EventLogXML = [xml]$Event.ToXML()
               Write-Verbose "Parsing XML and finding required entries"
               $ValidEntry = 0
            foreach ($Property in $EventLogXML.Event.EventData.Data) 
               {
	            if ($Username -ne '')
                   {
                       if ($Property.Name -eq "TargetUserName" -and $Property.'#text' -eq $Username)
                       {
		                $SingleEventOutput.Username = $Property.'#text'
                           $ValidEntry++
	                }
                   }
                   else
                   {
                       if ($Property.Name -eq "TargetUserName" -and ($Property.'#text').Trim() -notmatch "$ComputerName" -and $Property.'#text' -ne "SYSTEM" -and $Property.'#text' -ne $env:USERNAME) 
                       {
		                $SingleEventOutput.Username = ($Property.'#text').Trim()
                           $ValidEntry++
	                }
                   }
	            
            }
               if ($ValidEntry -eq 1) {
                   $EventOutput += $SingleEventOutput
               }
           }
       }
   }


   Write-Output $EventOutput
}

Posted
For the future, Sort out a login script that echos the username time an computer name to a text file in a file share

 

That's the easy way to handle it (we've also got impero which logs all this as well) but I was mostly doing it for the experience of playing around with event logs and because someone asked for something like this, which I assumed meant they didn't have anything like the text files or other logging in place.

Posted
Only some basic ones here.. I have a script that reads new AD users from a CSV and creates home folders and sorts out permissions. If anyone wants it I'll dig it out.
Posted (edited)
Just thought it would be useful to have a general thread for people to share Powershell scripts to save people having to redo all the work.

 

I don't have any script needs at the minute but I've got a stack of scripts that might be useful to people and usually more free time than I know what to do with so filling it with Powershell probably isn't a bad thing.

 

 

There's no doubt that PowerShell is a wonderfull tool and is used in a wide range of products (Veeam, Exchange, vSphere, HyperV, AD, XenDesktop) there are common commands that seem to work on each product.

 

The one thing that puts me off about using code from online is that there seems to be little commenting (if any) about what each line of code does, I am not talking about simple variables here i.e. $ad = "blah" or if/else statements. As a newcomer to scripting with PowerShell this makes learning complex code challenging.

Edited by Davit2005
Posted
There's no doubt that PowerShell is a wonderfull tool and is used in a wide range of products (Veeam, Exchange, vSphere, HyperV, AD, XenDesktop) there are common commands that seem to work on each product.

 

The one thing that puts me off about using code from online is that there seems to be little commenting (if any) about what each line of code does, I am not talking about simple variables here i.e. $ad = "blah" or if/else statements. As a newcomer to scripting with PowerShell this makes learning complex code challenging.

 

This is something I need to work on in my scripts but luckily Powershell is pretty good in terms of sensible naming of cmdlets and parameters so it's fairly readable. If the script writer has been good with variable names and coupled with good help comments at the start of the script then it can be almost like pseudo code in its readability.

 

When learning how a new script does something I break it down as much as possible, "this block does x through using that cmdlet and this logicc" etc. If I don't understand why there is that result or logic test then I'll use the ISE to run individual lines of code and examine the output. I'd even go so far as to say that the ISE should be everyone's default Powershell environment, even for running cmdlets that you know exactly what they do as it gets you into the habit of using it and intellisense is awesome.

  • Thanks 1
Posted

Here's an example of grabbing some student data from a CMIS database, not heavily documented but it should be reasonably easy to understand what is going on.

 

Another which uses the output from a DB extract simmilar to the previous and creates exchange mailing groups.

 

Finally, a script to Create Users, Add to Groups, Move to OU, Create Folder, Set ACL, Create Share.

Posted (edited)
I put together a script a while ago to find out which users had logged in to a PC by checking the Event Log, it worked reasonably well but I wasn't entirely happy with it. "Luckily" someone asked if I had a script for the same reason and I figured I'd update it and clean it up. So here it is for anyone to use, I've called it Get-LoginSuccess and that's what it's called in the examples but call it whatever you want really. The help does need a little updating for what the script does now but it's still reasonably accurate.

 

 

It can query a single PC (must be switched on) and either look for all instances of a single user logging in or every user who logged in and when within a set time frame. It can also query your DCs for every computer a user has logged in to but this takes a while depending on number of DCs and number of clients/users as it trawls through the event logs, I ran it earlier and it took about 1.5 hours to report back based on 3 DCs and about 500 users and devices. You'll need the AD module available on the machine to query DCs as it uses Get-ADDomainController to find all them in the environment but can be reworked to a static list. Event logs on the DCs may not go back as far as you'd like so it's probably better to query a specific machine (or two or whatever) if you only need to check a few or over a long time period (more than a few days).

 

 

 

 

<#
.Synopsis
  Checks the event log of the domain controllers and report any successful login attempts
for a particular user and which computers they logged in to. Needs to run as Administrator to access the log.
.DESCRIPTION
  Checks the event log of the domain controllers and report any successful login attempts
for a particular user and which computers they logged in to.Uses Get-WinEvent and filtering on ID 4624
between the dates provided. Then collates the Eventlogs into XML, which is searched for the username and
that is stored along with the IP and computer name (from DNS lookup) and output to the user.


This script can take quite a while to run due to the number of event log entries that are logged on each server,
testing was showing times of 10+ minutes to query each server when looking at the results for just one day. 
Further investigation required to attempt to streamline the process to reduce this time.


.EXAMPLE
  Get-LoginSuccess -Username "test.user" -StartDate "10/01/2015" -EndDate "11/01/2015"


  This will get all login successes by user test.user on the dates 10/01/2015 and 11/01/2015. If the second date is in the future then
  it will only get them from any days that have actually happened.


.EXAMPLE
  Get-LoginSuccess -Username "test.user"


  This will get all login successes by user test.user for the current day.


.EXAMPLE
  Get-LoginSuccess -ComputerName "test-computer"


  This will get all login successes by each user who logged into test-computer for the current day.


.EXAMPLE
  Get-LoginSuccess -ComputerName "test-computer" -StartDate "10/01/2015"


  This will get all login successes by each user who logged into test-computer from the start date till today.


.EXAMPLE
  Get-LoginSuccess -ComputerName "test-computer" -StartDate "10/01/2015" -EndDate "15/01/2015"


  This will get all login successes by each user who logged into test-computer from the start date till the specified end date.


.EXAMPLE
  Get-LoginSuccess -ComputerName "test-computer" -Username "test.user" -StartDate "10/01/2015" -EndDate "15/01/2015"


  This will get all login successes by specified userlogging into test.computer from the start date till the specified end date.


#>
[cmdletbinding()]
param 
(
   [Parameter(Mandatory=$True,HelpMessage='Computer to check',ValueFromPipelineByPropertyName,
       position=0,ParameterSetName="Computer")]
   [Alias('Computer Name','Computer','Device','Device Name')]
   [string]$ComputerName = "wsh-b103-td2",
   [Parameter(Mandatory=$false,HelpMessage="Username to search for",
       ValueFromPipelineByPropertyName,Position=0,ParameterSetName='IndividualUser')]
   [Parameter(HelpMessage="Username to search for",
       ValueFromPipelineByPropertyName,Position=1,ParameterSetName='Computer')]
   [alias('user','name')]
   [string]$Username,
   [string]$StartDate = $(Get-Date -format dd/MM/yyyy),
   [string]$EndDate
)
Process 
{
   if ($EndDate -eq '' -or $EndDate -eq $StartDate) 
   {
       $EndDate = Get-Date -date ((Get-date $StartDate).AddDays(1)) -format dd/MM/yyyy
   }
   else
   {
       $EndDate = Get-Date -Date $EndDate -Format dd/MM/yyyy
   }
   
   if ($EndDate -lt $StartDate) 
   {
       Write-error "End date ($EndDate) must be after start date ($StartDate). Please try again with the correct dates."
       Exit
   }
   
   $EventOutput =@()

   Switch ($PSCmdlet.ParameterSetName)
   {
       "IndividualUser" {
           $Controllers = Get-ADDomainController -filter *
           Foreach ($Controller in $Controllers)
           {
               Write-Verbose "Getting event data for $StartDate until $EndDate from $($Controller.Name)"
               $EventLog = Get-WinEvent -FilterHashTable @{logname='security';id=4624;StartTime=$StartDate;EndTime=$EndDate} -ComputerName "$($Controller.Name)"
               Foreach ($Event in $EventLog)
               {
                   $SingleEventOutput = New-Object -TypeName PSObject -Property @{'Username'='';'Computer'='';'Date'="$($Event.TimeCreated)"}
                   write-Verbose "Converting to XML"
                   $EventLogXML = [xml]$Event.ToXML()
                   Write-Verbose "Parsing XML and finding required entries"
                   $ValidEntry = 0
                   foreach ($Property in $EventLogXML.Event.EventData.Data) 
                   {
                       if ($Property.Name -eq "TargetUserName" -and $Property.'#text' -eq $Username) 
                       {
                           $SingleEventOutput.Username = $Property.'#text'
                           $ValidEntry++
                       }
                       elseif ($Property.Name -eq "IpAddress" -and $Property.'#text' -notmatch "::ffff:" -and $Property.'#text' -notmatch "" -and $ValidEntry -eq 1) 
                       {
                           Write-Verbose "Getting computer name from IP Address"
                           $PCName = nslookup ($Property.'#text')
                           $SingleEventOutput = (($PCName[3]).substring(9))
                           $ValidEntry++
                       }
                   }
                   if ($ValidEntry -eq 2) {
                       $EventOutput += $SingleEventOutput
                   }
               }
           }
       }


       "Computer" {
           Write-Verbose "Getting event data for $StartDate until $EndDate"
           $EventLog = Get-WinEvent -FilterHashTable @{logname='security';id=4624;StartTime=$StartDate;EndTime=$EndDate} -ComputerName $ComputerName
           Foreach ($Event in $EventLog)
           {
               $SingleEventOutput = New-Object -TypeName PSObject -Property @{'Username'='';'Computer'="$Computername";'Date'="$($Event.TimeCreated)"}
               write-Verbose "Converting to XML"
               $EventLogXML = [xml]$Event.ToXML()
               Write-Verbose "Parsing XML and finding required entries"
               $ValidEntry = 0
               foreach ($Property in $EventLogXML.Event.EventData.Data) 
               {
                   if ($Username -ne '')
                   {
                       if ($Property.Name -eq "TargetUserName" -and $Property.'#text' -eq $Username)
                       {
                           $SingleEventOutput.Username = $Property.'#text'
                           $ValidEntry++
                       }
                   }
                   else
                   {
                       if ($Property.Name -eq "TargetUserName" -and ($Property.'#text').Trim() -notmatch "$ComputerName" -and $Property.'#text' -ne "SYSTEM" -and $Property.'#text' -ne $env:USERNAME) 
                       {
                           $SingleEventOutput.Username = ($Property.'#text').Trim()
                           $ValidEntry++
                       }
                   }
                   
               }
               if ($ValidEntry -eq 1) {
                   $EventOutput += $SingleEventOutput
               }
           }
       }
   }


   Write-Output $EventOutput
}

 

 

Apparently I can't edit this post but I've updated the code a little, made a "small" mistake when collating the event logs from each server and it turns out that I was actually adding the logs for each server onto the logs from the previous ones and then looping over the whole collection again, which in my case meant I was looping over the first DC logs 3 times, the second 2 times and the final DC 1 time. Unsurprisingly this was a little inefficient and I've corrected it now.

Edited by halbaradkenafin
Posted
This script is what I run nightly to email any staff whose password is due to expire within 5 days.

 

You get an email saying how many days are left, and explaining how to change it in school or from home.

 

Peter

 

 

Just a quick question, what does the section below do just so I can get an understanding??

 

 

 

param (

[CmdletBinding()]

 

[parameter(Mandatory=$true)][int]$NumOfDays,

[switch]$All,

[switch]$AllUsers,

[switch]$ShowMaxAge,

[switch]$ShowPrecedence,

[switch]$ShowLastPasswordReset,

[switch]$ShowDaysSinceChange,

[switch]$ShowDaysTillChange

)

Posted

I should have said, I take no claim for writing it - the core of the class was stolen from elsewhere.

 

I just wrote the bits at the bottom that make use of the functions defined above.

 

In answer to your question, that is defining the parameters that the function accepts.

 

When you use auto-complete or intellisense, it will show you those as possible values you can provide to the routine.

 

Peter

  • Thanks 1
Posted
cmdletbinding() is pretty awesome when writing scripts, it's pretty good to be able to add Write-Verbose and put some useful text in for when you want to get more in-depth output from your scripts especially as it then applies the -verbose parameter to any cmdlets you run inside your script which will accept them.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now



×
×
  • Create New...