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

Shadow copy via script

$
0
0

Hello,

I setup multiple Windows 2008 R2 Servers. I have managed to script a lot of what needs to be setup but I would like to script the Shadow Copy.

I would like to match exactly what happens if you click the Enable button on the config page, including the schedule and the size limitation. Does anyone have this script?

Thank you for you help


Powershell Splitting file name issue

$
0
0

Hey guys,

       I have an issue with splitting a file name and assigning the splits to variables to i can write them to a SQL database.

my sample file name is: I12345L98765.tif where this variable is $name

what im using is 

      $splitup=$name -split'[I,L,.]'
      $item=$splitup[1]
      $lot=$splitup[2]

Then i'm trying to write the $item and $lot to a SQL database. 

Two problems i'm having is the the $lot doesnt always seem to get data and secondly if my sample file name has to characters the same ie: I12345LL98765.tif the variable never gets passed at all.

If hope i was clear in my explanation. Any help is greatly appreciated.

Thanks

Rich T.




Rich Thompson

Script to change computer description in Active Directory

$
0
0

I have the following script that allows me to disable 500+ computer accounts at once. It works just fine but I am wanting to also have it add a reason why in the Description field. I've looked online and can't seem to find anything.

Can someone add to this code so it will also add what I want to the description field?

Option Explicit

Dim strFile, objFSO, objFile
Dim objRootDSE, strDNSDomain, objTrans, strNetBIOSDomain
Dim strComputer, strComputerDN, objComputer

' Constants for the NameTranslate object.
Const ADS_NAME_INITTYPE_GC = 3
Const ADS_NAME_TYPE_NT4 = 3
Const ADS_NAME_TYPE_1779 = 1

' Specify text file of computer NetBIOS names.
strFile = "C:\Disable.XP\Computers.rAM.txt"

' Open the file for read access.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFile, 1)

' Determine DNS name of domain from RootDSE.
Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("defaultNamingContext")

' Use the NameTranslate object to find the NetBIOS domain name from the
' DNS domain name.
Set objTrans = CreateObject("NameTranslate")
objTrans.Init ADS_NAME_INITTYPE_GC, ""
objTrans.Set ADS_NAME_TYPE_1779, strDNSDomain
strNetBIOSDomain = objTrans.Get(ADS_NAME_TYPE_NT4)
' Remove trailing backslash.
strNetBIOSDomain = Left(strNetBIOSDomain, Len(strNetBIOSDomain) - 1)

' Read lines from the file.
Do Until objFile.AtEndOfStream
    strComputer = Trim(objFile.ReadLine)
    If (strComputer <> "") Then
        ' Convert NetBIOS name to DN.
        ' NetBIOS name must have "$" appended to end.
        ' Trap error if computer not found.
        On Error Resume Next
        objTrans.Set ADS_NAME_TYPE_NT4, strNetBIOSDomain & "\" & strComputer & "$"
        If (Err.Number <> 0) Then
            On Error GoTo 0
            Wscript.Echo "Computer not found: " & strComputer
        Else
            On Error GoTo 0
            strComputerDN = objTrans.Get(ADS_NAME_TYPE_1779)
            ' Bind to the computer object.
            Set objComputer = GetObject("LDAP://" & strComputerDN)
            ' Disable the computer.
            objComputer.AccountDisabled = True
	    objComputer.SetInfo
        End If
    End If
Loop

msgBox "Computers have been disabled"

search active directory for multiple computer names

$
0
0
Hi, Is there a simple way of searching AD for multiple computer names on a text file, and output the results to include the current OU ?

Create a remote share on a win2008R2 + share permission

$
0
0

Hello,

I have this script , the only problem is creation of the share , i think its happing problems with the UNC path the\\ws30540\c$\WebSrvLog\APP is used as a working UNC path on my computer ( its my own computer )

I know i can use net share with c:\ but as i have read on the internet netshare + unc path do not work ( i tested it myself )

