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

Filtering data from "Get-WmiObject" using "-Filter"

$
0
0

Hi,

Currently learning the Get-WmiObject cmdlet. I am trying to use the "-Filter" feature of this cmdlet, however I am getting the below exception while I get the correct output when I use the "Where-Object". I know that I am doing something wrong here. Please help.

Scenario: Query the "Win32_desktop" class, use the "-filter" option to obtain the results for the "vaio\sony" user.

Works:


PS C:\Users\SONY\Desktop> Get-WmiObject win32_desktop | where name -eq "vaio\sony"

Name               : VAIO\SONY
ScreenSaverActive  : False
ScreenSaverSecure  : 
ScreenSaverTimeout : 
SettingID          : 

Fails:

PS C:\Users\SONY\Desktop> Get-WmiObject win32_desktop -Filter "name='vaio\sony'"


Get-WmiObject : Invalid query "select * from win32_desktop where
name='vaio\sony'"
At line:1 char:1+ Get-WmiObject win32_desktop -Filter "name='vaio\sony'"+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidArgument: (:) [Get-WmiObject], Management
   Exception+ FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.C
   ommands.GetWmiObjectCommand

I did not find useful documentation/examples for the "Get-WmiObject" cmdlet. Any pointers will be appreciated. :)

Thanks


Windows not sleeping? I wrote a VBscript which puts a computer to sleep based on some criteria.

$
0
0

Tired of windows never sleeping despite lots of troubleshooting, I decided to just write a code to force sleep. Primarily - it must NOT sleep if the user is on it, or if backups are running. Code can be changed to look for different processes to stay awake for. Task scheduler is used to start the script at system start / resume, and every 15mins thereafter; script quits itself it it's already running.  

List of things this vbscript sleep code does:    
   1.   Closes itself if it's already running (like an automatic schedule run on top of a manual triggered run)    
   2.   Check if the screen is locked (now works w/ multiple users but not remote desktop - false positive on lock)    

   3.   Checks for certain / particular process and stay awake until it's done, in this case, an idrive backup and macrium reflect backup processes    

   4.  Call PsShutdown utility to sleep - the old setsuspendstate was not playing nice w/ wake timers. I hate adding extra programs but this was needed.

Sorry for the heavy commenting, it was helpful while I was thinking "out load" and trying to write it; I'm a rookie.

'=========
'CODE Functional Summary
'=========
' 	Program loads with OS boot to control sleep due to bugs in native OS sleep function
'		Also needs to run on system resume
'	Checks for duplicate instance of this script (by name), quits if new instance is a duplicate
'	Program sleeps min5s if screen is not locked (user active), then rechecks
'	Program prevents sleep while backup(s) are running (idrive, reflect)
'	If backup is not running AND screen is locked (ie - user away) sleep process initiated
'		-script ends
'		-note - it always waits 15 mins to sleep due to waiting for idrive to get running

'Recommended OS settings:
'	Ensure windows sleep setting waits at least 20mins before sleeping
'	Schedule to run this task in task scheduler when:
'		Computer boots
'		Resumes from sleep
'	Ensure a separate wake timer boots the OS ~10min prior to idrive backup start
'		backup needs to start before this script forces sleep
'		idrive setting 'wake for backup' not recommended due to issues
'		easist wake timer is to add task scheduler task to run dummy .bat using "wake to run" setting


'=========
'Development Notes
'=========
'1. the idrive service that starts during backup is intermittent during start of backup (on/off)
	'waiting min55s should allow the process to stabilize
'2. idrive setting "wake computer for backup" needs to be set to off, otherwise it keeps srvnet process open
	'even after backup is complete, which prevents sleep
'3. Need to allow idrive time to close (wscript.sleep)	after finding it's complete
'4. Need to confirm idrive is done - add for loop w/ min2 sleep after 1st not-running finding
'5. PsShutdown required to sleep and still allow wake timers - multiple other solutions failed.
'6. Duplicate wscript services found running preventing sleep
'	a. Potential issue: checking for duplicate instance fails
'		-adding error handing to end script if error happens while checking for duplicate instance
'7. ensure wscript.quit!!! did not quit after sleeping.
'8. checking for logonUI.exe is unreliable to check for locked screen - if another user
'		is logged on you get a false positive
'		SOLVED via comparing loginui count vs explorer.exe count
'9. False positive ready2sleep events - WIP
'	added line - reset ready2sleep to 0 inside non-locked code
'	WIP - add code to promt user if ready for shutdown - no prompts allowed when running w/ highest priviledges

