Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all 15028 articles
Browse latest View live

How to Add objectGUID into this vbscript

$
0
0

Hi,

I've been struggling for some while and I tend to do that before i give up and ask for help =(.... Well here I am. What I'm trying to do is get a full report from my AD. Came across this site that posted this script below. I've made adjustments and got it working great for someone Else's use. Now for my use it wont work. I Need to record GUID, SID and history if possible. Can someone take a look and let me know what changes you think I should make? I wont post the modified version but if i see what you put I can place it in the right place on my modified version. (just my luck I manage to get it to work for someone else but not for myself).

I assume the objects should be:

objectGUID,objectSid,sIDHistory

Here is the full script:

OPTION EXPLICIT

dim FileName, multivaluedsep,strAttributes
dim strFilter, strRoot, strScope
dim cmd, rs,cn
dim objRoot, objFSO,objCSV
dim comma, q, i, j, mvsep, strAttribute, strValue

' ********************* Setup *********************

' The filename of the csv file produced by this script
FileName ="userexport.csv"
' Seperator used for multi-valued attributes
multivaluedsep = ";"
' comma seperated list of attributes to export
strAttributes = "sAMAccountName,givenName,sn,displayName,description,physicalDeliveryOfficeName," & _"telephoneNumber,mail,cn"

' Default filter for all user accounts (ammend if required)
strFilter = "(&(objectCategory=person)(objectClass=user))"
' scope of search (default is subtree - search all child OUs)
strScope = "subtree"
' search root. e.g. ou=MyUsers,dc=wisesoft,dc=co,dc=uk
' leave blank to search from domain root
strRoot = ""