So i started using win32_share but this doesn't work either. When i change the script to C:\WebSrv... it works :(

I can't copy PS script here so i used pastbin ; http://pastebin.com/RGpvHP4X

Create view in Outlook 2013 using Powershell

$
0
0

Hi,

I am attempting to write a piece of script to create conditional formatting rules for user's Outlook. 

I have found the MSDN developer reference for the specific object and it includes an example of what I am trying to achieve:

http://msdn.microsoft.com/en-us/library/ff864185(v=office.15).aspx   (Sorry link not set up properly because I haven't posted enough to verify my account yet)

Unfortunately the example is in VBScript and I am failing to convert this into Powershell. So far I have got this:

# Import Outlook and get Mail API
Add-Type -assembly "Microsoft.Office.Interop.Outlook"
$Outlook = New-Object -comobject Outlook.Application

# Set Inbox path as variable
$namespace = $Outlook.GetNameSpace("MAPI")
$inbox = $namespace.GetDefaultFolder([Microsoft.Office.Interop.Outlook.OlDefaultFolders]::olFolderInbox)

$View = $namespace.GetDefaultFolder([Microsoft.Office.Interop.Outlook.OlDefaultFolders]::olFolderInbox).Views

$View.Add("Test", [Microsoft.Office.Interop.Outlook.OlViewType]::olTableView)

I know that it works up to the last line, if I print out $View then I can see all of my current views however the final line throws up this error message:

Exception calling "Add" with "2" argument(s): "Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))"
At C:\Scripts\Work_In_Progress\WIP-Outlook_Conditional_Formatting.ps1:11 char:1+ $View.Add("Test", [Microsoft.Office.Interop.Outlook.OlViewType]::olTableView)+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException+ FullyQualifiedErrorId : ComMethodTargetInvocation

Any help in working out how to make this work would be much appreciated.

Thank you

BITS 3.0 Bandwith Settings

$
0
0

Hi there, 
I am looking for a way to set BITS 3.0 / 4.0 bandwidth settings on various servers using a script, for organizational reasons it is not possible to adjust the values ​​by GPO. 

For BITS 2.0, there are registry entries to make these setting, these registry values ​​reflect the setting "Maximum network bandwidth for BITS background transfers," in the local computer policy. 

I've changed  the setting in the local computer policy, but the registry values were not created so in the case of BITS 3.0 / 4.0 i suspect the values ​​are no longer effective.

Does anyone know a way to change these settings via script, preferable remotely? 

Thanks in advance!
Rolf

Running a CMD.exe from PowerShell with arguments

$
0
0

Hello guys, I am working with a driver backup program that I need to automate. I am using Power shell to run a few other tasks, like check the OS version and create a folder based on the system type for drivers. We deploy many different devices and needed a way to automate. That is neither here nor there. Here is what I am trying to run, but the CMD, will not seem to pick up the arguments. If I run from the CMD prompt, it will run as expected, but when I lick it off with Power shell, I get a few errors. 

Here is what I have:

$command = @'
cmd.exe /C C:\DriverBU\DrvBK.exe MODE="BACKUP" BKPATH="C:\TempDrivers" BKDESC="Drivers" BKFILE="Backup %NOW%  %COMPUTERNAME%.bki" BKPATHFTM="%COMPUTERNAME%" BKDEVFMT="%DEVNAME%" BKDATEFMT="" OPT="HW"
'@

Invoke-Expression -Command:$command


This will open the program, however, will not run the arguments.

Thoughts?

Thank you!

Paul


Duramaxster


VBscript to find specific list of installed software on windows XP, windows & and others

$
0
0
Hi All,

I need a vbscript which will find following list of softwares on my system, and if it is there then it will give detials of that software like version, install date, etc.

1.  IE details (like v10)
2.  PAC File details which is use for internet browsing
3. Java JRE details

Also my concern is that it must run on all versions of windows OS from XP to 8.1

As I am new to vb script so please help me out.