'=========
'Error Handling
'=========
On Error Resume Next
dim error_location


'=========
'Debug Code
'=========

'Debug mode? ie - remove time delays
debug = 0	'0 = run live; 1=debug mode
debugmsg = 0	'0/1 to show debugging messages
'Err.Raise 6 'Test error handling

if debugmsg = 1 then
	msgbox"debug mode: script start - enter to continue"
end if


'========
'Variables
'========
dim ready2sleep
dim strikes
set WshShell = WScript.CreateObject("WScript.Shell")
Const TIMEOUT = 4
dim a(3)
dim debug
dim min1
dim min2
dim min5


'=========
'BEGIN CODE
'=========
'start w/ assumption NOT ready to sleep
ready2sleep=0

'set up time delays
if debug = 1 then
min1 = 351
min2 = min1
min5 = min1
else
min1 = 60000
min2 = min1*2
min5 = min1*5
end if


'Close script if it's already running
'also - quit on error
call duplicate_check
error_location = " @duplicate check"

If Err.Number <> 0 Then
	call error_log
	wscript.sleep 2000
	wscript.quit
end if

'Check if logged on or locked; if locked wait then recheck
'wait min5
'if it is - progress code to check if backup is running before sleeping
Do
	call checklock
	wscript.sleep min5
Loop while ready2sleep=0


'Now wait 3x 5min (15min total) for backup to start
'start computer 10mins before backup, backup will be running for ~min5s before proceeding

for i= 1 to 3
	wscript.sleep min5
	'WshShell.SendKeys "{numlock 2}"
	'Removed send keys - was not needed; concern was staying awake while waiting
Next


'Check for running processes which should keep system awake
	'if yes, WAIT some time, then loop until complete, if no, go to sleep
	'if no, wait min5 and check again 3x (the idrive process is intermittent so we need 3 stikes to be sure)
'		_600 processes come and go - so this helps prevent closing prematurely
'		Also helps when actually complete - to allow idrive to wrap up and close


for i = 1 to 3
	Do
		'reset status
		ready2sleep = 1

		'check status
		set service = GetObject ("winmgmts:")
			for each Process in Service.InstancesOf ("Win32_Process")
				If Process.Name = "idwutil_600.exe" OR process.name = "reflect.exe" then
					ready2sleep = 0	'if running NOT ready2sleep, so = 0
					i=1 'reset counter if process is running
				end if
			next
	wscript.sleep min1 ' don't overload the CPU constantly checking
	loop while ready2sleep = 0

	if debug = 1 then
		CreateObject("WScript.Shell").Popup "Sleeper code - no backup running stike " & i, 3, "sleep debugging"
	end if

	wscript.sleep min5 'wait 5mins to recheck - idrive service is intermittent

next

'Double check lock screen is on before final shutdown
'Did user logon while backup was running? if yes  - kill script, task scheduler restarts it
call checklock
if ready2sleep=0 then
	if debug = 1 then
		CreateObject("WScript.Shell").Popup "user logged on after backup stopped; script quiting; will be restarted at next scheduled event", 7, "sleep code debugging"
	end if
	wscript.quit
end if

'FINALLY - ready to sleep!

if debug = 1 then
	CreateObject("WScript.Shell").Popup "Sleeper code - before sleep!", 3, "Title"
end if

'Sleep option 1 - setsuspendstate
	'NOTES - having issues - will not allow wake timers - does not load booleans (0,1,0) - third one is supposed to set disable wake timer - false
	'Set objshell = CreateObject("Wscript.Shell")
	'objshell.Run "rundll32.exe PowrProf.dll, SetSuspendState 0,1,0"

'Sleep option 2 - use cmd window for PsShutdown - a windows utility, formally 3rd party
	'NOTES - could not get to work
	'Set objShell = CreateObject("WScript.Shell")
	'Set objWshScriptExec = objShell.Exec("psshutdown -d")

