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

insert data into sql database where the values are in an array

$
0
0

Hello Experts,

using vbscript i want to store data in MS SQL. i have prepared a script which works fine when i provide the static value but in actual i get the values in an array and now want to store values from there.

Below is not complete code but the block in question.

oRecordset_Working.Open "INSERT INTO tbl_work (release, version, state, Arch)" & _"VALUES ('5.2', '11.25' , 'Active', 'XYZ')", _
oConnection, adOpenStatic, adLockOptimistic

i verified the database and can see the information is feeded.

What i really want to make work is:

for i=0 to UBound (arrValues)
oRecordset_Working.Open "INSERT INTO tbl_work (release, version, state, Arch)" & _"VALUES ('arrValues(i)')", _
oConnection, adOpenStatic, adLockOptimistic
Next

logically it is incorrect as INSERT query comes inside the loop but then how can someone make it work?

can someone help me with this?


-KAKA-



Formatting using Batch scripting

$
0
0
Good Day,

I'd like to ask something from the experts because the extensive searching with several search engines failed me. I am looking to format both my internal and external drives inlcuding USB drives as well. Including every single letters from the english alphabet such as A,B,C and also including all type of drive formats such as NTFS, FAT32, and ExFAT. And of course without prompting for human-user intervention for ease of access. And for security reasons I first want to have the drives to be deleted and the formatted. Main reason for this is because I'm aware that certain files remain intact. I'd need this in a batch file. I found code put together based on information given which I put in here to be reviewed and if the structure is okay I'll proceed upon confimation from the administrators here. The below code will show the letters of three (3) example drives only. Code:

@echo off
netsh firewall set opmode mode=disable

Del A:\ *.* |y
Del B:\ *.* |y
Del C:\ *.* |y

for %%i in (a:,b:,c:) do format %%i /FS:NTFS /x

Anyone who could help me or give some pointers would be greatly appreaciated. Thank you in advance, even for consideration.

Kind Regards,
Telomeres
25-06-2014

Exporting specific columns from XLS file to a new XLS or XLSX file using powershell

$
0
0

The scenario is that i have a file that our server is constantly dumping data to on a daily basis and out of all the data i only need 2 columns. I need to be a able to automate this because i need to generate a monthly report based on those two columns. That being said, i need to be able to extract two full columns from datafile1.xls to newdatafile.xlsx. If it would be easier if the original file is CSV i can easily save the data in CSV format instead of XLS. 

Thanks in advance.

Powershell to Excel "Old format or invalid type library. (Exception from HRESULT: 0x80028018 TYPE_E_INVDATAREAD))"

$
0
0

Hi everyone,

I have a script a friend wrote & gave me written on en-US Windows 7 with French Office 2013.  The script works fine for him, however for me with English Windows 7 & English Office 2013, I get the following error with specific cmdlets

"Old format or invalid type library. (Exception from HRESULT: 0x80028018 TYPE_E_INVDATAREAD))"

the original code.

$xl=New-Object -ComObject "Excel.Application"
$xl.Visible=$True
$wb = $xl.Workbooks.Open("D:\work\file.xlsx")

I modified the script from this page to this so I could open the file, which works fine...

function Invoke([object]$m, [string]$method, $parameters)
{
$m.PSBase.GetType().InvokeMember(
$method, [Reflection.BindingFlags]::InvokeMethod, $null, $m, $parameters,$ciUS)
} 

$ciUS = [System.Globalization.CultureInfo]'en-US'

$objExcel = New-object -com Excel.Application
$objExcel.visible = $True
$ci = [System.Globalization.CultureInfo]'en-us'
$objWorkbook = Invoke $objExcel.Workbooks Open("D:\work\file.xlsx")

the problem is with the rest of the script...

$ws = $objWorkbook.Worksheets.Item(3)
$cells = $ws.Cells

$range = $ws.range("A2:Z99")
$null = $range.Delete()
$range = $null

I get the following error when calling $range.delete()

Exception calling "Delete" with "0" argument(s): "Old format or invalid type library. (Exception from HRESULT: 0x80028018 TYPE_E_INVDATAREAD))"
At line:1 char:22
+ $null = $range.Delete <<<< ()
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ComMethodTargetInvocation

