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

VBScript Form Submission Help

$
0
0

So I'm working with both macro express and vbscript to submit a query on a web tool we have here at work. The macro express side works great and passes the needed variables out to the vbscript as it's launched, but I can't seem to grab focus of a specific element that I have the name for. I suspect it's because the site has frames and I'm just scripting it wrong, but any help would be GREATLY appreciated.

Edit: to clarify some, the site is opened via macro express. I've chosen this method because half the company is still on xp and I didn't know if our machines would let the script create an internet explorer window.

Changed the code, trying a different approach. Still having focus issues on finding that form field.

Dim namedArgs,UfeID,wShell,objShell,objIE
'set data stored in our UfeID Argument to the UfeID Variable
Set namedArgs = wscript.arguments.named
UfeID = namedArgs.item("UfeID")
If UfeID = "" Then
	MsgResult = MsgBox("No UFE ID Detected. Be sure to run the macro from FACETS", vbOKOnly, "iDRS Search " & UfeID & " - Warning")
	Wscript.Quit
End If
Set wShell = CreateObject("Wscript.Shell")
Set objShell = CreateObject("Shell.Application")
Set objIE = CreateObject("InternetExplorer.Application")
objIE.Navigate "http://idrs/idrsimaging/"
objIE.visible = true
WaitIE(winShell)
objIE.document.getElementById("docId").focus
Sub WaitIE(MyIE)
	On Error Resume Next
	Wscript.Sleep 1000
	Do
		Do
		Loop Until MyIE.ReadyState = 4
		Do
		Loop Until Not MyIE.Document is Nothing
		Do
			'Wscript.Echo MyIE.Document.ReadyState
		Loop Until MyIE.Document.ReadyState = "complete"
		If Err.Number = 0 Then
			Exit Do
		Else
			Err.Clear
		End If
	Loop
	Err.Clear
	On Error Goto 0
End Sub

Edit 2: The Frame I'm trying to control and the line where the above script is breaking
<frame src="left_toolbar.asp" name="border" noresize scrolling="auto" marginwidth="0" marginheight="0">
MyIE.Document.GetElementByID("docId").Value = UfeID






How to delete a file with size of 1GB using scripts

$
0
0
Hi,

I have a script which deletes all the backup files of mine except 1 file which is more than 1 GB. And every other day I have to manually delete those files as the drive is only 600GB.

Please advice on any scripts which can delete the files more than 1GB in size.

Thanks 

Sridhar

Scripting - Add computer to AD group

$
0
0

Hi guys,

Just wondering if you have any Script or Template that could do the below.

The Task

During SCCM OS build task sequence; I want to run a script to add the computer account to a group I created in AD. I have two groups in AD  -The addition should be based on the IP of the computers .

The Variable

 if 192.168. XXX join to A group

If 171.15.XXXX   join to B group.

Any info on how I could archive this ?

Powershell closing Excel objects with ReleaseComObject leaves dangling posh variables

$
0
0

Per this link:

http://social.technet.microsoft.com/Forums/en-US/ITCG/thread/81dcbbd7-f6cc-47ec-8537-db23e5ae5e2f

the correct way to avoid Excel zombies is to release all ComObjects in the powershell environment / script by invoking:

while ([System.Runtime.InteropServices.Marshal]::ReleaseComObject($comobject)) {}
}

on each posh variable holding a reference to a COM object, and to do so in "reverse" order (suitably defined).

"Correct" means specifically"leaves no invisible lurking Excel apps behind".

The recipe works for me when I invoke my scripts as (say):

$ ./script.ps1

But when I invoke the script as:

. ./script.ps1

and then list posh variables:

$ ls variable:

posh throws an error when it encounters the first variable that (previously) held a ComObject reference:

ls : COM object that has been separated from its underlying RCW cannot be used.
At line:1 char:1+ ls variable:+ ~~~~~~~~~~~~~~~~~~+ CategoryInfo          : NotSpecified: (:) [Get-ChildItem], InvalidComObjectException+ FullyQualifiedErrorId : System.Runtime.InteropServices.InvalidComObjectException,Microsoft.PowerShell.Commands.GetChildItemCommand

I tried rv'ing the posh variables, but when I do so prior to the ReleaseComObject, I no longer have a handle to the Com Object; alternatively when I rv the posh variable after ReleaseComObject, posh throws the same error as above.

How to release both the Com Object and the posh variable in the base posh environment (ie . ./script) while avoiding Excel zombies?

Code excerpts below:

function release($foo) { while ([System.Runtime.InteropServices.Marshal]::ReleaseComObject($foo)) {} } function killExcel() { $xl.displayalerts = $false for ($i=1; $i -lt $wss.count; $i++) { $wss.Item(1).Delete() } release $wss $wb.close($false, $false, $false) release $wb } function quit() { killExcel $xl.Quit() release $xl [gc]::collect() [gc]::WaitForPendingFinalizers() exit } ...

// read xml file, define xmltitle variable

...

// define $count = # workbook pages ... $xl = new-object -comobject Excel.Application $xl.Visible = $True $xl.DefaultFilePath = (Get-Location).ToString() + "SpreadSheets.d\" $xl.DefaultFilePath.ToString() %{$title = $xmltitle.split()} $title[1] = $title[1] -replace "[.]","dot" $filename=$xl.DefaultFilePath.ToString() + $title[1] + "_" + $title[2] + ".xlsx" $filename.ToString() $xl.sheetsInNewWorkbook = $count $wb = $xl.Workbooks.Add() $wss = $wb.worksheets $sstoc = $wss.Item(1) $sstoc.name = "Table of Contents" $sscells = $sstoc.cells $sscells.item(1,1) = $xmltoc.index release $sscells release $sstoc try { $wb.saveas($filename, $xlFileFormat::xlWorkbookDefault) } catch [system.exception] { // ignore it } quit

TIA for the help.

FWIW, I'm running Win7 and Office 2010 in a Workstation 8 VM.

Jim Snyder

execute sql query or sp stored in cell by passing id in powershell

$
0
0

I will pass 10 and corresponding script in script column will execute by opening it in power shell, how to proceed

Actually I will use Query Analiser and connect power shell


--Himanshu Kulkarni


Send an email in a shutdown script using batch file that calls an executable

$
0
0

I started out with what I thought was a simple task.  I wanted to get an email if my building looses power and when it comes back online. My mail is web based but allows smtp and I have an executable called mailsend.exe.  I created a batch file (.bat) with the fully qualified path to the exe with desired parameters.  I can run the batch file from a command prompt without any problem.  I get the email.  Next was to add it as a shutdown script in the Group Policy Editor.  My problem is that I don't know the order that things get killed during a shutdown.  Is the script (batch file) the first thing to happen on a shutdown?  The last thing?  Is it synchronous?  Asynchronous? How to I ensure the resources needed to execute the batch file will not be destroyed before I can run them or that they get forced to shutdown before they are complete?  Also, in the batch file, I am simply putting the exe (fully qualified) with parameters.  Is that safe or can I only use command mode internal commands?

Thanks in advance!

relaunch from a specified point in case of error in my script

$
0
0

Hello, i have an issue, i would like to relaunch  my script from a specified point.

In my script people try to put an UNC , if this UNC  \"\server\share " is wrong. i want my script detect it and i would like to relaunch from the point to ask UNC again.

i try trap command to hide the error message , and it show the error BUT i d'ont know how to relaunch from the asking of share

At the end of this script:

$ErrorActionPreference = 'silentlycontinue'
trap {"Vous n'avez pas donner le bon partage";continue}

SCRIPT >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

CLEAR

Write-Host "`n`nBienvenue sur Tim ACL" -ForegroundColor Yellow

$Domain = Read-Host "PUT YOUR DOMAIN"