' *************************************************
q = """"

set cmd = createobject("ADODB.Command")
set cn = createobject("ADODB.Connection")
set rs = createobject("ADODB.Recordset")

cn.open "Provider=ADsDSOObject;"
cmd.activeconnection = cn

if strRoot = "" then
	set objRoot = getobject("LDAP://RootDSE")
	strRoot = objRoot.get("defaultNamingContext") 
end if

cmd.commandtext = "<LDAP://" & strRoot & ">;" & strFilter & ";" & _
		  strAttributes & ";" & strScope 

'**** Bypass 1000 record limitation ****
cmd.properties("page size")=1000

set rs = cmd.execute
set objFSO = createobject("Scripting.FileSystemObject")
set objCSV = objFSO.createtextfile(FileName)

comma = "" ' first column does not require a preceding comma
i = 0 

' create a header row and count the number of attributes
for each strAttribute in SPLIT(strAttributes,",")
	objcsv.write(comma & q & strAttribute & q)
	comma = "," ' all columns apart from the first column require a preceding comma
	i = i + 1
next
On Error Resume Next
' for each item returned by the Active Directory query
while rs.eof <> true and rs.bof <> true
	comma="" ' first column does not require a preceding comma
	objcsv.writeline ' Start a new line
	' For each column in the result set
	for j = 0 to (i - 1)
		select case typename(rs(j).value)
		case "Null" ' handle null value
			objcsv.write(comma & q & q)
		case "Variant()" ' multi-valued attribute
			' Multi-valued attributes will be seperated by value specified in
			' "multivaluedsep" variable
			mvsep = "" 'No seperator required for first value
			objcsv.write(comma & q)
			for each strValue in rs(j).Value
				' Write value
				' single double quotes " are replaced by double double quotes ""
				objcsv.write(mvsep & replace(strValue,q,q & q))
				mvsep = multivaluedsep ' seperator used when more than one value returned
			next
			objcsv.write(q)
		case else
			' Write value
			' single double quotes " are replaced by double double quotes ""
			objcsv.write(comma & q & replace(rs(j).value,q,q & q) & q)
		end select
		comma = "," ' all columns apart from the first column require a preceding comma
	next
	rs.movenext
wend

' Close csv file and ADO connection
cn.close
objCSV.Close

wscript.echo "Finished"

I get weird errors if I don't use
 On Error Resume Next



How to process cmd "nbtstat -A ip-address" output and display the computer name in Powershell

$
0
0

Hi All,

I am very new to PowerShell and I just start to play with it last week and base on my requirement now. I got this native windows command "nbtstat" that I run to validate remote computer hostname.  I am trying to make a function to pass ip-address to the command. Right now I am trying to make the code run first. The command output will be like below:

PS C:\> nbtstat -A 10.xx.xx.xxx

Local Area Connection:
Node IpAddress: [0.0.0.0] Scope Id: []

    Host not found.

Wireless Network Connection:
Node IpAddress: [10.xx.xx.xxx] Scope Id: []

           NetBIOS Remote Machine Name Table

       Name               Type         Status
    ---------------------------------------------
    COMPUTERNAME01 <00>  UNIQUE      Registered
    LAB01          <00>  GROUP       Registered
    LAB01           <1E>  GROUP       Registered
    COMPUTERNAME01 <20>  UNIQUE      Registered

    MAC Address = XX-XX-XX-XX-XX-XX

I want the function to return "COMPUTERNAME01" or the hostname only for every ip-address that I check.

Here is what I got so far and I do not know how to split the result to display the "COMPUTERNAME01" only. I am open for any suggestion from the experts. Many thanks in advance.

$nbtstat_out = nbtstat -A 10.xx.xx.xxx | Select-String -Pattern "\s*(\S+)\s+<20>"; $nbtstat_out

PowerShell Console:
COMPUTERNAME01 <20>  UNIQUE      Registered


Way to check if a cross forest user password policy has been disabled

$
0
0

We have cross forest processing going on due to a stricter password policy from forestA to forestB users. ForestB\User must continually receive the default password policy from ForestA.

Our concern is if an admin in ForestB disables the cross forest gpo/link, how would the admins in ForestA get notified/alerted for it?  What event id will appear on ForestA and ForestB domain controller?


Navgup

Working with arrays in Powershell

$
0
0

Hello everyone,

It has been an hour since I started to work on a new script in Active Directory. It is desired to query user LastLogin among all domain controllers in a domain. In a nutshell it will be used for:

 Query LastLogin of ALL user accounts from ALL domain controllers and compare them to determine the best result.

I know it might takes quite long time for this query to process but since I am not a third-party person, so far I have written this script block:

$DC = Get-ADGroupMember "domain controllers"
$Allusers = get-aduser -Filter * -searchbase "ou=AllUsers,dc=Contoso,dc=Net" -Properties Samaccountname
$i = 0
$j = 0

#Main Part Of The Script#
foreach ($User in $AllUsers)
{
$LastLogin = $null
$UserArray[$i] = $User.Samaccountname	
	foreach ($DC in $AllDC)
	{
	$UN = Get-ADUser $User -Properties lastlogin -Server $DC
	if ([DateTime]::FromFileTime($UN.LastLogin) -ge $LastLogin)
		{
		$LastLogin = $UN.LastLogin
		$LoginArray[$j] = $LastLogin
		}
	}
$i += 1
$j += 1
}

Well the questions are:

  1. Is it Optimized?
  2. Since I used two different arrays for this purpose, please kindly suggest me ideas on how to output this two arrays next to each other? ( I am not so professional in Powershell and Arrays especially) :)

Regards.

  


Mahdi Tehrani Loves Powershell
Please kindly click on Propose As Answer or to mark this post as and helpfull to other poeple.

Powershell code to print/break lines after each value read from text file

$
0
0

I am trying to create a script that can get all the servers patches installations in our environment. The script I am running is giving me continuous output without printing any success messages after each server read from text file. I have fairly written a basic script! doh.

I wanted some code to be inserted in my script to either print each server details with a break or Success message before printing another server continuously in CLI. Or to print each server in each separate text file. Please find the below Code:

$Computers = gc ServerListFile.txt

Get-hotfix -computer $Computers

Please Give me some input at least, to try and get it done.

Auto-Centering VBScript based HTA

$
0
0

Hi ScriptingGuys/All,

I am using the command below to call a custom HTA from within VBScript, and am having real difficulties getting it to launch in centre screen, rather than tucked up in one corner as it currently is!

sCommand = "mshta.exe ""javascript:{new ActiveXObject(""InternetExplorer.Application"")" _& ".putProperty('" & iRandom & "',window); window.resizeTo(" & WidthX & "," & HeightY & ");" _& "window.moveTo(" & ("screen.Width" & - WidthX) & "/2" & "," & ("screen.Height" & - HeightY) & "/2" & ")}"""

