Powershell script to get firewall status on all computers on the domain
Trying to create a script that will get the status of the firewall's on all computers in the domain. I have a decent start but the formatting looks like crap and I am sure there is a better way to do this. Any help would be appreciated.
$strFilter = "computer"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.SearchScope = "Subtree"
$objSearcher.PageSize = 1000
$objSearcher.Filter = "(objectCategory=$strFilter)"
$colResults = $objSearcher.FindAll()
foreach ($i in $colResults)
$objComputer = $i.GetDirectoryEntry()
$objComputer.Name
netsh -r $objComputer.Name advfirewall show allprofiles state | Export-Csv -append -Path C:\Firewall.csv
My export is not working as expected - it is just giving me gibberish numbers
Using the above script I was able to get the netsh output to txt. However the formatting is not very good. Not sure if there is anything that can be done about that. Unfortunately though the output does not even display the computer
name so that the output is just a bunch of the following...
Domain Profile Settings:
State OFF
Private Profile Settings:
State OFF
Public Profile Settings:
State OFF
Ok.
Domain Profile Settings:
State OFF
Private Profile Settings:
State OFF
Public Profile Settings:
State OFF
Ok.
How do I at least get the computer name in the text file?
I added $objComputer.Name to the loop this and it didn't work... it did not put this in the text file.
Thanks for your help
$strFilter = "computer"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.SearchScope = "Subtree"
$objSearcher.PageSize = 1000
$searcher=[adsisearcher]'(objectCategory=computer)'
$searcher.FindAll() |
ForEach-Object{
$objComputer.Name
netsh -r $_.Properties['name'][0] advfirewall show allprofiles state
} |
Out-File -append -FilePath C:\Firewall.txt
Similar Messages
-
Hi,
Any help on this?
Thanks
sraboni found one on the Codeplex, this will check Nt auth group, you have to modify accordingly your need and test it in your test farm.script is for 2010 but i am positive it will work for 2013 as well.
The Sixth script lists
all the site collections which have "NT AUTHORITY\authenticated users" in
Please remember to mark your question as answered &Vote helpful,if this solves/helps your problem. ****************************************************************************************** Thanks -WS MCITP(SharePoint 2010, 2013) Blog: http://wscheema.com/blog -
Powershell to list all computers and the complete OU path
I am trying to get a list of All Computers within the domain Prefixed UK and have it export the list to a CSV with the full OU Path.
So far I can get the computers but not the OU
Get-ADComputer -Filter 'SamAccountName -like "UK*"' | Select -Exp Name
ThanksHi,
What do you mean by 'complete OU path'? If you look at the DistinguishedName property of the returned computer object, you'll see the full path there.
Don't retire TechNet! -
(Don't give up yet - 12,700+ strong and growing) -
Powershell script to get the low disk space on the servers...
Hi,
We have many SQL & Sharepoint servers running on windows server. I need some Powershell script to get the low disk space on those servers and it should send an mail alert saying "Disc d:\ have less than threshold 15% free space".
Awaiting for response.
Thanks
Anilyou should be able to use this powershell script which you can run as a scheduled task.
just change the details at the start of the script to point the script to the right location to create log files. you will need to have a plain text file containing a list of server names or ip addresses that you want to check drive space on.
# Change the following variables based on your environment
#specify the path to the file you want to generate containing drive space information
$html_file_dir = "\\server\share\DriveSpace"
#specify the path and file name of the text file containing the list of servers names you want to check drive space on - each server name on a seperate line in plain text file
$server_file = "\\server\share\servers.txt"
#speicfy the from address for the email
$from_address = "[email protected]"
#specify the to address for the email
$to_address = "[email protected]"
#specify the smtp server to use to send the email
$email_gateway = "smtp.domain.com" # Can either be DNS name or IP address to SMTP server
# The seventh line from the bottom (line 167) is used if your smtp gateway requires authentication. If you require smtp authentication
# you must uncomment it and set the following variables.
$smtp_user = ""
$smtp_pass = ""
# Change the following variables for the style of the report.
$background_color = "rgb(140,166,193)" # can be in rgb format (rgb(0,0,0)) or hex format (#FFFFFF)
$server_name_font = "Arial"
$server_name_font_size = "20px"
$server_name_bg_color = "rgb(77,108,145)" # can be in rgb format (rgb(0,0,0)) or hex format (#FFFFFF)
$heading_font = "Arial"
$heading_font_size = "14px"
$heading_name_bg_color = "rgb(95,130,169)" # can be in rgb format (rgb(0,0,0)) or hex format (#FFFFFF)
$data_font = "Arial"
$data_font_size = "11px"
# Colors for space
$very_low_space = "rgb(255,0,0)" # very low space equals anything in the MB
$low_space = "rgb(251,251,0)" # low space is less then or equal to 10 GB
$medium_space = "rgb(249,124,0)" # medium space is less then or equal to 100 GB
#### NO CHANGES SHOULD BE MADE BELOW UNLESS YOU KNOW WHAT YOU ARE DOING
# Define some variables
$ErrorActionPreference = "SilentlyContinue"
$date = Get-Date -UFormat "%Y%m%d"
$html_file = New-Item -ItemType File -Path "$html_file_dir\DiskSpace_$date.html" -Force
# Create the file
$html_file
# Function to be used to convert bytes to MB or GB or TB
Function ConvertBytes {
param($size)
If ($size -lt 1MB) {
$drive_size = $size / 1KB
$drive_size = [Math]::Round($drive_size, 2)
[string]$drive_size + ' KB'
}elseif ($size -lt 1GB){
$drive_size = $size / 1MB
$drive_size = [Math]::Round($drive_size, 2)
[string]$drive_size + ' MB'
}ElseIf ($size -lt 1TB){
$drive_size = $size / 1GB
$drive_size = [Math]::Round($drive_size, 2)
[string]$drive_size + ' GB'
}Else{
$drive_size = $size / 1TB
$drive_size = [Math]::Round($drive_size, 2)
[string]$drive_size + ' TB'
# Create the header and footer contents of the html page for output
$html_header = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Server Drive Space</title>
<style type="text/css">
.serverName { text-align:center; font-family:"' + $server_name_font + '"; font-size:' + $server_name_font_size + `
'; font-weight:bold; background-color: ' + $server_name_bg_color + '; border: 1px solid black; width: 150px; }
.headings { text-align:center; font-family:"' + $heading_font + '"; font-size:' + $heading_font_size + `
'; font-weight:bold; background-color: ' + $heading_name_bg_color + '; border: 1px solid black; width: 150px; }
.data { font-family:"' + $data_font + '"; font-size:' + $data_font_size + '; border: 1px solid black; width: 150px; }
#dataTable { border: 1px solid black; border-collapse:collapse; }
body { background-color: ' + $background_color + '; }
#legend { border: 1px solid black; ; right:500px; top:10px; }
</style>
<script language="JavaScript" type="text/javascript">
<!--
function zxcWWHS(){
if (document.all){
zxcCur=''hand'';
zxcWH=document.documentElement.clientHeight;
zxcWW=document.documentElement.clientWidth;
zxcWS=document.documentElement.scrollTop;
if (zxcWH==0){
zxcWS=document.body.scrollTop;
zxcWH=document.body.clientHeight;
zxcWW=document.body.clientWidth;
else if (document.getElementById){
zxcCur=''pointer'';
zxcWH=window.innerHeight-15;
zxcWW=window.innerWidth-15;
zxcWS=window.pageYOffset;
zxcWC=Math.round(zxcWW/2);
return [zxcWW,zxcWH,zxcWS];
window.onscroll=function(){
var img=document.getElementById(''legend'');
if (!document.all){ img.style.position=''fixed''; window.onscroll=null; return; }
if (!img.pos){ img.pos=img.offsetTop; }
img.style.top=(zxcWWHS()[2]+img.pos)+''px'';
//-->
</script>
</head>
<body>'
$html_footer = '</body>
</html>'
# Start to create the reports file
Add-Content $html_file $html_header
# Retrieve the contents of the server.txt file, this file should contain either the
# ip address or the host name of the machine on a single line. Loop through the file
# and get the drive information.
Get-Content $server_file |`
ForEach-Object {
# Get the hostname of the machine
$hostname = Get-WmiObject -Impersonation Impersonate -ComputerName $_ -Query "SELECT Name From Win32_ComputerSystem"
$name = $hostname.Name.ToUpper()
Add-Content $html_file ('<Table id="dataTable"><tr><td colspan="3" class="serverName">' + $name + '</td></tr>
<tr><td class="headings">Drive Letter</td><td class="headings">Total Size</td><td class="headings">Free Space</td></tr>')
# Get the drives of the server
$drives = Get-WmiObject Win32_LogicalDisk -Filter "drivetype=3" -ComputerName $_ -Impersonation Impersonate
# Now that I have all the drives, loop through and add to report
ForEach ($drive in $drives) {
$space_color = ""
$free_space = $drive.FreeSpace
$total_space = $drive.Size
$percentage_free = $free_space / $total_space
$percentage_free = $percentage_free * 100
If ($percentage_free -le 5) {
$space_color = $very_low_space
}elseif ($percentage_free -le 10) {
$space_color = $low_space
}elseif ($percentage_free -le 15) {
$space_color = $medium_space
Add-Content $html_file ('<tr><td class="data">' + $drive.deviceid + '</td><td class="data">' + (ConvertBytes $drive.size) + `
'</td><td class="data" bgcolor="' + $space_color + '">' + (ConvertBytes $drive.FreeSpace) + '</td></tr>')
# Close the table
Add-Content $html_file ('</table></br><div id="legend">
<Table><tr><td style="font-size:12px">Less then or equal to 5 % free space</td><td bgcolor="' + $very_low_space + '" width="10px"></td></tr>
<tr><td style="font-size:12px">Less then or equal to 10 % free space</td><td bgcolor="' + $low_space + '" width="10px"></td></tr>
<tr><td style="font-size:12px">Less then or equal to 15 % free space</td><td bgcolor="' + $medium_space + '" width="10px"></td></tr>
</table></div>')
# End the reports file
Add-Content $html_file $html_footer
# Email the file
$mail = New-Object System.Net.Mail.MailMessage
$att = new-object Net.Mail.Attachment($html_file)
$mail.From = $from_address
$mail.To.Add($to_address)
$mail.Subject = "Server Diskspace $date"
$mail.Body = "The diskspace report file is attached."
$mail.Attachments.Add($att)
$smtp = New-Object System.Net.Mail.SmtpClient($email_gateway)
#$smtp.Credentials = New-Object System.Net.NetworkCredential($smtp_user,$smtp_pass)
$smtp.Send($mail)
$att.Dispose()
# Delete the file
Remove-Item $html_file
Regards,
Denis Cooper
MCITP EA - MCT
Help keep the forums tidy, if this has helped please mark it as an answer
My Blog
LinkedIn: -
Hi Experts,
I am trying to build a PowerShell Script to get the details Like Scope,Last Deployed date and Name for a Solution Deployed in the Farm.
Can anyone advise on this please.
RegardsGet-SPSolution|Select Name,Scope,LastOperationResult,LastOperationEndTime|Export-CSV "SPInstalledSolutions.csv" -NoTypeInformation
SPSolution properties
Get-SPSolution
This post is my own opinion and does not necessarily reflect the opinion or view of Slalom. -
Network : How can I get the name of all computers in the lan ?
Hi.
Network : How can I get the name or the IP of all computers in the lan ?Easiest way to find all IPs would be to scan the network. Ping every possible IP in the network and all IPs that replied to the ping exist.
Since I don't know how to do a ping in Java, I would scan for some Ports used by OS Services.
Since I don't know which ports are used by windows, I think you should look for a ping class (or library).
Scanning all ports for every IP in a class C network shouldn't take too long. And after finding one port you don't have to try the other ports for that IP, since it has to be online ;) -
The problem is to collect info in AD about operational system, installed on all computers in AD domain?
The problem is to collect info in AD about operational system, installed on all computers in AD domain?
In addition this is a nice article which covers your needs with good explanation:
Count the number of Windows XXX computers with PowerShell and Active Directory
Mahdi Tehrani |
|
www.mahditehrani.ir
Please click on Propose As Answer or to mark this post as
and helpful for other people.
This posting is provided AS-IS with no warranties, and confers no rights.
How to query members of 'Local Administrators' group in all computers? -
I have a macbook pro running 10.6.8. Since I got it over a year ago it will disconnect from the network when left idle and then not be able to reconnect. All computers in the house have to be shut down and the router turned off in order to reconnect again. My son just updated his macbook using my os disc and now his computer is doing the same thing. What can we do?
Place the iOS device in Recovery Mode and then connect to your computer and restore via iTunes. The iPod will be erased.
iOS: Wrong passcode results in red disabled screen
If recovery mode does not work try DFU mode.
How to put iPod touch / iPhone into DFU mode « Karthik's scribblings
For how to restore:
iTunes: Restoring iOS software
To restore from backup see:
iOS: How to back up
If you restore from iCloud backup the apps will be automatically downloaded. If you restore from iTunes backup the apps and music have to be in the iTunes library since synced media like apps and music are not included in the backup of the iOS device that iTunes makes.
You can redownload most iTunes purchases by:
Downloading past purchases from the App Store, iBookstore, and iTunes Store
Also
If you have Find My iPhone enabled, you can use Remote Wipe to erase the contents of your device. If you have been using iCloud to back up, you may be able to restore the most recent backup to reset the passcode after the device has been erased. -
Hi
I need to know the command for getting list of softwares installed on all the remote systems in network which are existing in their respective registry like HKEY_LOCAL_MACHINE\SOFTWARE of all other systemsHey
Sorry this isn't powershell but it should do the job if you want to use it. The problem with using the Win32_Product WMI Class to enumerate the installed software (especially on Windows 2000 & 2003 Servers) is that the WMI class is NOT installed by default. Here is a VBScript i wrote to read a list of hostnames from a text file named "ComputerNames.txt" from the scripts directory and attempt to remotely enumerate all subkeys within the following registry key
HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall
For each subkey enumerated it will attempt to read the value of the "DisplayName" key and output the results to a csv file.
(the results should be the same as what you would see when you open Add/Remove Programs)
Hope that helps
Cheers
Matt :)
'Script Name : CheckInstalledSoftware.vbs
'Author : Matthew Beattie
'Created : 01/03/10
'Description : This script reads a list of hostnames from a text file name "ComputerNames.txt" in the scripts working
' : directory. For each hostName it requests an ICMP response and if successfull attempts a remote registry
' : connection to enumerate and read the registry values of installed software. All results are logged to the
' : scripts working directory in a log file per computer name.
'Initialization Section
Option Explicit
Const ForReading = 1
Const ForAppending = 8
Dim objFSO, wshNetwork, wshShell, hostName
Dim scriptBaseName, scriptPath, scriptLogPath
On Error Resume Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set wshShell = CreateObject("WScript.Shell")
Set wshNetwork = CreateObject("WScript.Network")
scriptBaseName = objFSO.GetBaseName(Wscript.ScriptFullName)
scriptPath = objFSO.GetFile(Wscript.ScriptFullName).ParentFolder.Path
scriptLogPath = scriptPath & "\" & IsoDateString(Now)
If Err.Number <> 0 Then
Wscript.Quit
End If
On Error Goto 0
'Main Processing Section
On Error Resume Next
PromptStart
ProcessScript
If Err.Number <> 0 Then
Wscript.Quit
End If
PromptEnd
On Error Goto 0
'Functions Processing Section
'Name : ProcessScript -> Primary Function that controls all other script processing.
'Parameters : None ->
'Return : None ->
Function ProcessScript
Dim fileSpec, hostNames, regKey, keyName, results, result
keyName = "DisplayName"
regKey = "HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall"
fileSpec = scriptPath & "\ComputerNames.txt"
'Ensure the "ComputerNames.txt" file exists within the scripts working directory.
If Not objFSO.FileExists(fileSpec) Then
MsgBox DQ(fileSpec) & " does not exist!", vbCritical, scriptBaseName
Exit Function
End If
'Read the list of hostNames from the "ComputerNames.txt" text file within the scripts working directory.
If Not GetScriptInput(hostNames, fileSpec) Then
Exit Function
End If
'Attempt to read the registry from each hostname read from the list of hostnames.
For Each hostName In hostNames
Do
'Ensure the system responds to an ICMP request.
If Not CheckConnection(hostName) Then
LogMessage 2, "Failed to respond to an ICMP Request"
Exit Do
End If
'Enumerate and read the registry values.
If Not GetRegValues(results, hostName, keyName, regKey) Then
Exit Do
End If
'Log the registry values results.
For Each result In results
LogMessage 0, result
Next
Loop Until True
Next
End Function
'Name : GetScriptInput -> Reads a text file to be used as Script input.
'Parameters : items -> Output: An array of items in the script input file.
' : fileSpec -> The full folder Path, file Name and extention of the script input file.
'Return : GetScriptInput -> Returns an array of items for script input and True or False.
Function GetScriptInput(items, fileSpec)
Dim scriptInputFile, itemsDict, item
GetScriptInput = False
Set itemsDict = NewDictionary
If Not objFSO.FileExists(fileSpec) Then
Exit Function
End If
On Error Resume Next
Set scriptInputFile = objFSO.OpenTextFile(fileSpec, ForReading)
If Err.Number <> 0 Then
Exit Function
End If
On Error Goto 0
Do Until scriptInputFile.AtEndOfStream
item = scriptInputFile.ReadLine
If item = "" Then
Exit Function
End If
If Not itemsDict.Exists(item) Then
itemsDict.Add item, ""
End If
Loop
items = itemsDict.Keys
GetScriptInput = True
End Function
'Name : CheckConnection -> Checks a remote host using WMI ping.
'Parameters : hostName -> Hostname of computer system to verify network connectivity with.
'Return : Boolean -> True if hostname replies. False otherwise.
Function CheckConnection(hostName)
Dim ping, response, replied
Set ping = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
("select * from Win32_PingStatus where address = '" & hostName & "'")
For each response in ping
replied = Not IsNull(response.StatusCode) And response.StatusCode = 0
Next
CheckConnection = replied
End Function
'Name : GetRegValues -> Enumerates the subkeys in a registry key and the values of the keyName.
'Parameters : hostName -> String containing the hostName of the system to enumerate the registry keys on.
' : keyName -> String containing the name of the registry key value to enumerate.
' : regKey -> Registry key to enumerate subkey names for.
'Return : GetRegValues -> Returns True and an Array containing the registry key values otherwise False.
Function GetRegValues(results, hostName, keyName, regKey)
Dim objReg, regDict, rootKey, hive, keyValue, subKeys, i
GetRegValues = False
rootKey = regKey
hive = GetRegistryHiveFromKey(rootKey)
On Error Resume Next
If hive <> 0 Then
'Create a dictionary object to store the registry values in.
Set regDict = NewDictionary
If Err.Number <> 0 Then
LogMessage 1, "Creating Dictionary Object"
Exit Function
End If
'Connect to the remote registry.
Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & hostName & "\root\default:StdRegProv")
If Err.Number <> 0 Then
LogMessage 1, "Creating StdRegProv Object"
Exit Function
End If
'Enumerate the subkey names within the regKey paramater.
objReg.EnumKey hive, rootKey, subKeys
If Err.Number <> 0 Then
LogMessage 1, "Enumerating Registry Keys"
Exit Function
End If
'Ensure the results are an array.
If Not IsArray(subKeys) Then
subKeys = Array(subKeys)
End If
'Read the registry key value for each subkey. Add the results to the dictionary.
For i = 0 to UBound(subKeys)
objReg.GetStringValue hive, rootKey & "\" & subKeys(i), keyName, keyValue
If Err.Number = 0 Then
If Not IsNull(keyValue) Then
regDict(regDict.Count) = keyValue
End If
Else
Err.Clear
End If
Next
End If
On Error Goto 0
results = regDict.Items
GetRegValues = True
End Function
'Name : GetRegistryHiveFromKey -> Get the hive ID from a registry key name.
'Parameters: Input/Output: key -> Registry key name. Hive name will be removed.
'Return : GetRegistryHiveFromKey -> ID of hive of given key name (0 if invalid).
' : -> The hive name is removed from the input key name.
Function GetRegistryHiveFromKey (key)
Dim pos, hive
pos = Instr (key, "\")
If pos = 0 Then
pos = Len(key) + 1
End If
hive = Left (UCase (Left (key, pos - 1)) & " ", 4)
key = Mid (key, pos + 1)
GetRegistryHiveFromKey = Array(0, &H80000000, &H80000001, &H80000002, &H80000003, &H80000005, &H80000006) _
(Int ((Instr("HKCR,HKCU,HKLM,HKU ,HKCC,HKDD", hive) + 4) / 5))
End Function
'Name : NewDictionary -> Creates a new dictionary object.
'Parameters : None ->
'Return : NewDictionary -> Returns a dictionary object.
Function NewDictionary
Dim dict
Set dict = CreateObject("scripting.Dictionary")
dict.CompareMode = vbTextCompare
Set NewDictionary = dict
End Function
'Name : DQ -> Place double quotes around a string and replace double quotes
' : -> within the string with pairs of double quotes.
'Parameters : stringValue -> String value to be double quoted
'Return : DQ -> Double quoted string.
Function DQ (ByVal stringValue)
If stringValue <> "" Then
DQ = """" & Replace (stringValue, """", """""") & """"
Else
DQ = """"""
End If
End Function
'Name : IsoDateTimeString -> Generate an ISO date and time string from a date/time value.
'Parameters : dateValue -> Input date/time value.
'Return : IsoDateTimeString -> Date and time parts of the input value in "yyyy-mm-dd hh:mm:ss" format.
Function IsoDateTimeString(dateValue)
IsoDateTimeString = IsoDateString (dateValue) & " " & IsoTimeString (dateValue)
End Function
'Name : IsoDateString -> Generate an ISO date string from a date/time value.
'Parameters : dateValue -> Input date/time value.
'Return : IsoDateString -> Date part of the input value in "yyyy-mm-dd" format.
Function IsoDateString(dateValue)
If IsDate(dateValue) Then
IsoDateString = Right ("000" & Year (dateValue), 4) & "-" & _
Right ( "0" & Month (dateValue), 2) & "-" & _
Right ( "0" & Day (dateValue), 2)
Else
IsoDateString = "0000-00-00"
End If
End Function
'Name : IsoTimeString -> Generate an ISO time string from a date/time value.
'Parameters : dateValue -> Input date/time value.
'Return : IsoTimeString -> Time part of the input value in "hh:mm:ss" format.
Function IsoTimeString(dateValue)
If IsDate(dateValue) Then
IsoTimeString = Right ("0" & Hour (dateValue), 2) & ":" & _
Right ("0" & Minute (dateValue), 2) & ":" & _
Right ("0" & Second (dateValue), 2)
Else
IsoTimeString = "00:00:00"
End If
End Function
'Name : LogMessage -> Parses a message to the log file based on the messageType.
'Parameters : messageType -> Integer representing the messageType.
' : -> 0 = message (writes to a ".csv" file)
' : -> 1 = error, (writes to a ".err" file including information relating to the error object.)
' : -> 2 = error message (writes to a ".err" file without information relating to the error object.)
' : message -> String containing the message to write to the log file.
'Return : None ->
Function LogMessage(messageType, message)
Dim prefix, logType
prefix = hostName
Select Case messageType
Case 0
logType = "csv"
Case 1
logType = "err"
message = "Error " & Err.Number & " (Hex " & Hex(Err.Number) & ") " & message & ". " & Err.Description
Case Else
LogType = "err"
End Select
If Not LogToCentralFile(scriptLogPath & "." & logType, hostName & "," & message) Then
Exit Function
End If
End Function
'Name : LogToCentralFile -> Attempts to Appends information to a central file.
'Parameters : logSpec -> Folder path, file name and extension of the central log file to append to.
' : message -> String to include in the central log file
'Return : LogToCentralFile -> Returns True if Successfull otherwise False.
Function LogToCentralFile(logSpec, message)
Dim attempts, objLogFile
LogToCentralFile = False
'Attempt to append to the central log file up to 10 times, as it may be locked by some other system.
attempts = 0
On Error Resume Next
Do
Set objLogFile = objFSO.OpenTextFile(logSpec, ForAppending, True)
If Err.Number = 0 Then
objLogFile.WriteLine message
objLogFile.Close
LogToCentralFile = True
Exit Function
End If
Randomize
Wscript.sleep 1000 + Rnd * 100
attempts = attempts + 1
Loop Until attempts >= 10
On Error Goto 0
End Function
'Name : PromptStart -> Prompt when script starts.
'Parameters : None ->
'Return : None ->
Function PromptStart
MsgBox "Now processing the " & DQ(Wscript.ScriptName) & " script.", vbInformation, scriptBaseName
End Function
'Name : PromptEnd -> Prompts when script has completed.
'Parameters : None ->
'Return : None ->
Function PromptEnd
MsgBox "The " & DQ(Wscript.ScriptName) & " script has completed successfully.", vbInformation, scriptBaseName
End Function
'Name : PromptError -> Prompts when an unexpected script error occurs.
'Parameters : None ->
'Return : None ->
'Function PromptEnd
' MsgBox "Error " & Err.Number & " (Hex " & Hex(Err.Number) & "). " & Err.Description, vbCritical, scriptBaseName
'End Function -
Powershell script to get all user profiles with specific email address
Hello,
Please help me. I need a powershell script which can do the following things.
List of all sharepoint user profiles with email address
[email protected]
List of all FBA user profiles with email address [email protected]
List of all Pending Access Requests
Any help is much appreciated. Thanks.
chiragThe script is not working for me. I changed the url according to my site. See the below error
New-Object : Exception calling ".ctor" with "1" argument(s):
"UserProfileApplicationNotAvailableException_Logging ::
UserProfileApplicationProxy.ApplicationProperties ProfilePropertyCache does
not have 3f3a5705-0691-4fe8-8643-cccd65363dc9"
At C:\Scripts\userprofileemails.ps1:11 char:19
+ $profileManager = New-Object
Microsoft.Office.Server.UserProfiles.UserProfileMan ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvoca
tionException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.Power
Shell.Commands.NewObjectCommand
You cannot call a method on a null-valued expression.
At C:\Scripts\userprofileemails.ps1:12 char:1
+ $profiles = $profileManager.GetEnumerator()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Please guide me what to do on this.
Thanks
chirag -
Hi,
I´m in a situation where I need to disable static IP option on all Domain machines (workstations). I have found many different forum topics about that but nothing is suitable for me. Let me describe a situation:
* In our environment every computer have specific IP configured in DHCP (specific MAC = specific IP). Machines Must be configured DHCP enabled!
* In our environment all developers are local admins in their computers. This can´t be changed as we are IT corporation and this is our policy.
* As every IP have specific rights in Firewall to access different places then some IT guys are quite smart to change their IP to static IP that have more access then they should have.
This last thing is my main problem! We have working PKI and NPS in both WLAN and LAN so only domain and certified computers can have access to our local network. My mission is to prevent local admins to change IP addressess by themselves but I can´t find
a good solution for doing that. I have tought about Powershell script that is published by SCCM or GPO to all workstations and script idea is to find network card that is "connected to" our "domain.com" network. If this is true then automatically
DHCP will be enabled for that interface (Set-NetIPInterface -Dhcp Enabled). I know that here is an open window for some moment when script will be ran again or GPO policy will be refreshed but it´s better then nothing. In this script I have one problem - I
can´t find a solution about how to find network interface that is connected to our "domain.com"? It seems that there is no easy way to do that.
Is there any other and better solution to accomplished this situation. Any good ideas will be appreciated.
Best Regards,
TaaviHi,
the real answer is the one you don't want to hear: don't make your users local admninistrators.
Local administrators will always be able to get araound any security measurement you put in place. For gpo's for example, they can identify the involved registry key, configure it to their desired value and
remove privileges for everyone but themselves to write the key. Upcoming 'gpupdate' will not be able to write the values...
For your script, I would recommend to just configure all adapters to dhcp on the client computers. After all the location detection depends on the network Location Awareness service. If your users disable that one (an rermove the appropriate privileges from
registry ;) ) your script would again be useless.
That being said, as you post to the security forums my answer is focussed on the security off your solution. if you need assistance in creating this script, I would advice to post back in the Scripting guys forums (and leave out the why as you will otherwise
agin be pointed on the flawed security ;) )
I think get-connectionprofile might already be helpull on 8.1
MCP/MCSA/MCTS/MCITP -
Powershell script to Get members of AD group members with first, last, email address
I'm running a powershell script to retrieve AD users from a specific AD group and pipe specific attributes to a csv file. The script is working perfectly except for one detail. I want the script to ignore any users who have a null value in any of the values
I'm piping to the spreadsheet. Meaning that if any of the users found in the queried groups have a null value in the attributes givenname, sn or mail, ignore the user and do not pipe to the csv.
Get-ADGroupMember -identity adgroup -recursive | get-adobject -Properties givenname,sn,mail | select givenname,sn,mail |export-csv -path c:\powershell\groupmembers.csv
–NoTypeInformationHi,
You can pipe your user objects through ForEach-Object and then use if to verify all three properties exist. If so, output the object. If not, move to the next object. After you've processed all user objects, then pipe into Export-Csv.
EDIT: See below.
Don't retire TechNet! -
(Don't give up yet - 13,225+ strong and growing) -
Powershell script to get Site Collection. Site Owner, Title
Hi,
I am new to SharePoint, currently I have given one task to create the powershell script which contains the below fields from our two farms. Could you please help me out with the same.
The script to list out below items:
Site Collections:
Site Collection Name:
Site Collection Owners:
Last Activity and the size of site collections.
Many Thanks & Best Regards,
NarenTo get all Site Collections:
If all you want is a list of all site collections in the farm, all you have to do is open a PowerShell window, load the SharePoint Snapin, if you haven't (Add-PSSnapin
Microsoft.SharePoint.PowerShell), and type Get-SPSite.
If you want to return the list of site collections for a specific web application, the easiest way is to just pipe it as Get-SPWebApplication
http://intranet | Get-SPSite
To get Site Collection Owners:
Add-PSSnapin "Microsoft.SharePoint.Powershell" -ErrorAction SilentlyContinue
Get-SPWebApplication "http://mySharePointSite.com"|
Get-SPSite| foreach-object{ Write-host$_.Url - $_.Owner.Email}
To get Size of all Site Collections:
Get-SPSite | select url, @{label"Size in MB";Expression={$_.usage.storage/1MB}} | Sort-Object
-Descending -Property "Size in MB" | ConvertTo-Html -title "Site Collections sort by size" | Set-Content sc.html
Regrading the retrieving the last activity I am not sure to what exactly you are looking for but I assume you are concern about getting users last logon time and date using PowerShell.
For this refer here: Get Users Last Logon Time and Date using PowerShell
Please remember to upvote if it helps you or
click 'Mark as Answer' if the reply answers your query. -
Hi All,
I have the below script which gives me the Exchange database names with the number of mailboxex in it.
(get-mailboxdatabase) | foreach-object {write-host $_.name (get-mailbox -database $_.name).count}
What i want is i also need the Server name and the DAG name (If possible) in this script so i get the output in the below format
What i get is:
Database name | No of mailboxes in the DB
XXXXX 250
What i want is:
Server name | Database name | No of mailboxes in the DB | DAG name (If possible)
XXXXXX XXXXXXX 250
DAG01
Can any one help me in making this script plz.
Gautam.75801Hi Peter,
Script works well and Good. But i cannot export the same in a CSV File. I used the below commands. But the output csv file is empty. I can just view the data in the monitor in the powershell window.
Any idea how can i export this in CSV ?
(get-mailboxdatabase) | foreach-object {write-host $_.Server, $_.name (get-mailbox -resultsize
unlimited -database $_.name).count, $_.masterserveroravailabilitygroup} | Export-csv -Path C:\Rpt.csv
And
(get-mailboxdatabase) | foreach-object {write-host $_.Server, $_.name (get-mailbox -resultsize
unlimited -database $_.name).count, $_.masterserveroravailabilitygroup} >C:\Rpt.csv
Gautam.75801 -
Exchange PowerShell script to get mailbox properties of user from a CSV file
Hi Team,
I've a CSV file with alias of numerous users and I want to get their mailbox sizes and other properties. These users are dispersed in various databases of same Exchange organization.
Need a Powershell Script, Any help?
Muhammad Nadeem Ahmed Sr System Support Engineer Premier Systems (Pvt) Ltd T. +9221-2429051 Ext-226 F. +9221-2428777 M. +92300-8262627 Web. www.premier.com.pkYou can use this and modify it to what you need. Output to a file (IE: Export-CSV "path to file"
If you need more specifics let me know. This one is for one user at a time but can be used to read a CSV file.
# Notifies the user a remote session needs to be started
Write-Host "Get a users mailbox size" -fore yellow -back red;
Write-Host "Please wait while a remote session started" -fore red -back yellow;
# Import a remote session with exchange
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://exchangeservername/Powershell/ -Authentication Kerberos
Import-PSSession $Session
Do {
# Prompts user for a name
$name = Read-Host "Enter a username"
# Get the mailbox statistics for that user
Get-MailboxStatistics $name | fl totalitemsize, storagelimitstatus, totaldeleteditemsize | out-default
# Give the user a choice to test another or EXIT
$Output = Read-Host "Press Y to continue or ENTER to exit"
# Ends the program if the user does not press Y
Until ($Output -ne "Y")
HossFly, Exchange Administrator
Maybe you are looking for
-
Adjusting the Maximum Power level Assignment Value
I have a deployment of AIR-CAP35021 APs. They are in 2 buildings with multiple floors. They are installed in a row down the hallways. I want to increase the power levels by using the controller and not configuring the APs individually. I have set the
-
DVD Dual Layer Not Working?
Hi all! This is my first time to these forums and I have some trouble with a used Toshiba x205-SLI1 I just bought. the HD Dual Layer burning does not function and the driver appears to be updated properly. It is a TS L802a model, with drivers dated a
-
How do I rebuild a common library used by both iPhoto and Aperture?
I'm using a common library for both iPhoto and Aperture-latest versions of each and Mavericks. I'm finding photos that are in the library that seem to have fallen out of their events or projects. When I open those events or projects, the folders are
-
SharePoint 2010 Designer workflow failing in an Ad hoc manner.
Hi Friends, We have a SharePoint 2010 Designer workflow with 25 approval stages (supposed to run for around 1.5 yrs. ) . We have a consistent problem in the workflow as it keeps failing with message "error occured" at some stages(not uniform) after a
-
I just downloaded ios 6.1.2 and now my iphone 4 wont hook up to a charging device
i just downloaded ios 6.1.2 and now my iphone 4 wont accept a charging device there is no error message, there is no little lightening bolt in the battery icon to show its charging, i have tried several cords and several wall outlets and hard reboote