$UNC = read-host "PUT YOUR SHARE"

if ($Domain -eq "HO")

{


#Connexion à l'ACL sur le serveur#
$Drive = "B:"

# IF THE DRIVE DOESN 't EXIST

      
if (((New-Object -Com WScript.Network).EnumNetworkDrives() | Where-Object `
{$_ -eq $Drive}))

# vrai , supprime
{
       
$net = $(New-Object -comobject WScript.Network)
$net.RemoveNetworkDrive($Drive,1)
      
}
# IF EXIST

if (!((New-Object -Com WScript.Network).EnumNetworkDrives() | Where-Object `
{$_ -eq $Drive}))
              
{

# Création objet , et map drive
$net = $(New-Object -comobject WScript.Network)
$net.mapnetworkdrive("$Drive","$Unc",$false, "ho\fr497199", "Devoteam.2017")
$ErrorActionPreference = 'silentlycontinue'
trap {"YOU DIDNT GIV THE CORRECT SHARE";continue}

CLEAR

Write-Host "`n`nBienvenue sur Tim ACL" -ForegroundColor Yellow

$Domain = Read-Host "Veuillez entrer le domaine sans extension"

$UNC = read-host "Veuillez entrer le nom de votre partage"

if ($Domain -eq "HO")

{


#Connexion à l'ACL sur le serveur#
$Drive = "B:"

# Si le drive existe alors supprime.
      
if (((New-Object -Com WScript.Network).EnumNetworkDrives() | Where-Object `
{$_ -eq $Drive}))

# vrai , supprime
{
       
$net = $(New-Object -comobject WScript.Network)
$net.RemoveNetworkDrive($Drive,1)
      
}
# Si n'existe pas
if (!((New-Object -Com WScript.Network).EnumNetworkDrives() | Where-Object `
{$_ -eq $Drive}))
              
{

# Création objet , et map drive
$net = $(New-Object -comobject WScript.Network)
$net.mapnetworkdrive("$Drive","$Unc",$false, "ho\fr497199", "Devoteam.2017")
$ErrorActionPreference = 'silentlycontinue'
trap {"Vous n'avez pas donner le bon partage";continue}

Password expiry notification!

$
0
0

Experts out there !

I am running the below script to send out email notification to all AD users whose password is going expire (mainly for the remote users who do not login to domain), below script does not throw any errors. powerGUI shows script execution is successfull and we do receive an email.

The issue with the below script is we receive an empty email with the subject "Password change log for",  the body of the message "Password change log for" and the attachment with txt file is empty. no information is written to the logs.

Appreciate if anyone can coorect the script.

========================================================================

#Add the Quest PowerShell snapin
Add-PsSnapIn Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue
Get-QADUser -SearchRoot "OU=Test Accounts,OU=Accounts,OU=Cityname,OU=Xyz,DC=Mydomain"
Where-Object {$_.PasswordStatus -ne "Password never expires" -and $_.PasswordStatus -ne "Expired" -and $_.PasswordStatus -ne "User must change password at next logon." -and $_.mail -ne $null} | 
ForEach-Object {
  $today = Get-Date
  $logdate = Get-Date -format yyyyMMdd
  $samaccountname = $_.samAccountName
  $mail = $_.mail 
  $passwordstatus = $_.PasswordStatus
  $passwordexpiry = $passwordstatus.Replace("Expires at: ","")
  $passwordexpirydate = $passwordexpiry
  $daystoexpiry = ($passwordexpirydate - $today).Days
  $attachment = "C:\passwordexpiry.txt"
  $emailFrom = "adadmin@mydomain.com"
  $body = "Please change your password to prevent loss of access to your *my domain* systems`n`n"
  $body += "If you are unable to change your password, please contact the help desk at ext 000 or 000.000.0000"
  if ($daystoexpiry -lt 9 )
  {
    $emailTo = "$mail"
    $subject = "Your Network password will expire in $daystoexpiry day(s) please change your password."    
    Send-MailMessage -To $emailTo -From $emailFrom -Subject $subject -Body $body -Attachments $attachment -SmtpServer "mail.mydomain.com"
    Write-Host "Email was sent to $mail on $today"
    Add-Content C:\maillog$logdate.txt  "Email was sent to $mail on $today"
  }
}
Send-MailMessage -To "adadmin@mydomain.com" -From "adadmin@mydomain.com" -Subject "Password change log for $today" -Body "This is the log from $today" -Attachments "C:\maillog$logdate.txt" -SmtpServer "mail.mydomain.com"

==========================================================

Thanks in Advance

Naveen Rao


VBscript text file items compare

$
0
0

I dont even know if whatI am trying to do is possible, but Ill ask anyway. I currently have a script that pulls Hostname and Ip from a xml document then runs a nslookup on results. the result output looks like this:

hostname, ip
ip, hostname.domain

What I am trying to do is compare the hostname and ip from line 1 with hostname and ip from line 2 and if they match copy the hostname to a new text document.

Please help

Thanks in advance,

cfderek

Inactive user 90 days to include lastlogin formatting lastlogonTimestamp when exporting to CSV

$
0
0

Search-ADAccount -UsersOnly -SearchBase "ou=Path,ou=To,ou=OrgUnit,dc=example,dc=com" -AccountInactive -TimeSpan 90 | 
  Get-ADUser -Properties Name, sAMAccountName, givenName, sn, lastLogonTimestamp, userAccountControl | Where {($_.userAccountControl -band 2) -eq $False} | 
    Select sAMAccountName, givenName, sn, @{n="LastLogonTimeStamp";e={[DateTime]::FromFileTime($_.lastlogon)}} | 
      Sort-Object sAMAccountName | export-csv c:\report\90day-Inactive-users.csv -NoTypeInformation

the format is coming as "12/31/1600 4:00:00 PM" for all users ???

Escaping a registry value with -PATH in the name

$
0
0

I'm writing a script to rewrite the default document locations for Microsoft Office. Word 2013 stores the default document path under the following key:

hkcu:\Software\Microsoft\Office\15.0\Word\Options\DOC-PATH (Where DOC-PATH is the value and Options is the last key).

Anyway, with powershell, I can get to this value by running:

$itemProp = Get-ItemProperty hkcu:\Software\Microsoft\Office\15.0\Word\Options -Name DOC-PATH

Now I'm trying to get $itemProp to print out the path as just a string, so I've tried $itemProp.DOC-PATH . However, whenever I run this I get the following error:

At line:1 char:14+ $itemprop.DOC-PATH+              ~~~~~
Unexpected token '-PATH' in expression or statement.+ CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException+ FullyQualifiedErrorId : UnexpectedToken

This works fine when trying to edit Excel 2013's default path (It doesn't have the -PATH in the name of the value though). Is there a way I can escape the -PATH, so I can get the string value out of the registry? Thanks!

Need to do auto SnapShot to hyperv machine with powershell

$
0
0

Hello,

I need to do every week once a time snapshot to my v.machine

and i wnat to do it with power shell and than a task schdular.

i have a  scrip but i keep geting an error :

my script:

$VMManagementService = Get-WmiObject -Namespace root\virtualization -Class Msvm_VirtualSystemManagementService
$SourceVm = Get-WmiObject -Namespace root\virtualization -Query “Select * From Msvm_ComputerSystem Where ElementName=’Xamp’”
$result = $VMManagementService.CreateVirtualSystemSnapshot($SourceVm)
#ProcessWMIJob($result)
$VMManagementService = Get-WmiObject -Namespace root\virtualization -Class Msvm_VirtualSystemManagementService $SourceVm = Get-WmiObject -Namespace root\virtualization -Query “Select * From Msvm_ComputerSystem Where ElementName=’Xamp’”
$result = $VMManagementService.CreateVirtualSystemSnapshot($SourceVm) #ProcessWMIJob($result)

the Error :

 

Get-WmiObject : Cannot bind parameter because parameter 'Namespace' is specified more than once. To provide multiple values 
to parameters that can accept multiple values, use the array syntax. For example, "-parameter value1,value2,value3".

Any one help ???

Using ip address list to get arp -a

$
0
0
I have a spreadsheet containing ip addresses, i was thinking of using a script to run each address along side arp -a and take the mac address and add it to the list alongside the corresponding ip address. 

Sometimes the answer is so blindingly obvious i fail to see it. Sdog

Windows Server Backup Robocopy Script

$
0
0

Hey Guys,

I'm trying to do local backups of a server to a Buffalo NAS device on the network using Windows backup on server 2008 R2. Ideally, I'd like to do incremental backups M-F with a full backup on Saturday night. I understand the limitations of only have one schedule backup task, so I think it would be easier to let that do the incremental backups for the week. I think a viable solution for the full backups though would be to do a robocopy script for that once a week. 

Does anyone have any suggestions on this? I have a script now that will copy the contents from one to the other, but I would ideally like it to either overwrite the existing contents or delete what is there, and write new to the folder. This would be so that the folder doesn't fill up and run out of space.

Thanks. 

Delete conflicting objects in AD and keep an ongoing log of what is being deleted

$
0
0

Hello,

I need to create a script that deletes conflcting objects within AD, and then append that info into a log. Below is what I have, however, I cannot get what is being deleted to be appended to the text file. I've tried variations and combos, including trying to use Export-Excel, or putting the line after the brackets. I've Bing'ed and consulted friends, and they do not understand why Out-File just doesn't work.


Any suggestions?

$test = dsquery * forestroot -gc -attr distinguishedname,whenchanged,whencreated -limit 0 -scope subtree -filter "(name=*\0ACNF:*)" 
foreach ($object in $test){
Remove-QADObject -Identity $object -Force -Verbose | Out-File -Append "c:\scripts\ConflictingObjectLog.txt" -noclobber
}


Shortcut Powershell Quirks

$
0
0

Hi

I am using PowerGUI and running the code below

The C drive entries come out file, path, destination, owner

However in the D drive the destination value ($LinkTarget) is mainly empty, because the
   $LinkObject = $Shell.CreateShortcut($ShortcutName)
is null

I don't understand what could be going on, i am an admin on my machine and have similat access to both the C: and D: drives.

>> Is there such a thing as "OLD STYLE" shortcuts ?

One that did not work was 299 bytes, the one that did was 663 bytes and i the differences in path lengths are nothing like 360 bytes.

# PowerShell function to list Start Menu Shortcuts
Clear-Host
#$ErrorActionPreference = "SilentlyContinue"
$Shell = New-Object -ComObject WScript.Shell 

Function Get-AllLinks([string]$path){

Get-ChildItem $Path -Include *.lnk -Recurse  |
ForEach-Object {
  $Shortcut = $_
  $objectFile = Get-Acl $Shortcut.FullName
   $ShortcutName = $Shortcut.FullName
   $LinkObject = $Shell.CreateShortcut($ShortcutName)
   $LinkTarget = $LinkObject.targetpath
   $Owner = $objectFile.Owner
   Write-Output $ShortcutName", "$LinkTarget", "$Owner

  } 
 } 

$Drives = @("C", "D")

Foreach($i in $Drives)
{
	[string]$name = "c:\temp3\"+$i+"_links.txt"
	Get-AllLinks $i":\" | Out-File $name
}

[Runtime.InteropServices.Marshal]::ReleaseComObject($Shell) | Out-Null

Thanks


Calendar Free/Busy Status

$
0
0

Hi:

Could someone please write me a VBA Script for Outlook 2007. Basically I receive many calendar invitations from a mailbox (say 123@xyz.com). Some are for 1 day or shorter. However, many are for extended periods. I need for the Free/Busy option to change to Free for the longer (invitations) so that my calendar is not block booked, and for 1 day or less to remain Busy if accepted.

Since I am new to scripts, etc., I welcome detailed responses. Thank you.

Is there a way to create a script to input large amounts of data into a file or excel?

$
0
0

Essentially I am creating a Map. For testing purposes I would want it to be 200*600 Which is 120,000 tiles that I would like to avoid entering manually :)

I want each tile to have 10 variables and the data input to be like so:

Tile1
2
3
4
5
6
7
8
9
10
Tile2
2
3
4
5
6
7
8
9
10
Tile3
...

And so on.

I would want the script to read from different files for different variables or create random numbers between 0 and x.

IE: Variable 2 = random input from file var2.txt that has 30 different rows of different text in it all with different lengths.

Now I'm just curious how hard or complicated this would be to script. What should I script it in? I would ideally like to create something much bigger in the future, something like 2000*6000 maybe. Would MySQL be able to handle such a big database that would require an hrly refresh on certain variables?

Create user script fails

$
0
0

Hi Everyone,

I have a power shell script designed to create an OU and then create users inside this OU. The commands for these parts are:

# CREATES THE OU
dsadd ou "OU=$pd,OU=Tenants,DC=ttlcloud,DC=local"

*Where $PD is the customers primary domain which is entered earlier in the script.

# CREATES THE USERS IN THE OU, FROM A CSV FILE
Import-csv "C:\Triumph\TenantSetup\UserList.csv" | foreach {new-mailbox -name $_.Fullname -alias $_.Alias -userPrincipalName “$($_.Alias)@ttlcloud.local” –FirstName $_.Firstname –Initials $_.Initial –LastName $_.Surname –OrganizationalUnit "ttlcloud.local/tenants/$pd” -SamAccountName $_.Alias –AddressBookPolicy “$pd ABP” -Password $password -ResetPasswordOnNextLogon $false -PrimarySmtpAddress “$($_.Email)@$pd”}When I run the script

When I run the script it creates the OU fine but then when it goes to create the users it says that the OU does not exist. However if I run the command a few minutes later it will add the user to the OU.

I do have 2 domain controllers but this did used to work fine all in one go. Any ways I can adjust the script to allow it to work in one run?

Thanks

Dave

VBScript to import reg file if the machine name=xxx?

$
0
0

Hi,

Here is my vbscript which checks the computer name and then it'll run the registry key if the first 3 letters of machine code matches. But unfortunately it's not working. Please help me..

'------------------------------
' Computer name
'------------------------------
Dim COMPUTER_NAME

Dim oFso, sShell, oShellEnv, target, source
Set oFso = CreateObject("Scripting.FileSystemObject")
Set oShell = WScript.CreateObject("WScript.Shell")
Set oShellEnv = oShell.Environment("Process")
COMPUTER_NAME = oShellEnv("ComputerName")

'MsgBox COMPUTER_NAME

'------------------------------
' First Three
'------------------------------
Dim FIRST_THREE

FIRST_THREE = Mid(COMPUTER_NAME, 1, 3)

'MsgBox FIRST_THREE

'------------------------------
' Get Run Registry
'------------------------------
Dim IS_RUN_REGISTRY

If FIRST_THREE = "HAC" Then
IS_RUN_REGISTRY = true
Else
IS_RUN_REGISTRY = false
End If

'MsgBox "[" & FIRST_THREE & "][" & IS_RUN_REGISTRY & "] "

'------------------------------
' Run Registry if needed
'------------------------------
Set regFile = "Genesis.reg"

If IS_RUN_REGISTRY Then
Set oShell = CreateObject("Wscript.Shell")
sRegFile = regFile
 
oShell.Run "regedit.exe /s " & Chr(34) & sRegFile & Chr(34), 0, True
End If

Viewing all 15028 articles
Browse latest View live


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