As you can see, I have the code which I THINK should be there and should work in the 'window.moveTo' statement, but this seems to be ignored completely!

('WidthX' and 'HeightY' are the two parameters passed in when calling the function, that determine the desired size of the window)

If anyone has any suggestions or can point me in the right direction, I'd be very grateful!

Many thanks,

James



LDIFDE and UPN Suffix

$
0
0

HI

how I can change UPN Suffix  by Ldfifde command 

thx


Scripting for Windows Server Backup for Exchange 2010

$
0
0

Hi,

I'm new to writing scripts and was wondering if anyone could assist with writing a script to backup an Exchange Server in a windows 2008 r2 environment.  I currently use Windows Server Backup with a full VSS backup to run exchange backups, however, each backup overwrites the previous one, and i would really like to have multiple backups.  I would also like  to specify backup log locations, and have emails sent upon successful backups or failed backups.  I am trying to write this powershell but cant seem to get things to work.

Thanks

Debbian


Listbox item value and text

$
0
0

Hello,

I'm currently working on a Powershell GUI. It's going pretty good, but i'm having a little bit of trouble wit one part.

What i want to achieve is to place a listbox with data created form a foreache object. But the displayed text in the listboxt must be different from the value.

What i have is the following:

#list box
    $lbresult = New-Object System.Windows.Forms.ListBox 
    $lbresult.Location = New-Object System.Drawing.Size(10,40) 
    $lbresult.Size = New-Object System.Drawing.Size(260,20) 
    $lbresult.Height = 80
    $lbresult.location = New-Object System.Drawing.Point(10, ($s_tbsearch.Location.Y + $s_tbsearch.Size.Height + 10))
    $s_form.Controls.Add($lbresult) 

The data is being added by:

foreach ($r in $result)
           {
                        $lbresult.Items.add($r.original_title)
            }

This  is doing what it should do. But after someone selects a field I want to preform a certain action. but i cannot do that action by the original_title value. i need to do it by the id that belongs to the title. The id is under $r.id.

So what i want is to display the original_title and has as value the id.

Is this possible? if not how could i do this. because sometimes the original_title is the same so that's not a valid source to use.

I hope you understand my question, sorry if my English is wrong. 

Greetings,

Jos

Listview control

$
0
0

I want to add a Excel like filter to a ListView in a powershell form.

The end user would like the ability to sift through the data selectively instead of looking at a few hundred rows at a time.

The source data is from a SQL server table Employee Name, Department, Location.

Any help is appreciated.

Specifying multiple names in a windows feature using DSC

$
0
0

Hi,

I'm playing around with Desired State Configuration and had a (simple?) question around it. 

All the example I have seen so far demonstrate on how to install IIS using DSC - well and good. Now, I want to install not just the web server but also the Management tools, how can I specify multiple name parameters in the same config block?

What I have is this:

    Node $NodeName
    {
        WindowsFeature IIS
        {
            Ensure = "Present"
            Name = "Web-Server"
        }
    }

What I would like is to specify the "Web-Mgmt-Tools" as part of the Name parameter, but it doesn't allow duplicate parameters. How can I specify a list of names? Is it possible to do a foreach loop in the WindowsFeature block?

Iv'e tried using Name = "Web Server,Web-Mgmt-Tools" but I get an error about the name not being recognised

Thanks in advance


outputting a function to a file.

$
0
0

Hi Guys, I am new to scripting and I can't get my head around how to output a function to a text file.

The function I have is to go away and get the external IP of a machine when a user logs in.

Function WAN_IP
   Set objxmlHTTP = CreateObject("Microsoft.XMLHTTP")
   Call objxmlHTTP.open("get", "http://checkip.dyndns.org", False)
   objxmlHTTP.Send()
 
   strHTMLText = objxmlHTTP.ResponseText
   Set objxmlHTTP = Nothing
 
   If strHTMLText <> "" Then
       varStart = InStr(1, strHTMLText, "Current IP Address:", vbTextCompare) + 19
       If varStart Then varStop = InStr(varStart, strHTMLText,"</body>", vbTextCompare)
       If varStart And varStop Then strIP = Mid(strHTMLText, varStart, varStop - varStart)
   Else
       strIP = "Unavailable"
   End If
   WAN_IP = Trim(strIP)