'Sleep option 3 - run scheduled task which calls a PsShutdown bat file
	'NOTES - could not get it to run
	'Set objTaskService = CreateObject(“Schedule.Service”)
	'objTaskService.Connect
	'Set objRootFolder = objTaskService.GetFolder(“\”)
	'Set objTask = objRootFolder.GetTask(“Test Task”)
	'objTask.Run vbNull

'Sleep option 4 - run a .bat file w/ the pshutdown command
	'NOTES - no spaces allowed in bat file name
	Set objShell = CreateObject("WScript.Shell")
	objShell.Run "\\blackbeauty\Documents-Hatcreek\Scripts\PsShutdown-sleep.bat"

if debug = 1 then
	msgbox "debug mode: end of script after sleep command, end of code"
end if

wscript.quit




'==========================================
'============= FUNCTIONS ==================
'==========================================




'Function: prevent multiple instances of this script / of a vbs / of a vbscript
'Check this file's script name
function duplicate_check
strComputer = "."
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcesses = objWMIService.ExecQuery("select * from win32_process")

	i=1
	For Each objProcess in colProcesses

		If objProcess.Name = "wscript.exe" Then
			strScriptName = Trim(Right(objProcess.CommandLine,Len(objProcess.CommandLine) - InstrRev(objProcess.CommandLine,"\")))
			strScriptName = Left(strScriptName, Len(strScriptName) - 1)
			'wscript.echo strScriptName
			a(i)= strScriptName
			'wscript.echo a(i)
			'If more than 1 wscript - check if any of the names match
			'close if there is a duplicate name
				while i>1
					if a(i)=a(i-1) then
						'Set objShell = WScript.CreateObject("WScript.Shell")
						'objShell.Popup "Already running, closing duplicate!", TIMEOUT
						wscript.quit
					end if
				Wend
			i=i+1
		End If
	Next

end function



'Function: Check lock screen status
function checklock
	Dim computer : computer = "."

	If locked(computer) Then
		if debug = 1 then
			CreateObject("WScript.Shell").Popup "Sleeper code - computer locked", 5, "debug popup"
		end if
		ready2sleep = 1
	Else
		if debug = 1 then
			CreateObject("WScript.Shell").Popup "Sleeper code - computer NOT locked", 2, "debug popup"
			wscript.sleep 3000 'for debugging - allow time to enter lock screen
		end if
		ready2sleep = 0
	End If

end function

'part of check lock
Function locked(computer)
	Dim wmi : Set wmi = GetObject("winmgmts://" & computer & "/root/cimv2")
	Dim logonUI_count : logonUI_count = wmi.ExecQuery ("SELECT * FROM Win32_Process WHERE Name = 'logonUI.exe'").Count
	Dim lockapp_count : lockapp_count = wmi.ExecQuery ("SELECT * FROM Win32_Process WHERE Name = 'lockapp.exe'").Count
	Dim explorer_count : explorer_count = wmi.ExecQuery ("SELECT * FROM Win32_Process WHERE Name = 'explorer.exe'").Count
	locked = (logonUI_count >= explorer_count)
End Function




'Function: log an error
function error_log
		Set log_file = CreateObject("Scripting.FileSystemObject").OpenTextFile("\\blackbeauty\Documents-Hatcreek\Scripts\Script Logs\Sleep Error Log.txt",8,true)
		log_file.WriteLine("test")
		log_file.WriteLine(Now & " - Error : " & Err.Number & ": " & Err.Description & error_location)
		log_file.Close
		Set log_file = Nothing
 end function

      

How to check if mailbox is already migrated before mailbox migration to HYbrid 365

$
0
0

Hello

I followed following url it seems to be working

https://social.technet.microsoft.com/Forums/scriptcenter/en-US/470b39ac-1bac-4f29-8d2d-b0ccf349e648/automating-office-365-user-licensing-and-mailbox-moves-to-the-cloud-in-hybrid-environment?forum=ITCG 

I have following query

1. Should I enable license for each before mailbox migration or after mailbox migration?

2. How do I check if user mailbox is already migrated?

Pleas advise

Avian

Hi team

$
0
0

i have applied this below script...i need help preventing save on document & folder & c drive.

after applying script how to revert back to original state.

please do the needful

Regards,

Madhu

Microsoft Dynamic CRM Deployment Manager - Set Binding Type Using Script

$
0
0

Hi Guys, 

I want to ask, is it possible set Binding Type as Https using powershell script ? And if it possible , can I change also portname for Web Application Server, Organization Web Service, Discovery Web Service and Deployment Web Service on it?

FYI, i knew it well how to configure it from UI. 

Thank you for your answer, And sorry for my bad English. 

Looking at different folders and combining files

$
0
0

Hi,

The code below is provided by someone else (unfortunately don't recall by whom) but it works.  I need to manipulate this code so that it looks not in the current folder but in the subfolders found in the directory I am working in and combine the pdf files found there.

TIA!

$workingDirectory = Split-Path -Parent $MyInvocation.MyCommand.Path;
$pdfs = ls $workingDirectory -recurse | where {-not $_.PSIsContainer -and $_.Extension -imatch "^\.pdf$"};

[void] [System.Reflection.Assembly]::LoadFrom(
    [System.IO.Path]::Combine($workingDirectory, 'itextsharp.dll')
);

$output = [System.IO.Path]::Combine($workingDirectory, 'output.pdf');
$fileStream = New-Object System.IO.FileStream($output, [System.IO.FileMode]::OpenOrCreate);
$document = New-Object iTextSharp.text.Document;
$pdfCopy = New-Object iTextSharp.text.pdf.PdfCopy($document, $fileStream);
$document.Open();

foreach ($pdf in $pdfs) {
    $reader = New-Object iTextSharp.text.pdf.PdfReader($pdf.FullName);
    $pdfCopy.AddDocument($reader);
    $reader.Dispose();  
}

$pdfCopy.Dispose();
$document.Dispose();
$fileStream.Dispose();

Powershell to get Event Logs, APPLICATION, SYSTEM, SETUP & SECURITY with Critical status

$
0
0

Hey PowerShell Guy,

We perform server checks and I am trying to put together a script to gather all the required information. One of the requirements is to gather the critical events from the application, system, setup and security logs. Application and System work fine but when I use the below statement the setup or security does not error out but never comes back with any information and just hangs.

$time = (Get-Date)-(new-timespan -day 1) - Last 24hr

$strComputer = get-content ".\Clientlist.txt" - Server List

Get-WinEvent -FilterHashTable @{LogName="Setup"; StartTime=$time} -ComputerName $strComputer | where {$_.LevelDisplayName -eq "Critical"}

Get-WinEvent -FilterHashTable @{LogName="Security"; StartTime=$time} -ComputerName $strComputer | where {$_.EntryType -eq "Critical"}

Any ideas?

Best practice for allowing/running PowerShell on a production server

$
0
0

I have created a PS script that will be used to clean-up a user share on a production server. I have done some reading on Execution Policy but don't want to open us to any extra unnecessary risk by permitting all PS scripts to run if that is not necessary.

Can someone confirm if I should this script be run directly on the server or from a remote workstation? There are a few restricted folders in the path so I will need to use the local admin of the sever or Domain Admin account to access any folders with special restrictive permissions.

The script that will be used to do the following on one of our production file servers, (in a user share);

  1. Delete all empty folders
  2. Enumerate all folders at a set path level that don't match a RegEx and move them to an Archive location
  3. At that same path level find all folders that have exceeded our retention period and move the an Archive location

Should we be signing our PS or are the alternative ways to allow this to run that is considered safe?


Stunpals - Disclaimer: This posting is provided "AS IS" with no warranties.


Add Users to a security group from a txt or csv file

$
0
0
I am trying to add the contents of a txt file to an AD security group using powershell, it acts like it works (drops down to a c:\ with no errors).....but nobody is in the group. I have tried with a csv file and a txt file. The file contains the samaccountname property. So, if you open the text file you would just see "testbox" without the quotes (this is the sam account name for the user). I am running this on a server, I am a domain admin, and the users and group are in the same domain. I am making this way to hard. Here is my scipt when trying with a csv file (GRP_PE is the name of the security group):

Import-CSV "C:\temp\pe.csv" | % { Add-ADGroupMember -Identity "grp_PE" $_.samaccountname}

I am running this in the "AD module for windows powershell"


HDL

Read-Host from a hidden Powershell session in a scheduled task!

$
0
0

Hi,

  I have a scheduled task (using an .xml to set task parameters) that runs a Powershell script.  The script is run with -WindowStyle Hidden, so the user doesn't see it.  However, sometimes I want to ask the user to enter their password, so I try to run a child Powershell process that runs Read-Host, but I don't see the Read-Host prompt.  I would like to use Powershell to get the password because of the security the -AsSecureString argument gives me.

  I assume that the child Powershell process is inheriting it's parent's Hidden aspect.  I know that because the task is set to run whether the task's account is logged on or not, that the parent task will be run hidden for other accounts.

  I'm running on Windows 8.1, the task runs with highest privileges, and it runs at the logon of any user, whether the task's account is logged on or not.

  How can I do this, and get back the user's input?

  thanks, Rob




use vbscript to abstract specific string

$
0
0

Hi Guys

I'm new to vbscript. I need a short script can do followings:

I have a lots of computer named LQ+XXXX+number ,like LQIT052,LQCST001. Those strings starts with "LQ" and followed by a variable length department code and then with 3 numbers.

What i want was a script can abstract the department code from the computer name , like 'IT' from LQIT052 or 'CST' from LQCST001. Can somebody help me.

Very appericated.

Jacky

Check whether aplication in COMAdmin.COMAdminCatalog is running or not

$
0
0

Hi,

We have some applications running in COMAdmin Catalog.

We need to check whether the application is in STOPPED state or not.If the application is in STOPPED state we need to start it.

Could you please help us with the command to check the state of the application.

We have worked the below, however not sure how to identify the current state of the service Step App and Step Common.

set oCatalog1= CreateObject("COMAdmin.COMAdminCatalog")

er4=oCatalog1.StartApplication("STeP Apps")
End If
WScript.sleep 1000

er5=oCatalog1.StartApplication("STeP Common") 'case sensitive
End If
set oCatalog1= nothing

Thanks,

Nithya

Change Computer name and join to Domain at a time through Powershell Script.

$
0
0

Hi,

I want to run a script in my windows server 2008 which will change specified client computer name and join to my domain xxxxx.com with a powershell script. 


Sugandh

VBS that runs fine under Windows 7 won't create scheduled task under Windows 10 even if it say's the task was created

$
0
0

The following script create a scheduled task under Windows 7 but not under Windows 10, even basic script samples to create a scheduled task that used to work on Windows 7 don't work on Windows 10. Are there any major changes to VBS from Windows 7 to Windows 10 that could prevent this script from running fine?

'==========================================================================
'
' VBScript Source File 
'
' NAME: 
'
' AUTHOR: Marc Sanschagin
' DATE  : 2012-03-06
'
' COMMENT: 
'
'==========================================================================
'Command,StartTime,RunRepeatedly,DaysOfWeek,DaysOfMonth,InteractWithDesktop,JobID
'***Description of properties***
'
'*DaysOfMonth* Days of the month when the job is scheduled to run.
'If a job is to run on multiple days of the month, these values can be joined in a logical OR.
'For example, if a job is to run on the 1st and 16th of each month, the value of the DaysOfMonth property will be 1 OR 32768.
'Possible values are:
'1 - 1st
'2 - 2nd
'4 - 3rd
'8 - 4th
'16 - 5th
'32 - 6th
'64 - 7th
'128 - 8th
'256 - 9th
'512 - 10th
'1024 - 11th
'2048 - 12th
'4096 - 13th
'8192 - 14th
'16384 - 15th
'32768 - 16th
'65536 - 17th
'131072 - 18th
'262144 - 19th
'524288 - 20th
'1048576 - 21st
'2097152 - 22nd
'4194304 - 23rd
'8388608 - 24th
'16777216 - 25th
'33554432 - 26th
'67108864 - 27th
'134217728 - 28th
'268435456 - 29th
'536870912 - 30th
'1073741824 - 31st

'*DaysOfWeek*
'Days of the week when the job is scheduled to run.
'If a job is to run on multiple days of the week, these values can be joined in a logical OR.
'For example, if a job is to run on Mondays, Wednesdays, and Fridays, the value of the DaysOfWeek property will be 1 OR 4 OR 16.
'Possible values are:
'1 - Monday
'2 - Tuesday
'4 - Wednesday
'8 - Thursday
'16 - Friday
'32 - Saturday
'64 - Sunday


strComputer = "."

TimeDelay = "15"'Time Delay after wich the scheduled task will execute
RUN_REPEATEDLY =False'If the task need to be run only once set to False if it as to run on a regular basis set to True
'DaysOfMonth =  'Uncomment and Define if required otherwise just use a coma
'DaysofWeek=    'Uncomment and Define if required otherwise just use a coma
InteractWithUser =False
TaskToRun=chr(34) & "C:\windows\system32\msiexec.exe" & chr(34) & " " & "/I C:\windows\support\sources\DotSoft_ToolPAC_14\ToolPac14.msi LAUNCHREADME=-2 ALLUSERS=1 USERPROFILE=C:\Users\public\ SHOWLAUNCHREADME=0 /l*v c:\windows\support\sources\DotSoft_ToolPAC_14\msi_install.log /qb"
TaskToTest= "C:\windows\system32\msiexec.exe /I C:\windows\support\sources\DotSoft_ToolPAC_14\ToolPac14.msi LAUNCHREADME=-2 ALLUSERS=1 USERPROFILE=C:\Users\public\ SHOWLAUNCHREADME=0 /l*v c:\windows\support\sources\DotSoft_ToolPAC_14\msi_install.log /qb"
Modifier= "00"


Dim MyTime
Dim strTimeZoneOffset


dtmDate = Now

blnDST = isDST( dtmDate )
DSTEffective =  blnDST


Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colScheduledJobs = objWMIService.ExecQuery  ("SELECT * FROM Win32_ScheduledJob")
ForEach objJob in colScheduledJobs

If objJob.Command = TaskToTest Then
 WScript.Echo "Task already created, exiting."
    WScript.Quit
EndIf
Next


If DSTEffective = TrueThen Modifier = "-01"

heure = Time + TimeSerial (00,TimeDelay,00) 'Set the time delay to add before execution hours, minutes, seconds
heure = heure + TimeSerial (Modifier,00,00) 'Adjustment to Daylight saving Time
heure = Replace (heure, ":","")

mode=Right(heure,2)


SelectCase mode
  Case"AM" strheure=Left (heure,Len(heure)-3)
            test=Len(strheure)
            If test =5Then
            strheure = "0" & strheure
            Endif
            MyTime= strheure
                        
  Case"PM" strheure=Left (heure,Len(heure)-3)
            test=Len(strheure)
            If test =5Then
            strheure = "0" & strheure
            Endif
            MyTime= strheure + 120000
            
        
  CaseElse MyTime=heure
  EndSelect
  
  
  
  TimeZoneOffset
  
  
  strWhen = "********" & MyTime & ".000000" & strTimeZoneOffset

  
strComputer = "."
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objNewJob = objWMIService.Get("Win32_ScheduledJob")
errJobCreated = objNewJob.Create (TaskToRun, strWhen,RUN_REPEATEDLY , , ,InteractWithUser , JobID) 

If errJobCreate = 0Then
    WScript.Echo "Job created successfully: " & VBcrlf & "DotSoft ToolPack 14 setup scheduled to run in " & TimeDelay & " minutes"
Else
    WScript.Echo "Job not created. Error code = " & errJobCreated
EndIf

WScript.quit


Function isDST( myDate )
' Returns TRUE if the specified date is in daylight Saving Time, or FALSE if not.
' The function ignores the 'ambiguous hour' right after the Standard Time transition.
'   Dim myDay, myHour, myMinute, myMonth, myYear
'   Dim lngDaylight, lngLocDate, lngStandard
'   Dim colItems, objItem, objWMIService
'   Dim strTZDST, strTZStd

    ' Parse the specified date/time
    myDate   = CDate( myDate )
    myDay    = DatePart( "d",    myDate )
    myMonth  = DatePart( "m",    myDate )
    myYear   = DatePart( "yyyy", myDate )
    myHour   = DatePart( "h",    myDate )
    myMinute = DatePart( "n",    myDate )

    Set objWMIService = GetObject( "winmgmts://./root/cimv2" )
    Set colItems = objWMIService.ExecQuery( "SELECT * FROM Win32_TimeZone", , 48 )

    ForEach objItem in colItems
        With objItem
            ' Convert the Daylight Start date/time, specified date/time and Standard Start date/time to long integers (YYYYMMDDHHmm)
            lngDaylight = .DaylightMinute + 100 * .DaylightHour + 10000 * LastDoW( .DaylightDayOfWeek, .DaylightMonth, myYear, .DaylightDay ) + 1000000 * .DaylightMonth + 100000000 * myYear
            lngLocDate  =  myMinute       + 100 *  myHour       + 10000 * myDay                                                               + 1000000 *  myMonth       + 100000000 * myYear
            lngStandard = .StandardMinute + 100 * .StandardHour + 10000 * LastDoW( .StandardDayOfWeek, .StandardMonth, myYear, .StandardDay ) + 1000000 * .StandardMonth + 100000000 * myYear
            ' Store the names for DST and Standard Time
            strTZDST    = .DaylightName
            strTZStd    = .StandardName
        EndWith
    Next

    Set colItems = Nothing
    Set objWMIService = Nothing

    ' Now that we have the long integers for the date/times, the actual comparison is quite straightforward
    If lngLocDate < lngDaylight Then
        isDST       = False
        strTimeZone = strTZStd
    ElseIf lngLocDate >= lngStandard Then
        isDST       = False
        strTimeZone = strTZStd
    Else
        isDST       = True
        strTimeZone = strTZDST
    EndIf
EndFunction

Function LastDoW( myDoW, myMonth, myYear, myWoM )
' Returns the day of the month for the specified week day, month, year and week of month
' e.g. LastDoW( 0, 3, 2011, 5 ) will return the last (5) Sunday (0) of March (3) 2011, which is 27
    Dim i, j
    j = 0
    LastDoW = 0
    For i = 1To31
        If myWoM > j Then
            IfIsDate( myYear & "-" & myMonth & "-" & i ) Then
                IfDatePart( "w", CDate( myYear & "-" & myMonth & "-" & i ), vbSunday ) = myDoW + 1Then
                        j = j + 1
                        LastDoW = i
                EndIf
            EndIf
        EndIf
    Next
EndFunction

Function TimeZoneOffset
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colTimeZone = objWMIService.ExecQuery("Select * from Win32_TimeZone")

ForEach objTimeZone in colTimeZone
    strTimeZoneOffset = objTimeZone.Bias 
Next
EndFunction

Web Server Ping or Response Time

$
0
0

Hey Scripting Guys,

By using measure-command with Invoke-Webrequest I can display the response time of a web service.

This works but I would like to be able to control the size of the web request.  Is this possible?  For example, I want to compare the response time of a request with a size of 100 bytes vs one with a size of 1400 bytes.  I could be over thinking it.  Any suggestions would be greatly appreciated.

Thanks,


Best method for scripting % Processor Time

$
0
0

I'm trying to use PowerShell to get the results of the % Processor Time performance counter, and I came across this article from 2006:

https://support.microsoft.com/en-us/kb/262938

Why would I want to use the Performance Data Helper to get the results of % Processor Time instead of using the Get-Counter cmdlet in PowerShell, or calling System.Diagnostics.PerformanceCounter in .NET?

WMI Query not returning Executable Path

$
0
0

I am using perl script to get remote executable process id, memory, thread and executable path.

This script works fine for 2008 server but on 2012 server, it is not returning ExecutablePath. I can still get memory and threadCount and process id for remote process but it does not return executable path. Permissions are given at COM Security and WMI CIMV2 namespace level same way in both servers (2008 server and 2012 servers). Can you please let me know if some additional preveleges must be given in order to get executable path?

Below is the script - 

#!perl 
use strict;
use Win32::OLE('in');
use constant wbemFlagReturnImmediately => 0x10;
use constant wbemFlagForwardOnly => 0x20;
my $host = $ARGV[0];
my $process = 'notepad.exe';
my $username = 'USERID';
my $password = 'XXXPWD';

sub connectServer {
    my $locator = Win32::OLE->new("WbemScripting.SWbemLocator") 
or die "Can't access WMI on local machine.", Win32::OLE->LastError;
    my $serverConn = $locator->ConnectServer($host, "root/cimv2", $username, $password) 
or die "Can't access WMI on remote machine $host: ", Win32::OLE->LastError;
return $serverConn;
}
my $serverConn = connectServer();
my $colItems = $serverConn->ExecQuery("SELECT *  FROM Win32_Process where Description='$process'", "WQL", wbemFlagReturnImmediately | wbemFlagForwardOnly);
foreach my $objItem (in $colItems) {
print "Name=$objItem->{Name}\t";
print "PID=$objItem->{ProcessId}\t";
print "ThreadCnt=$objItem->{ThreadCount}\t";
print "Path=$objItem->{ExecutablePath}\t";
}

OUTPUT - 

Name=notepad.exe        PID=6744        ThreadCnt=1     Path=

Executing same script for 2008 Server returns executable path information too.

Batch script to check a service is running on remote servers

$
0
0

Hey Guys

I have the bare bones of a script below . What i want it to do is

(1) Check from a list called servers.txt

(2) Check is a particular service is running

(3) If it's not then start it

(4) Echo the results to a file called results.txt

net start | find "servicename" > nul 2>&1
if not .%errorlevel%.==.0. goto startservice
goto skip


:startservice
net start "servicename"
echo service restarts @ %date% %time% >> C:\results.txt

Hostname and IP Address

$
0
0
What is a Hostname and a IP address?

Powershell script for auto Gmail logon won't work on 2nd system

$
0
0

I run the following Powershell script to auto logon to a Gmail account on my first Windows 7 system and it works just fine:

# Ensure that you are not already signed-in Gmail!
#seeking help to improve this script

$url = "http://gmail.com"
$username="myname"
$password="mypassword"
#$ie = New-Object -com internetexplorer.application;
#$ie.visible = $true;
#$ie.navigate($url);
$ie = New-Object -ComObject InternetExplorer.Application
$ie.Visible = $true
$ie.navigate($url);
$sw = @'
[DllImport("user32.dll")]
public static extern int ShowWindow(int hwnd, int nCmdShow);
'@

$type = Add-Type -Name ShowWindow2 -MemberDefinition $sw -Language CSharpVersion3 -Namespace Utils -PassThru
$type::ShowWindow($ie.hwnd, 3) # 3 = maximize
while ($ie.Busy -eq $true)
{
 Start-Sleep -Milliseconds 1000;
}
$ie.Document.getElementById("email").value = $username
$ie.Document.getElementByID("Passwd").value=$password
$ie.Document.getElementById("signin").Click();

The problem is I just got a second new Windows 7 system and when I attempt to run the very same auto logon to a Gmail account on that system, I get the following error message from Powershell:

PS C:\Windows\system32> D:\Hold\PowerShell\gmailautologon.ps1
24
Method invocation failed because [System.__ComObject] doesn't contain a method named 'getElementById'.
At D:\Hold\PowerShell\gmailautologon.ps1:24 char:28
+ $ie.Document.getElementById <<<< ("email").value = $username
    + CategoryInfo          : InvalidOperation: (getElementById:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound
 
Method invocation failed because [System.__ComObject] doesn't contain a method named 'getElementByID'.
At D:\Hold\PowerShell\gmailautologon.ps1:25 char:28
+ $ie.Document.getElementByID <<<< ("Passwd").value=$password
    + CategoryInfo          : InvalidOperation: (getElementByID:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound
 
Method invocation failed because [System.__ComObject] doesn't contain a method named 'getElementById'.
At D:\Hold\PowerShell\gmailautologon.ps1:26 char:28
+ $ie.Document.getElementById <<<< ("signin").Click();
    + CategoryInfo          : InvalidOperation: (getElementById:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

So my question is:

Why does my Powershell auto logon to a Gmail account work just fine on my first Windows 7 system, but fails on my new second Windows 7 system? 

Note: I'm no Powershell techie, so any help would be appreciated!

Thanks in advance!

Viewing all 15028 articles
Browse latest View live