Thanks.

Writing a table to a MS Access database from Powershell

$
0
0

Hey guys, me again...I'm trying to wrap up a project here and i have a powershell app writing to a SQL database just fine. The last piece is writing to a MS Access database table. For the life of me i cannot find anything out there that really points me in the right direction.

I know my database name/path and i know the table/headers i need to write my data too.

Anyone have a link to a quick dirty tutorial or can someone point me in the right direction ?

Thanks as always

Rich


Rich Thompson

Powershell Script to automatically format USB Thumb drives when inserted. Not working on Windows XP

$
0
0

I have created a script that recognizes USB thumb drives then formats them, it works great on my Windows 7 machines but I did not realize that the machine I was making it for used Windows XP.

Is there a way to make this script work under windows XP? I have updated XP to the latest PowerShell and when I start it up all it tells me is "starting script" but the script does not work, nothing happens after I start it..

Here is the Script:

Register-WmiEvent -Class win32_VolumeChangeEvent -SourceIdentifier volumeChange
write-host (get-date -format s) " Beginning script..."
do{
$newEvent = Wait-Event -SourceIdentifier volumeChange
$eventType = $newEvent.SourceEventArgs.NewEvent.EventType
$eventTypeName = switch($eventType)
{
1 {"Configuration changed"}
2 {"Device arrival"}
3 {"Device removal"}
4 {"docking"}
}
write-host (get-date -format s) " Event detected = " $eventTypeName
if ($eventType -eq 2)
{
$driveLetter = $newEvent.SourceEventArgs.NewEvent.DriveName
$driveLabel = ([wmi]"Win32_LogicalDisk='$driveLetter'").VolumeName
write-host (get-date -format s) " Drive name = " $driveLetter
write-host (get-date -format s) " Drive label = " $driveLabel
# Execute process if drive matches specified condition(s)
if ($driveLetter -eq 'M:')
{
write-host (get-date -format s) " Starting task in 3 seconds..."
start-sleep -seconds 3
Start Format 'm: /fs:Fat32 /q /x /y'
}
if ($driveLetter -eq 'L:')
{
write-host (get-date -format s) " Starting task in 3 seconds..."
start-sleep -seconds 3
Start Format 'L: /fs:Fat32 /q /x /y'
}
}
Remove-Event -SourceIdentifier volumeChange
} while (1-eq1) #Loop until next event
Unregister-Event -SourceIdentifier volumeChange

Remove Permission Weirdness

$
0
0

I have the following script to create a folder and add a default permission.

It is then supposed to remove inheritance.

Then remove Authenticated Users from the folder.

If I run the following script all works except remove the Authenticated Users from the folder.

$dir = "\\serversfs01\users\systest3"

New-item -Path $dir -ItemType Directory

$acl = get-acl -Path $dir
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule('systest3',"DeleteSubdirectoriesAndFiles, Write, ReadAndExecute, Synchronize", "ContainerInherit, ObjectInherit", "None", "Allow")
$acl.AddAccessRule($rule)

# This removes inheritance
$acl.SetAccessRuleProtection($True,$True)

$removeuser = "NT Authority\Authenticated Users"
$accessrule = New-Object system.security.AccessControl.FileSystemAccessRule($removeuser,"Read",,,"Allow")
$acl.RemoveAccessRuleAll($accessrule)

$acl |Set-Acl

I can then run this and it removes the Authenticated Users from the folder. I just can't figure out why it does not work all as one.

$dir = "\\serversfs01\users\systest3"

$acl = get-acl -Path $dir

$removeuser = "NT Authority\Authenticated Users"
$accessrule = New-Object system.security.AccessControl.FileSystemAccessRule($removeuser,"Read",,,"Allow")
$acl.RemoveAccessRuleAll($accessrule)

$acl |Set-Acl

Any ideas. I thought it was a timing issue, but that is not it.


Start a script as administartor from within a script (Batch)

$
0
0
Hi,

