Hello all,
I’m a novice at PowerShell but none the less I have been asked to create a PS script based on the merit that I’m the only one with any experience using it at my office; albeit limited.
The Request is to create a reboot script based on last reboot reported.
The users at my company rarely reboot their pc’s. Since we use SCCM to deploy; in some cases a reboot is required. Now I know what you’re going to say. “Why not just have SCCM reboot after deploying” Well yes I could do that, however we are a global Law AM 100 firm whose attorney’s work round the clock and basically charge by the minute. I can’t tell you what kind of trouble we would be in if the machine rebooted whilst still having a document open and not saved.
The requirements of the request.
1. Query active directory user workstations for machines that have not rebooted in x days.
2. Check for open documents (Word, Excel, PowerPoint, Outlook) if Open then
a. Allow for opt out message timer. (User could opt out if they are actually working on the machine during the scheduled maintenance.)
b. Save as “Closed for reboot maintenance date” on the desktop
Here is what I have so far.
Using François-Xavier Cat’s Get-DomainComputer function from here I am able to query my domains workstations based on OU location. Example: OU=computers,OU=test,DC=somedomain,DC=com
I then added my own function called Set-reboot which uses foreach to obtain the last reboot using get-ciminstance stores it in a variable. I run $computers it lists out all the computers in the specific ou. If I run Set-reboot it errors out. With the following error. Finally
get-CimInstance : WS-Management could not connect to the specified destination: (@{Name=NYLD8300-512C6M}:5985).
At C:\Users\orivera\Documents\Set-Reboot.ps1:217 char:6
+ {get-CimInstance -ClassName win32_operatingsystem -ComputerName $computer | ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (root\cimv2:win32_operatingsystem:String) [Get-CimInstance], CimException
+ FullyQualifiedErrorId : HRESULT 0x80072ee5,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstanceCommand
+ PSComputerName : @{Name=NYLD8300-512C6M}
Finally the sripts.
The following is the query portion I have added the unfinished word check portion (which I planned to add once I had a working query) at the bottom for reference . Any help, guidance would greatly be appreciated. Hopefully I didn’t overwhelm you with my long winded message I just wanted to provide as much detail as I could.
QUERY
# Varibles
."C:\Scripts\Functions\Get-DomainComputer.ps1"
$sourcedn='OU=computers,OU=test,DC=somedomain,DC=com'
$rebootage= 14
$computers=Get-DomainComputer-DomainDN$sourcedn-SizeLimit 10000 -ComputerName *ld8300*-Credentialdomain\username | selectname
# Credit for the following Get-Domaincomputer function goes to François-Xavier Cat
FunctionGet-DomainComputer {
<#
.SYNOPSIS
The Get-DomainComputer function allows you to get information from an Active Directory Computer object using ADSI.
.DESCRIPTION
The Get-DomainComputer function allows you to get information from an Active Directory Computer object using ADSI.
You can specify: how many result you want to see, which credentials to use and/or which domain to query.
.PARAMETER ComputerName
Specifies the name(s) of the Computer(s) to query
.PARAMETER SizeLimit
Specifies the number of objects to output. Default is 100.
.PARAMETER DomainDN
Specifies the path of the Domain to query.
Examples: "FX.LAB"
"DC=FX,DC=LAB"
"Ldap://FX.LAB"
"Ldap://DC=FX,DC=LAB"
.PARAMETER Credential
Specifies the alternate credentials to use.
.EXAMPLE
Get-DomainComputer
This will show all the computers in the current domain
.EXAMPLE
Get-DomainComputer -ComputerName "Workstation001"
This will query information for the computer Workstation001.
.EXAMPLE
Get-DomainComputer -ComputerName "Workstation001","Workstation002"
This will query information for the computers Workstation001 and Workstation002.
.EXAMPLE
Get-Content -Path c:\WorkstationsList.txt | Get-DomainComputer
This will query information for all the workstations listed inside the WorkstationsList.txt file.
.EXAMPLE
Get-DomainComputer -ComputerName "Workstation0*" -SizeLimit 10 -Verbose
This will query information for computers starting with 'Workstation0', but only show 10 results max.
The Verbose parameter allow you to track the progression of the script.
.EXAMPLE
Get-DomainComputer -ComputerName "Workstation0*" -SizeLimit 10 -Verbose -DomainDN "DC=FX,DC=LAB" -Credential (Get-Credential -Credential FX\Administrator)
This will query information for computers starting with 'Workstation0' from the domain FX.LAB with the account FX\Administrator.
Only show 10 results max and the Verbose parameter allows you to track the progression of the script.
.NOTES
NAME:FUNCT-AD-COMPUTER-Get-DomainComputer.ps1
AUTHOR: Francois-Xavier CAT
DATE:2013/10/26
EMAIL: info@lazywinadmin.com
WWW: www.lazywinadmin.com
TWITTER:@lazywinadm
VERSION HISTORY:
1.0 2013.10.26
Initial Version
#>
[CmdletBinding()]
PARAM(
[Parameter(ValueFromPipelineByPropertyName=$true,
ValueFromPipeline=$true)]
[Alias("Computer")]
[String[]]$ComputerName,
[Alias("ResultLimit","Limit")]
[int]$SizeLimit='1000',
[Parameter(ValueFromPipelineByPropertyName=$true)]
[Alias("Domain")]
[String]$DomainDN=$(([adsisearcher]"").Searchroot.path),
[Alias("RunAs")]
[System.Management.Automation.Credential()]
$Credential= [System.Management.Automation.PSCredential]::Empty
)#PARAM
PROCESS{
IF ($ComputerName){
Write-Verbose-Message"One or more ComputerName specified"
FOREACH ($itemin$ComputerName){
TRY{
# Building the basic search object with some parameters
Write-Verbose-Message"COMPUTERNAME: $item"
$Searcher=New-Object-TypeNameSystem.DirectoryServices.DirectorySearcher-ErrorAction'Stop'-ErrorVariableErrProcessNewObjectSearcher
$Searcher.Filter ="(&(objectCategory=Computer)(name=$item))"
$Searcher.SizeLimit =$SizeLimit
$Searcher.SearchRoot =$DomainDN
# Specify a different domain to query
IF ($PSBoundParameters['DomainDN']){
IF ($DomainDN-notlike"LDAP://*") {$DomainDN="LDAP://$DomainDN"}#IF
Write-Verbose-Message"Different Domain specified: $DomainDN"
$Searcher.SearchRoot =$DomainDN}#IF ($PSBoundParameters['DomainDN'])
# Alternate Credentials
IF ($PSBoundParameters['Credential']) {
Write-Verbose-Message"Different Credential specified: $($Credential.UserName)"
$Domain=New-Object-TypeNameSystem.DirectoryServices.DirectoryEntry-ArgumentList$DomainDN,$($Credential.UserName),$($Credential.GetNetworkCredential().password) -ErrorAction 'Stop' -ErrorVariable ErrProcessNewObjectCred
$Searcher.SearchRoot =$Domain}#IF ($PSBoundParameters['Credential'])
# Querying the Active Directory
Write-Verbose-Message"Starting the ADSI Search..."
FOREACH ($Computerin $($Searcher.FindAll())){
Write-Verbose-Message"$($Computer.properties.name)"
New-Object-TypeNamePSObject-ErrorAction'Continue'-ErrorVariableErrProcessNewObjectOutput-Property @{
"Name"= $($Computer.properties.name)
"DNShostName" = $($Computer.properties.dnshostname)
"Description"= $($Computer.properties.description)
"OperatingSystem"=$($Computer.Properties.operatingsystem)
"WhenCreated"= $($Computer.properties.whencreated)
"DistinguishedName"= $($Computer.properties.distinguishedname)}#New-Object
}#FOREACH $Computer
Write-Verbose-Message"ADSI Search completed"
}#TRY
CATCH{
Write-Warning-Message ('{0}: {1}'-f$item, $_.Exception.Message)
IF ($ErrProcessNewObjectSearcher){Write-Warning-Message"PROCESS BLOCK - Error during the creation of the searcher object"}
IF ($ErrProcessNewObjectCred){Write-Warning-Message"PROCESS BLOCK - Error during the creation of the alternate credential object"}
IF ($ErrProcessNewObjectOutput){Write-Warning-Message"PROCESS BLOCK - Error during the creation of the output object"}
}#CATCH
}#FOREACH $item
}#IF $ComputerName
ELSE {
Write-Verbose-Message"No ComputerName specified"
TRY{
# Building the basic search object with some parameters
Write-Verbose-Message"List All object"
$Searcher=New-Object-TypeNameSystem.DirectoryServices.DirectorySearcher-ErrorAction'Stop'-ErrorVariableErrProcessNewObjectSearcherALL
$Searcher.Filter ="(objectCategory=Computer)"
$Searcher.SizeLimit =$SizeLimit
# Specify a different domain to query
IF ($PSBoundParameters['DomainDN']){
$DomainDN="LDAP://$DomainDN"
Write-Verbose-Message"Different Domain specified: $DomainDN"
$Searcher.SearchRoot =$DomainDN}#IF ($PSBoundParameters['DomainDN'])
# Alternate Credentials
IF ($PSBoundParameters['Credential']) {
Write-Verbose-Message"Different Credential specified: $($Credential.UserName)"
$DomainDN=New-Object-TypeNameSystem.DirectoryServices.DirectoryEntry-ArgumentList$DomainDN, $Credential.UserName,$Credential.GetNetworkCredential().password -ErrorAction 'Stop' -ErrorVariable ErrProcessNewObjectCredALL
$Searcher.SearchRoot =$DomainDN}#IF ($PSBoundParameters['Credential'])
# Querying the Active Directory
Write-Verbose-Message"Starting the ADSI Search..."
FOREACH ($Computerin $($Searcher.FindAll())){
TRY{
Write-Verbose-Message"$($Computer.properties.name)"
New-Object-TypeNamePSObject-ErrorAction'Continue'-ErrorVariableErrProcessNewObjectOutputALL-Property @{
"Name"= $($Computer.properties.name)
"DNShostName" = $($Computer.properties.dnshostname)
"Description"= $($Computer.properties.description)
"OperatingSystem"=$($Computer.Properties.operatingsystem)
"WhenCreated"= $($Computer.properties.whencreated)
"DistinguishedName"= $($Computer.properties.distinguishedname)}#New-Object
}#TRY
CATCH{
Write-Warning-Message ('{0}: {1}'-f$Computer, $_.Exception.Message)
IF ($ErrProcessNewObjectOutputALL){Write-Warning-Message"PROCESS BLOCK - Error during the creation of the output object"}
}
}#FOREACH $Computer
Write-Verbose-Message"ADSI Search completed"
}#TRY
CATCH{
Write-Warning-Message"Something Wrong happened"
IF ($ErrProcessNewObjectSearcherALL){Write-Warning-Message"PROCESS BLOCK - Error during the creation of the searcher object"}
IF ($ErrProcessNewObjectCredALL){Write-Warning-Message"PROCESS BLOCK - Error during the creation of the alternate credential object"}
}#CATCH
}#ELSE
}#PROCESS
END{Write-Verbose-Message"Script Completed"}
}#function
#Get-Domaincomputer
#Get-Domaincomputer -ComputerName "LAB1*" -SizeLimit 5
#Get-Domaincomputer -Verbose -DomainDN 'DC=FX,DC=LAB' -ComputerName LAB1* -Credential (Get-Credential -Credential "FX.LAB\Administrator")
#Get-Domaincomputer -Verbose -DomainDN 'FX.LAB' -ComputerName LAB1* -Credential (Get-Credential -Credential "FX.LAB\FXtest")
#Get-Domaincomputer -DomainDN 'FX.LAB' -ComputerName LAB1* -Credential (Get-Credential -Credential "FX.LAB\Administrator")
#Get-Domaincomputer -DomainDN 'FX.LAB' -ComputerName LAB1*
#Get-Domaincomputer -DomainDN 'LDAP://FX.LAB' -ComputerName LAB1*
#Get-Domaincomputer -DomainDN 'LDAP://DC=FX,DC=LAB' -ComputerName LAB1*
FunctionSet-reboot (${sourcedn}<#${rebootage} = 14#>)
{
${complist}=${computers}
foreach (${computer}in${complist})
{get-CimInstance-ClassNamewin32_operatingsystem-ComputerName$computer | select csname, lastbootuptime}
}
$computers
#Set-reboot
Word Close
$wd= [Runtime.Interopservices.Marshal]::GetActiveObject('Word.Application')
$wd.Documents | ? { $_.Name } | % {
$_.Saved =$true
$_.Close()
}
$timer= 10
$date=Get-Date
if (Get-Process winword*)
{ Get-Processwinword | foreach {
if((($date-$_.StartTime).seconds) -gt$timer) {
$procID=$_.id
Write-Host-ForegroundColorMagenta"Process $procID is running longer than $timer seconds."
Write-Host-ForegroundColorGreen"Killing process $procID.."
Stop-Process$procID
}
} }