End Function

I want to add that function to this script and wrote the function to the text file it creates.

'Defines the Logon server to deposit audit logs

StrDatadump = "y:\AuditData\"

On Error Resume Next

'get the name of the local computer
strComputer = objWshNet.Computername

strHTMLText = objxmlHTTP.ResponseText

'get the username
strUserName = objNetwork.UserName

'Write something to the output file

dim s_date(5)    'define array

s_date(0) = Year(Now)
s_date(1) = Month(Now)
s_date(2) = Day(Now)
s_date(3) = Hour(Now)
s_date(4) = Minute(Now)
s_date(5) = Second(Now)

s_count = 0

' loop through array and add leading zero for consistency if returned value is only one character e.g. 1,2,3

for s_count = 0 to 5
    if len(s_date(s_count)) < 2 then
        s_date(s_count) = "0" & s_date(s_count)
    end if
next

' concatenate a string that will be written to output file

s_constr = s_date(2) & "/" & s_date(1) & "/" & s_date(0) & " " & s_date(3) & ":" & s_date(4) & ":" & s_date(5)

' write string to file

If objFSO.FileExists(StrDatadump & strUserName & ".txt") Then
    Set objFile = objFSO.OpenTextFile(StrDatadump & strUserName & ".txt", ForAppending)
    objFile.WriteLine ("Log In  " & strUserName & " " & s_constr)
    wscript.escho WAN_IP
Else
    Set objFile = objFSO.CreateTextFile(StrDatadump & strUserName & ".txt", ForWriting)
    objFile.WriteLine ("Log In  " & strUserName & " " & s_constr)
End If

Thanks in advance for any help you may be able to provide.

Find and delete .DS_Store files

$
0
0
I have a 2008 server where some mac clients connect. They create .DS_Store, ._.TemporaryItems and other files that starts with "._".
I want to find them and delete them every night.
What kind of script can I run.
Thank you so much for your help.

Add laptop to particular group in AD

$
0
0
I want to create a script which monitors AD for new Laptop addition and whenever there is addition of laptop in AD it should be added to particular group. I know how to manually add Laptop in group with batch when i have the hostname of laptop. what i want is a script which monitors AD for new entries in Laptop and add it automatically to the required group like say xyz group. I have searched all over net but don't understand scripts much as I am new to AD and scripting.

\m/

How do you set the value of a variable from command prompt within a batch script?

$
0
0

I just need to re-set the value of an program variable through a command prompt from within a batch file but totally forgot how to.


Can you help?


Powershell Script for DISM command on multiple servers

$
0
0

Good morning, Scripting Guys. I recently completed a project to install Windows 2008 R2 Service Pack 1 on 550 servers.

Looking for a powershell script to remotely run the command: dism /online /cleanup-image /spsuperseded /hidesp on these 550 servers.

I tried and out error code 87 because of UAC. I used psexec with starting CMD.exe remotely then using dism /online /cleanup-image /spsuperseded /hidesp

I searched Google and Technet and could not find a powershell script already, which is strange. I would like to see if you guys could assist in creating a powershell script to assist with this. I know that this command does not require a start and need to confirm that these servers do not restart and add the /norestart switch for confirmation. I have local administrator rights on all these servers as well.

Thank you!

Chris

csv to xml conversion, element naming problem

$
0
0

Script:

#Convert CSV FILES TO XML
#Test if directory has and csv files, if yes then proceed
if((test-path c:\temp\csv\*csv) -eq 1){
    $csvpath= get-childitem c:\temp\csv\*.csv| foreach-object { $_.FullName }
    $csv=Import-Csv $csvpath
    $xml=[xml]'<csvobjects/>'
    $p=$csv|gm -MemberType NoteProperty|%{$_.Name}
    $csv|%{
         $row=$xml.CreateElement('row')
        $r=$_;
        $p|%{
             $el=$xml.CreateElement($_)
             $el.InnerText=$r.($_)
             [void]$row.appendChild($el)
         }
         [void]$xml.DocumentElement.AppendChild($row)
    }
    $currdate=get-date -f MM_dd_yyyy_hh
    $f= "c:\temp\xml\$($currdate).xml"
    $xml.Save($f)

#if the directory does not have any .csv files then break
else {
break
}


Script to read a bat file from a shared location and run the bat file against the list computers provided

$
0
0

Hello,

 I'm new to writing scripts an was wondering if anyone could assist with writing a script to read a bat file from a shared location (example \\server\share.cmd) and run the bat file against the list of computers provided.

we need to uninstall a software from a list of windows 2003 servers, and we created a bat file to uninstall the softwares. But the number of computers are more than 400. So we are planning to do this using a script.


Access denied on set-adorganizationalunit

$
0
0

hi

i want to disable protected from accidental deletion on all ous for a temporary time and re-enable them again after moving ad object. i use this command:

Get-ADOrganizationalUnit -filter * -Properties protectedfromaccidentaldeletion | where {$_.protectedfromaccidentaldeletion  -match "false"} | Set-ADOrganizationalUnit -ProtectedFromAccidentalDeletion $true
but everytime it gives me error:
Set-ADOrganizationalUnit : Insufficient permissions to protect object 'OU=Server,OU=Managed,DC=Costa,DC=wl'.
At line:1 char:166+ Get-ADOrganizationalUnit -filter * -Properties protectedfromaccidentaldeletion | where {$_.protectedfromaccidentaldel
etion -match "false"} | Set-ADOrganizationalUnit <<<<  -ProtectedFromAccidentalDeletion $true+ CategoryInfo          : NotSpecified: (OU=Server,OU=Ma...DC=Costa,DC=wl:ADOrganizationalUnit) [Set-ADOrganizati
   onalUnit], ADException+ FullyQualifiedErrorId : Insufficient permissions to protect object 'OU=Server,OU=Managed,DC=Costa,DC=wl'
   .,Microsoft.ActiveDirectory.Management.Commands.SetADOrganizationalUnit

I run this command as domain admin and powershell is elevated.



Vbscript Expired User account for Newest event.

$
0
0

Hi,

I am trying to get this to work, I did ask before but then never got to implement it, now I am working on it again and I would like to get the Newest one currently with this script I am getting the oldest one so I just need to swap that around, then its working. the next step for me is to query the managed by account in ad and send the owner the notification I got that part sorted I just need the newest one.

'Option Explicit

'Declare variables being used
'Dim fso,objTextFile,strBody

'Comment out to save to result file
'Set fso = CreateObject("Scripting.FilesystemObject")
'Set objTextFile = fso.OpentextFile("Expired Notification.html", 2, True)


strComputer = "."
 
Set objWMIService = GetObject("winmgmts:" _
      & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
 
Set colLoggedEvents = objWMIService.ExecQuery _
          ("SELECT * FROM Win32_NTLogEvent WHERE Logfile = 'Security'" _
              &  "AND EventCode = '4625'")
 
For Each objLog in colLoggedEvents
     strTargetuserName =  objLog.InsertionStrings(5)
 
   strTargetDomain = objLog.InsertionStrings(6)
Next

  
'Header of the Table
strBody = "<p>The following Account's Password Expired</p>"& VbCrLf

'Contents of the script P1
strBody = strBody & "<table border=""2"" bordercolor=""2A8588"" cellspacing=""3""><Caption><b><u>Expires Password Notification</b></u></Caption><tr align=""center""><td><b>User Account</b></td><td colspan=""2"">"& strTargetuserName &"</td></tr><tr align=""center""><td><b>Domain</b><td colspan=""2"">"& strTargetDomain & "</td></td></tr>" & VbCrLf

'command to write file to the disk
'objTextFile.WriteLine(strBody)

' WMI Query # = SELECT * FROM Win32_NTLogEvent WHERE Logfile = 'Security' AND EventCode = '4625'

'SendMail settings below configured

Set objEmail = CreateObject("CDO.Message")
set objConf = CreateObject("CDO.Configuration")

objEmail.From = "Notifications@Contoso.com"
objEmail.To = "Me@Contoso.com"
objEmail.Subject = "Expired Password"
objEmail.htmlbody = strBody
objEmail.Configuration.Fields.Item _
    ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objEmail.Configuration.Fields.Item _
    ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "mail.Contoso.com"
objEmail.Configuration.Fields.Item _
    ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objEmail.Configuration.Fields.Update

objEmail.Send

Viewing all 15028 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>