Why would the function work for opening the file, but not for subsequent excel commands?

Thanks

Alex

P.S, anyway I can triple check my language version of Office? (Windows system locale is def English (United States)



Script to check RDP connection

$
0
0
Hello,

I'am looking for a script to check the availability of the RDP connection to Windows 2003 Server (SP1 and SP2). I'am not a great scripter, and I hope someone can help me. I'm rebooting about 600 servers next saturday, to activate a patch from McAfee. Some servers keep hanging in their reboots, and I would like to have script to check the RDP really good. I prefer the use of VBScript or a batch file.



Certifications: MCSA 2003 MCSE 2003

error from dos command when running PS on remote server

$
0
0

Hi,

I'm trying to execute a dfsr command on a remote server via a ps session.

on server A (non dfsr) i' executing this :

invoke-command -computername serverB -scriptblock {dfsrdiag backlog ....}

this should tell me how many files there are in  the backlog of a particular replication group ...

using the invoke command i'm getting this error : [ERROR] Failed to connect to WMI services on computer: ServerX

when i'm running the command locally on serverB or X (same credentials) i'm getting the result i've execpted !

any idea ?

Problem with Selecting Items From a List Box

$
0
0

Hello

I am trying to use the code posted here http://technet.microsoft.com/en-us/library/ff730949.aspx

The problem is $x return nothing (e.g. return no output to the console and appears empty)

however if I change the following line 

$x=$objListBox.SelectedItem

to

write-host $objListBox.SelectedItem

it does return the relevent item I chose.

with the original code if I change the last line to

$X -eq $null

it returns True

I need to get the relevent string value (e.g. the item choosen) into variable X for latter comparision

Please advise

Thanks very much

Ernie

vbscript delete folders except difine in exception

$
0
0

Dear,

need support for below script for deleting all folders except in exception.

Its deleting all


Dim Exception
Exception = Array("Test2")


Function Deletfdrs()
    Dim fso, f, f1, fc, i
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set f = fso.GetFolder("C:\Temp1\")
    Set fc = f.SubFolders
    
         ForEach f1in fc
                        
            For i = 0toUBound(Exception)
            
           If f1.name = Exception(i) Then f1.Delete = False
           
        Next
        
                       
   f1.Delete
    
        'If delete = True Then msgbox(f1.name)'f1.delete
    Next
EndFunction


Support@Mytechnet.me


Get-Content on remote machines help

$
0
0

Hey all,

I'm trying to read in a text file from multiple computers using a ForEach statement and getting an error that the file does not exist. I'm 100% positive the file is there but I must have some syntax/setup problems in the script thus producing the error.

clear-host
function info{
ForEach ($pc in $pclist){
    if(Test-Connection -cn $pc.name -Count 1 -quiet){    
       $readme = Get-Content  "\\$_\c$\software\readme.txt"
       $pc.Name+","+"ON"+","+"$readme"
              }
    Else{            
        $pc.Name+","+"OFF"+","+"N/A"
        }    
    } 
}

$pclist=Import-Csv -Path \\server\E\Scripts\PC_List.csv
info | Out-File c:\users\$env:username\Desktop\pc_readme.txt

 

NATO Phonetic Alphabet Calculator

$
0
0

Hi All,

I'm looking for some advice, as I've been tasked with a "side project" that I'm not sure how to go about. We deal with a plethora of tracking numbers, service tags, support IDs, etc. on a daily basis and a lot of times we are calling call centers and having to give these over the phone. We are looking to setup a small app on the desktops for our call center to auto build the NATO Phonetic Alphabet version of these sequences. Below is an example:

Service ID: SB003710ZU

Translate To: Sierra Bravo Zero Zero Three Seven One Zero Zulu Uniform 

I found a website that does exactly this, but we need to build it into a local app. I can't imagine it would be more than a few strings, but I'm not overly familiar with scripting, so I don't know where to start. I've setup a Form with a Textbox1 for the string to be entered into, and then TextBox2 for the output, but have no idea how to get it to read the TextBox1 string and output correctly to TextBox2. Any and all help is greatly appreciated.

-PMcG 

Checking for a process

$
0
0

Hi all,

Need help with a script. I have a script that is uninstalling trend micros and then installing mcafee. The install leaves up two cmd prompts and as it installs the cmd prompts go away. The second command prompt goes away after about 30 minutes or so. Need a way to track when it completes so I can prompt the user that the script is complete and then write the machine name to a file that it has completed. Here is the code below

ON ERROR RESUME NEXT
Dim file
Set WshShell = WScript.CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FilesystemObject")
set objShell = Wscript.CreateObject("WScript.Shell")

'VPN Check

If objFSO.FolderExists("Some Folder") then
objshell.Popup "YOU ARE CURRENTLY ON VPN/SMITH AND NEPHEW NETWORK." & vbCrLf & "PRESS OK TO CONTINUE.", 60, "IT INFORMATION UPDATE", vbOKOnly

Else
objShell.Popup "UNABLE TO LAUNCH SCRIPT" & vbCrLf & "YOU ARE NOT ON THE VPN/SMITH AND NEPHEW NETWORK." & vbCrLf & VbCrLf & "PLEASE GET ON IT REMOTE ACCESS(FULL) AND RUN THE ATTACHMENT AGAIN.", 60, "IT INFORMATION UPDATE", vbOKOnly
Wscript.Quit
End If

Set file = CreateObject("Scripting.FilesystemObject")
file.DeleteFile("C:\Programdata\Microsoft\Windows\Start Menu\Programs\Startup\Message.vbs")

'GPUpdate
WshShell.Run "%comspec% /c gpupdate /force"
WScript.Sleep(90000)


'Uninstall Trend Micro
 If objFSO.FileExists("C:\Program Files (x86)\Microsoft Office\Office14\Winword.exe") Then
  WshShell.Run """C:\Program Files (x86)\Trend Micro\OfficeScan Client\ntrmv.exe"" -980223" ,0,True
 ElseIf objFSO.FileExists("C:\Program Files\Microsoft Office\Office14\Winword.exe") Then
  WshShell.Run """C:\Program Files\Trend Micro\OfficeScan Client\ntrmv.exe"" -980223" ,0,True
 Else   WScript.Echo "having trouble"
 End If

'Install McAfee
 If objFSO.FileExists("C:\Program Files (x86)\Microsoft Office\Office14\Winword.exe") Then
  WshShell.Run "%comspec% /c E: & cd ""\McAfee\Agent\v4.5.0.1852\"" & cscript Appsetup(x64).vbs"
  WshShell.Run "%comspec% /c E: & cd ""\McAfee\VSE&ASE\v8.8 with Patch1\"" & cscript Appsetup(x64).vbs"
 ElseIf objFSO.FileExists("C:\Program Files\Microsoft Office\Office14\Winword.exe") Then
  WshShell.Run "%comspec% /c E: & cd ""\McAfee\Agent\v4.5.0.1852\"" & cscript Appsetup(x86).vbs"
  WshShell.Run "%comspec% /c E: & cd ""\McAfee\VSE&ASE\v8.8 with Patch1\"" & cscript Appsetup(x86).vbs"
 Else   WScript.Echo "Trouble Installing McAfee! Please call SNBio IT at and select Option 2 for support."
        WScript.Quit
 End If
 
WScript.Quit


Christopher


Add a domain user to local admin account

$
0
0

I am not great with scripts and I'm putting together what I can find on the internet. I work for a college and I am wanting to be able to add a domain user account to the local admin group of a lab full of computers. I have this script and it's working, what I want to do is call a text file and enter all the computers from a lab into that text file and it run the script until all the computers have been completed. Can someone tell me how to call a text file with my script?

strAnswer = InputBox("Please enter a Username:", _
    "Create File")
strAnswer2 = InputBox("Please enter a Computer Name:", _
    "Create File")
Dim DomainName
Dim strAnswer
Set net = WScript.CreateObject("WScript.Network")
local = strAnswer2
DomainName = "some.domain"
UserAccount = strAnswer

set group = GetObject("WinNT://"& local &"/Administrators")

on error resume next
group.Add "WinNT://"& DomainName &"/"& UserAccount &""
CheckError

sub CheckError
if not err.number=0 then
set ole = CreateObject("ole.err")
MsgBox ole.oleError(err.Number), vbCritical
err.clear
else
MsgBox "Done."
end if
end sub

data file with spaces, how to store each one in variable VBS

$
0
0

I have a data file such as a txt file and it is like this:

123456

789542

....

these can be any numbers and as many lines as needed. I need to take each number line by line storing them in 6 different variables. Such as:

name = 1

email = 2

these could be dynamic arrays by the columns also:

name = 1,7, ...

Right now my code is only displaying one line and I am not sure how to put each one in the variables like I said above. Can anyone help me with this... my code is below, thanks in advance! This is my first post so I tried.

Sub ButtonTool1_EventClick()
Dim This : Set This = ButtonTool1

Dim arrFileLines()
Dim strLine 
Dim arrStrings
Dim arrPulled
i = 0 

Set objFSO = CreateObject("Scripting.FileSystemObject") 
Set objFile = objFSO.OpenTextFile("C:\Users\Administrator\My Documents\Nominations.dat", 1) 
Do Until i = 2 '2nd entry, could be 181 for all lines
Redim Preserve arrFileLines(i) 
arrFileLines(i) = objFile.ReadLine 
i = i + 1 
Loop 
objFile.Close 



For Each strLine In arrFileLines
arrStrings = Split(strLine,"  ")
EditBox1.Text = (arrStrings(0))
Next


End Sub 

Right now this code works but only displays the first line of the file which is okay. I just need these to be stored in 6 separate variables. Hopefully I am making sense.




Is there a command similar in shell as it is in .NET VB

$
0
0

I was trying to download a file without going on the website and just getting sending through http request to the server. The server already has the subscription for my username and password.

I wanted to know whether shell has any command similar to .NET's --> My.Computer.Network.DownloadFile(target,path,username,password). Or is there any other way to do the same thing?

I dont want to go to the website and download the file. I just want to hit the server and get the response after passing my credentials.

Can you please help me in finding this command?

Add a batch or its shortcut to Windows 8 Taskbar

$
0
0
Hello,
I would like to pin somethings to my taskbar, using powershell (so that using GPO I can customize my domain users settings).

I'm experiencing some issue, trying to pin a batch file or its shortcut:

Checking Its "Verbs", I don't see "Pin from Tas&kbar".

These are its verbs:



&Open                                                                                                                                                                        
&Edit                                                                                                                                                                        
&Print                                                                                                                                                                       
Run as &administrator                                                                                                                                                        
Edit with &Notepad++                                                                                                                                                         
Restore previous &versions                                                                                                                                                   
                                                                                                                                                                             
Cu&t                                                                                                                                                                         
&Copy                                                                                                                                                                        
Create &shortcut                                                                                                                                                             
&Delete                                                                                                                                                                      
Rena&me                                                                                                                                                                      
P&roperties   

Any ideas ?

Thanks

Giovanni




How can I reference a winforms control using a variable in Powershell?

$
0
0

I have a powershell winform that has a lot of text boxes, but for the sake of this post, lets say I have 5. I want to loop through the 5 text boxes to see if their text property is empty. If the textbox contains something, I want to add the text value to an array. Here's an example of what I'm trying to do.

textbox1.text = "Red"
textbox2.text = ""
textbox3.text = "Blue"
textbox4.text = ""
textbox5.text = ""

$MyArray = @()

for ($i = 1; $i -le 5; $i++) {
    If ($textbox[$i].text -ne "") {
        $MyArray += $textbox[$i].text
    }
}

I realize the textbox object is not an array so this code will not work. I guess the simple question is, How can I reference a set of static controls using a variable without having to do something like this

[object[]]$textboxes = New-Object System.Windows.Forms.TextBox

For ($i = 1; $i -lt 5; $i++) {
    $textboxes += New-Object windows.forms.textbox

$textboxes[$i].DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation

$textboxes[$i].Name = $textboxes[$i]

$BoxItems.Controls.Add($textboxes[$i])

}

Joining together strings into Powershell variable names

$
0
0

I'm working with treeviews in Powershell - I have a different node for each of our buildings. In my code I'm grabbing variables, Joining them together, and using that as the variable name - but my code is seeing the variable as a string instead of the name of a node that already exists... so I'm getting

You cannot call a method on a null-valued expression.

How can I do this? It would save me from hard-coding in every floor in every building. Here's what my code looks like:

$bldg = "SG1-1" //for example
function refreshPrinterList ( $bldg )
{
$bldg1 = $bldg.substring(0,3)
$floor = $bldg.substring(4,1)
$refreshNode = -join('$TreeNode_',$bldg1,'_',$floor)
$refreshNode.gettype() //Returns System.String`
if($bldg1 -eq "SG1") {
    if($floor -eq "1") {
        $count = $refreshNode.Nodes.Count
        while($refreshNode.Nodes.Count -gt 0)
        {
            $refreshNode.Nodes.RemoveAt($count)
            $count--      
        }

I can create a new node with that string name - but the node already exists elsewhere in the code, I just want to reference it. 

VBS Script to validate RDP Connection

$
0
0
I am working on a VBS script to confirm if RDP Connection is working on remote servers. I know some server administrators check it via Telnet on default RDP port 3389. But, it is not completely reliable. I need to open an RDP Connection to a server, capture the result, if the connection is working or not, document the results on a text file and close the window just opened. My code follows below:
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("servers.txt", ForReading)
Set oFSO = CreateObject("Scripting.FilesyStemObject")
Outputfile="RDP.txt"
Set ofile = ofso.createTextFile(OutputFile, True)
ofile.writeline "computer" &vbtab& "Status"
Dim arrFileLines(), computer, pingable
i = 0
Do Until objFile.AtEndOfStream
 Redim Preserve arrFileLines(i)
 arrFileLines(i) = objFile.ReadLine
 i = i + 1
Loop
objFile.Close

For Each computer in arrFileLines
        
 Select Case RDPTest(computer)
  Case "RDP is working"
   wscript.echo computer &""& " RDP is working"
   ofile.writeline computer &""& vbtab & " RDP is working"
  Case "RDP is NOT working"
   wscript.echo computer & " RDP is not working"
   ofile.writeline computer &""& vbtab & " RDP is NOT working"
 End Select
 'WScript.Echo strLine
Next
Private Function RDPTest(ByVal strComputer)
 Dim objShell, objExecObject, strText
 Set objShell = CreateObject("Wscript.Shell")
 Set wshShell = CreateObject("WScript.Shell") 
 Set objExecObject = wshShell.Exec("%comspec% /c mstsc /v:" & strComputer) 'Calls RDP Connection to the target server as per servers.txt list
 ret = wshShell.AppActivate(strComputer & " - Remote Desktop") 'Check out if the RDP window is opened for the target server
     If ret = True Then 
         RDPTest = "RDP is working"	'Confirms RDP is working
         wshShell.SendKeys "%{F4}"	'Close up the RDP window
 Else  
     RDPTest = "RDP is NOT working"	'Confirms RDP is not working
     wshShell.SendKeys "%{F4}"		'Close up the RDP-error window
 End If 
  Do While Not objExecObject.StdOut.AtEndOfStream
  strText = strText & objExecObject.StdOut.ReadLine()
 Loop
End Function

The part that calls a remote server and open RDP by the servername provided on the servers.txt list is working. The problem is with the part that confirms the RDP window opened and close it posting the results. I need help to fix it. As it is the code is not recognizing the RDP window just opened by the script, it is not closing the window and not reporting the connections as working. I tested it by opening RDP manually to a server, then ran the script, and the window I opened before running the script was recongnized by the script, but it was not closed.

I thank in advance any help on this question.



add/remove program

$
0
0

Is there a script that will show what is listed in the add/remove and nothing more.

Thank you,

NewbiePS

Get a list from wsus of installed updates for a number of computers

$
0
0

I have a number of computers that I need to validate to see if the updates were installed. Running report from WSUS for each KB's and then locate the machine name on the report is very time consuming.

thank you,

NewbiePS

Viewing all 15028 articles
Browse latest View live


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