I have a Batch script that is started remotely from one computer(PC-X)  on another(PC-A).

Now within the script tat is running on the PC-A I want to triger another Batch script  (or command) with administartive privileges.
Everey thing I tried till now failed.

I now stick on the Evelate Tools: Elevate Tools

But I also Fail:

Script A:

 
D:
CD D:\ElevDir
@Echo Parent Script>> D:\elev.txt
Elevate32 -s 1 -d D:\ElevDir cmd.exe /c D:\ElevDir\Cmd_Tracer.bat
@Echo Parent Script>> D:\elev.txt

Script B:

@Echo OFF
D:
CD D:\ElevDir
@Echo Child Script >> D:\elev.txt
for /F "TOKENS=1,2,*" %%a in ('tasklist /FI "IMAGENAME eq MyProcess.exe"') do set MyPID=%%b
@Echo %MyPID% >>  D:\elev.txt
@Echo Child Script >> D:\elev.txt

When I run it manually it allways prompts me for a UAC, but this is not wanted during a automated execution ...
I'think I missing something basic ...

If else usage for Windows Batch

$
0
0
@ECHO OFF
COLOR 3E
SET A111="Documents and Settings"
SET A222=Users
SET /P PC=Enter Computer IP or HostName: 

@echo Opening Remote Folder....
if exist "" "\\%PC%\C$\"%A111%" (start "" "\\%PC%\C$\"%A111%") else (start \\%PC%\C$\%A222%)
PAUSE

I made a batch file to open some remote folders but there is a mistake I didn't notice.

After entering IP; I want to open, If there is remote "Documents and Settings" folder. But If there is no "Documents and Settings", I want to see "Users" folder.

Where is the error I make?

Thank you in advance...


\_(ツ)_/ twitter.com/serdaruzun

Need some help in building a PowerShell Script

$
0
0

I am in the process of setting up continuous self-auditing on a set of computers that are on a Domain. My company has a restriction on use of USB devices as well as CDs/DVDs. The domain pushes patches but we have been seeing some users that are using (or trying to) the network without becoming a part of the domain. My aim is to run a PowerShell script periodically (say, hourly) on each computer on the domain and dump certain parameters to XML / XHTML and then load these onto a web-server that can display the results in a (sort of) dashboard to flag anomalies like unauthorised USB use etc.

I know there must be some commercial products for this but the boss says "No" to a purchase. 

Am I on the right track or do I need to change my approach? Also, is there a starting scirpt available somewhere so that I can study it for techniques? My major problem is the display part. I am able to dump it into XML and (sort of ) format it but how do I collate the data and display it as a web-page is what is bothering me. Help would be deeply appreciated.


72|80004005|The_Microsoft_Jet_database_engine_cannot_open_the_file_''.__It_is_already_opened_exclusively_by_another_user__or_you_need_permission_to_view_its_data.|65|800a0035|File_not_found

$
0
0

Hi ,

Error Information: 72|80004005|The_Microsoft_Jet_database_engine_cannot_open_the_file_''.__It_is_already_opened_exclusively_by_another_user__or_you_need_permission_to_view_its_data.|65|800a0035|File_not_found

Am using a Microsoft Jet Oledb 4.0 connection to read data from a csv file using classic asp and Vbscript.

All the environments till the UAT are single server(Window 2003 server sp2)  and code was working fine 100 or 200 concurrent users.

While Pre-Prod servers are load balanced by network load balance. I am receiving this error when the code is deployed in dual nodes.

This very urgent as code should be moved to production asap



Start Application in Background

$
0
0

Hi,

Is there a way to start a programm in the background?

I want to run a VirtualBox in Headless mode without opening any window.

With a C#.Net Programm I archived it like this:

  myProcess.StartInfo.WorkingDirectory = @"C:\Program Files\Oracle\VirtualBox\";  myProcess.StartInfo.FileName = @"C:\Program Files\Oracle\VirtualBox\VBoxHeadless.exe";  myProcess.StartInfo.Arguments = string.Format("-s {0} -v on", args[0]); myProcess.StartInfo.CreateNoWindow = true;  myProcess.StartInfo.UseShellExecute = false; myProcess.Start();

Now I would like to do it with powershell, as I thought that it also should work as it is also .Net able ...

I used the Start-Process comand but I does not work.
I tried some combinations like this:

$str = @("-s","vmBox","-v","on");
Start-Process -FilePath "C:\Program Files\Oracle\VirtualBox\VBoxHeadless.exe" -ArgumentList $str -NoNewWindow -WorkingDirectory "C:\Program Files\Oracle\VirtualBox\"

But doing so, the program occupies the current powershell console and does not continue running when I close the terminal.

Is there a way to do so?


http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/3030821-allow-connecting-to-test-controller-using-differen <-- Vote for connecting with any user to Test Contrtoller


Add shared calendar to another users account using powershell

$
0
0

Hi,

I am trying to add a calendar to another using account using powershell as it will be easier to make a script than logging in to each user and adding the calendar. Has anyone done this before or know how to do it.

Thanks


Search Registry ValueName and its Value for a lot of subkeys

$
0
0

Hi guys,

I have one vb script for local printers:

Option Explicit
Const HKEY_LOCAL_MACHINE = &H80000002
Dim oReg : Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
Dim oShell : Set oShell = CreateObject("WScript.Shell")
Dim sPath, aSub, sKey, aSubToo, sKeyToo, StringValue, StringValue1

' Get all keys within sPath
sPath = "SYSTEM\CurrentControlSet\Control\Print\Printers"
oReg.EnumKey HKEY_LOCAL_MACHINE, sPath, aSub

' Loop through each key
For Each sKey In aSub
    ' Get all subkeys within the key 'sKey'
	oReg.GetStringValue HKEY_LOCAL_MACHINE, sPath & "\" & sKey , "Printer Driver", StringValue

	If StringValue = "MyOwnPrinterDriverName" Then
    Wscript.Echo "Test of " & sPath & "\" & sKey & "\" & sKeyToo & " = " & StringValue
	Wscript.Echo StringValue

	End IF

Next

For local printers there will be one reg value name "Printer Driver" and the value is my goal. This will work for local printers, but not for network printers, because network printer are located in another regkey "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Print\Providers\Client Side Rendering Print Provider\Servers\"PrinterName"\Printers\"ID"

The problem is, "Printer Name" and "ID" is unknown, so I need one script update, which will search all subkeys after "ID".

The main goal is to search for the printer name, and all what I have is his driver name :)

Thx for u help :)

Get-wbsummary FOReach

$
0
0

Hi, please help! i'm sooo close!
i run a FOREACH on the function below against 4 servers.  if one of the servers is offline i only get 3 results back, how do i make it spit out a row indicating 'Command Failed' or 'Server unavailable' for the 4th server? 

what i get now is an html table with:
PSComputerName  LastBackupTime           LastBackupResultDetailedHR
server1                 6/18/2014 1:30:05 AM      0
server2                 6/18/2014 1:00:14 AM      0
server4                 6/17/2014 9:30:31 PM      0

And what i want is an html table with:

PSComputerName  LastBackupTime           LastBackupResultDetailedHR
server1                 6/18/2014 1:30:05 AM      0
server2                 6/18/2014 1:00:14 AM      0
server3                 NO RESPONSE or Command Failed
server4                 6/17/2014 9:30:31 PM      0

_____________________________________________________________________
function Get-WBStats

{
BEGIN {}
Process
{
Invoke-Command -ScriptBlock {
                                get-wbsummary
                            } -computername $Servername -credential $Cred | select PSComputerName,LastBackupTime,LastbackupResultDetailedHR | sort pscomputername                           
}
END {}
}

Thank you, any help is appreciated.

MN

Viewing all 15028 articles
Browse latest View live