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

Using powershell executing a query on multiple SQL servers

$
0
0

HI ,

Can some one help me on below requirement

I want to execute a powershell script from my desktop which reads all other 5sql  servers data and dump to a table.

my desktop has sql server ( sql instance name: insta1, database name: testdb, table name: filesize)

5 sql server instances in text file( C:\servers.txt) -- 2000 and 2008 servers are exists

we need to run the below query and get the file size details on

if it is sql 2000 then query will be "select name,filename,size,maxsizefrommaster..sysaltfileswheredbid notin(1,2,3,4)

    else:  query will be "select name,physical_name,size,max_sizefrommaster.sys.master_files

so the above results needs to be loaded into insta1.testdb.filesize table.

Please help me on above requirement.

Thanks in advance.

From there I can send the results by dbsendmail .( I can work from this part)


-


Retreiving extended file properties - Company Name

$
0
0

Hello everyone,

I have been tasks with trying to document owner, author, and company name for each file on our network. I have had limited success using the code below but it doesn't seem to be getting the information from Office documents.

Dim arrHeaders(100)
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace("t:\test\")
For i = 0 to 100
 arrHeaders(i) = objFolder.GetDetailsOf(objFolder.Items, i)
Next
For Each strFileName in objFolder.Items
 For i = 0 to 100
 Wscript.Echo i & vbtab & arrHeaders(i) _& ": " & objFolder.GetDetailsOf(strFileName, i)
 Next
Next

Can anyone give me some pointers? I have trawled through countless scripting examples and they all seem to fall short of what I have been asked to do.

Thanks,

Matt

'How Can I Map a Drive Based on the Computer’s Subnet?' Question

$
0
0
Hey,

In the article on mapping a drive based on a computer's subnet, a brief mention is made about the difficulty of doing this with a PC that has two or more active NICs.  It was mentioned as something that the scripting guys would have to tackle in the future.  Well, there's no time like the present! :-)  (http://www.microsoft.com/technet/scriptcenter/resources/qanda/mar08/hey0304.mspx)

We're trying to deploy this script in our AD domain, but we do have many users with multiple NICs and our tests with these machines have not been positive.  Has anyone had any luck adjusting this script in that kind of circumstance?

Thanks!

John


Function and returned values

$
0
0

I have a function, listed below, that basically receives a list computer names and uses those values to identify all local profiles on such computers. These profiles (which basically is a string with several lines) then gets returned.

My issue is that I only get back the first line, or just one profile, instead of the entire list.

Basically, this is what $profile.LocalPath contains:

C:\Users\training01
C:\Users\glexp2
C:\Users\Administrator
C:\Windows\ServiceProfiles\NetworkService
C:\Windows\ServiceProfiles\LocalService
C:\WINDOWS\system32\config\systemprofile

I'd like to be able to return all these lines back to the calling portion.

This is how I'm calling that function:  $profilesFound = ListProfilesOnRemoteComputer ($machineName)

Thanks in advance!

Function ListProfilesOnRemoteComputer ($machineName)
{
    $foundProfiles = Get-WmiObject Win32_UserProfile -ComputerName $machineName

    # Initialize profile array
    $profile = @()
    
    ForEach ($profile in $foundProfiles)
    {
        return ,$profile.LocalPath
    }
}


Change with powershell 3

$
0
0

In v2 I have a profile script that sets aliases and starts programs after asking:

$app = Read-Host -prompt "Would you like to start daily use apps? [Anything but no starts apps]"

if($app -eq "no")
{
    Write-Host "Good Morning"
        
}
else
{
<Code to start apps>

}

After upgrading to v 3 the ise and cli both seem to choke on this read-host question

Why the change?  How can I implement in v 3? 

Thank you -

PS Script to Copy Report Files to SP List, Creating Folder Based on Part of FileName

$
0
0

I have a project where I need to populate an existing SharePoint library with reports each day from a file share.  The new report will overwrite existing reports (but not folder) and be put into folders, based on part of the report filename.

- Filename of report will be alphanumeric (ex.  Report_Location_City_01.00, or Report_Location_City_3287.00)

- Check to see if folder exists in SP document library, create if it doesn't exist.  

- Folder name will be based on report filename.  Report name needs to be stripped down to just numeric, removing leading zeros and anything after decimal.  Using example above, folders would be named "1" and "3287".  

                  - There is always an underscore before numeric.

                  - Numeric is always at end of name.

                  - The reports are not always sequential numbers.

                  - The report name may or may not have leading zeros in numeric portion.

                  - Cannot overwrite folders, but ok to overwrite report if it exists in folder

I have tried to approach this a couple different ways, but am not getting the results I need.   Any ideas are appreciated.



Help passing variables with GetNewClosure

$
0
0

I'm having trouble passing a variable to the remote workstation in a script. I would like the script to uninstall any program you enter for $program. This is what does work:

$computers = Get-Content 'C:\computerlist.txt'
foreach ($computer in $computers) {
Invoke-Command -ComputerName $computer -ScriptBlock { $app = Get-WmiObject -Class Win32_Product | Where-Object { 
    $_.Name -match "Java" 
}
$app.Uninstall()
}}


Now when I try to add in the $variable, I get errors:

$computers = Get-Content 'C:\computerlist.txt' $program = 'java' foreach ($computer in $computers) { Invoke-Command -ComputerName $computer -ScriptBlock {$app = Get-WmiObject -Class Win32_Product | Where-Object { $_.Name -match "$program" } $app.Uninstall() }}


I get the error:

Method invocation failed because [System.Object[]] doesn't contain a method named 'Uninstall'.+ CategoryInfo          : InvalidOperation: (Uninstall:String) [], RuntimeException+ FullyQualifiedErrorId : MethodNotFound+ PSComputerName        : computername

I know that the $program is not being passed to the remote computer and I need to use GetNewClosure, but I am having trouble getting this to work.




How to set password expiration date of Active Directory user (VBScript)

$
0
0

I am writing an application that communicates with Active Directory and I need to test how it behaves when the password of a user account in Active Directory has only a few days until its expiration date.

Therefore my question is: how can I set the password expiration date of a particular Active Directory user account to a date like "today + 2 days" (without changing the password expiration policy, of course!). I am looking for a way to do that using VBScript.

I have already tried this approach:

  • Using IADsUser::PasswordExpirationDate, see code example below: Problem: setting PasswordExpirationDate fails with error code 0x800A01BD. It only succeeds with value 0 ("expire now").

Code example:

'VBScript
strUserName = "test97" 
Set objUser = GetObject("LDAP://CN=" & strUserName & ",CN=Users,DC=mydomain,DC=com") 
dtmDate = Now+2 
objUser.PasswordExpirationDate = dtmDate 
objUser.SetInfo 
MsgBox "Successfully changed password expiration date" 



 


Delete certain files in subfolders

$
0
0

Guys,

Need help creating a script that deletes certain pst files I created that are in certain subfolders. So far this is what I have. Thanks in advance.

Dim file
Dim oFSO


'ON ERROR RESUME NEXT
Set oFSO = CreateObject("Scripting.FileSystemObject")


Set file = CreateObject("Scripting.FileSystemObject")
file.DeleteFile("I:\PST Data\2012\*\Careers.pst"), DeleteReadOnly

The PST data folder has two subfolders within it. 2012 and 2013. Within each of these are Month folders such as December,October, etc. Need to be able to remove a certain set of PST files from each month folder.


Christopher

VBS - Login Script for mapping with multiple NICs.

$
0
0

HI,

I tried this code for mapping drive with Multiple NICs, but i am getting this error.

set objNetwork = CreateObject("Wscript.Network")
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

Set colAdapters = objWMIService.ExecQuery _
    ("Select * From Win32_NetworkAdapterConfiguration Where IPEnabled=True")
i = 0 
	For Each objAdapter in colAdapters 
	    For Each strAddress in objAdapter.IPAddress 
	        arrOctets = Split(strAddress, ".") 
	        If arrOctets(0) <> "" Then  arrSubnets(i) = arrOctets(0) & "." & arrOctets(1) & "." & arrOctets(2) 
	            i = i + 1 
WScript.Echo arrSubnetIPs(i)
	        End If 
	    Next 
	Next 
	Set colItems = objWMIService.ExecQuery _ 
	    ("Select * From Win32_LogicalDisk Where DeviceID = 'G:'") 
If colItems.Count = 0 Then
For i = 0 To UBound(arrSubnets) 
Select Case strSubnet
       Case "10.1.1" 
            objNetwork.MapNetworkDrive "G:", "\\10.1.1.62\zShared",True
	    objNetwork.MapNetworkDrive "F:", "\\10.1.1.62\zShared2",True

        Case "10.1.20" 
            objNetwork.MapNetworkDrive "G:", "\\10.1.20.150\sharedch",True
	    objNetwork.MapNetworkDrive "F:", "\\10.1.20.150\sharedch1",True	
End Select
Next
End If


Sainyam Aggarwal MCTS



Change Owner/Permissions for folders with exceptions and then delete those Folders and content.

$
0
0

Hey Scripting Guy!! I have read, lots of posts about the same topic... not so good so far... this is what I need to do...

Under C:\Users\  -I have a lot users... I need to delete those folders/subfolders/files...
but I need to -Exclude some other folders like my own folder + Administrator + Default...
The problem is that the scrpt is ONLY working If I own all the Folders/SubFolders/Files

$FoldersC3P = "Default","Administrator"

Get-ChildItem "C:\Users" -Force | `
    Where-Object {$_.PsIsContainer -eq $true} | ForEach { If($FoldersC3P -notcontains $_.Name) { Remove-Item

-Recurse -Force $_.FullName }}

How can I change the Owner and get permissions of Folders/SubFolders and Files of all of them but -Exclude Folders AND CONTENT!
I don't want to change the files/folder owner under Default folder or some other Excluded folder...
I tried usign Get-Acl/Set-Acl with -Recurse (to get all the files/foldes) and -Exclude (to exclude the non needed files/foldes) without a good result.

Any suggestion for the Owner thing...
Thanks a lot!!!

How to Extract Folder and Sub Folder NTFS Access Rights For Share Drive (NAS)

$
0
0

Hey There!

Below powershell command extract users list for Root Folder(CALPROD) and its SubFolders and ALL its FILES under every folder.

What changes should i need to make to below script, to avoid/ignore FILE LEVEL Details(xml, tif,txt,img any file )?

Powershell Script(PS_PROD.ps1):

Get-ChildItem \\ABC.BANK.net\CALPROD -recurse | Where-Object { $_.PSIsContainer } get-acl | select-object path,owner,accesstostring,group | export-csv "C:\Temp\NASPROD.csv"

FYI:

1. I have Admin(Full Control) Access to this Share.

2. Subfolder of the path(\\ABC.BANK.net\CALPROD) contains xml, tif,txt,img etc

3. I only want to extract list users for Folders/Subfolders not for various type of files in it.

4. And with my script most of the times the csv file doesn't display full list of subfolder details beacuse it is flooded with file permisions.

Your Advise is Greatly Appreciated and rewarded :)


Bod

New-FsrmFileGroup Powershell cmdlet not running in 2008 R2, maybe i need to import something?

$
0
0

PS C:\Users\ns_service> New-FsrmFileGroup -Name "TUK_Media" -IncludePattern @(".aac", ".aif", ".aiff", ".asf", ".asx", "
.au", ".avi", ".divx", ".flac", ".m3u", ".m4v", ".mid", ".midi", ".mkv", ".mov", ".mp1", ".mp2", ".mp3", ".mp4", ".mpa",
 ".mpe", ".mpeg", ".mpeg2", ".mpeg3", ".mpg", ".ogg", ".qt")

The term 'New-FsrmFileGroup' is not recognized as the name of a cmdlet, function, script file, or operable program. Che
ck the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:18
+ New-FsrmFileGroup <<<<  -Name "TUK_Media" -IncludePattern @(".aac", ".aif", ".aiff", ".asf", ".asx", ".au", ".avi", "
.divx", ".flac", ".m3u", ".m4v", ".mid", ".midi", ".mkv", ".mov", ".mp1", ".mp2", ".mp3", ".mp4", ".mpa", ".mpe", ".mpe
g", ".mpeg2", ".mpeg3", ".mpg", ".ogg", ".qt")
    + CategoryInfo          : ObjectNotFound: (New-FsrmFileGroup:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

i'm sure you've been asked this before, what am i misssing

Running on Server 2008R2, /w File Services, FSRM and the relevant tools

thanks in advance :)


Amit



Have byte array, need to convert values to uint16, uint32

$
0
0

Howdy all,

I know I'm just being dense, but how do you convert specific bytes in an array to Uint16 or Uint32 variables?  I'm trying to do this with powershell.

I have a binary file that has some integer values imbedded into it at various offsets.  I can get the file into a byte array easily enough, but how do I extract a pair of bytes from it and convert that to a UInt16 value?  Additionally how about taking a UInt16 and making it back into a pair of bytes (even better: at a specific offset into an byte array)?

[Byte[]] $AByteArray = 0x0f, 0x00, 0x0e, 0x00

I'd like to read/convert bytes @ offset 2 & 3 into a UInt16 variable.

Clearly I need to worry about Endian-ness so 0x0e,0x00 is the integer value of 14

I'm considering a binary reader type of thing but seems like the [Byte].toUInt16 methods would do if I could figure out how to use them.

-greg

Hard Drive Rotational Speed

$
0
0
Need a command line or script to list rotational speed of local or remote system hard drives.  It would be nice to have it say: 5400RPM, 7200RPM, etc.

Powershell and connecting to WSUS (multiple domains)

$
0
0

I'm working on a script to clean up our WSUS databases. The script works great against the domain with the upstream WSUS server. The problem is that we have multiple domains, and I'm not sure how to access them using just one script.

How would I go about modifying the code below, to use different credentials? Is there a way to setup the Windows Credential Manager to automatically pick the correct credential?

I would prefer not to store the password (secure or otherwise) in a text file, but I'm not 100% opposed.

Here is the code:

# WSUS Connection Parameters:
[Boolean]$useSecureConnection = $False
#[Int32]$portNumber = 8530
[Int32]$portNumber = 80
$PrimaryWSUSServer = “mnusinvctgwsus.managed.local”
$BeginScriptTime = Get-Date

# First Pass Variables
# Decline updates that have not been approved for 30 days or more, are not currently needed by any clients, and are superseded by an approved update.
[Boolean]$FirstPassSupersededUpdates = $False
# Decline updates that aren’t approved and have been expired my Microsoft.
[Boolean]$FirstPassExpiredUpdates = $False
# Delete updates that are expired and have not been approved for 30 days or more.
[Boolean]$FirstPassObsoleteUpdates = $True
# Delete older update revisions that have not been approved for 30 days or more.
[Boolean]$FirstPassCompressUpdates = $True
# Delete computers that have not contacted the server in 30 days or more.
[Boolean]$FirstPassObsoleteComputers = $False
# Delete update files that aren’t needed by updates or downstream servers.
[Boolean]$FirstPassUnneededContentFiles = $False

# Second Pass Variables
[Boolean]$SecondPassSupersededUpdates = $False
[Boolean]$SecondPassExpiredUpdates = $False
[Boolean]$SecondPassObsoleteUpdates = $False
[Boolean]$SecondPassCompressUpdates = $False
[Boolean]$SecondPassObsoleteComputers = $False
[Boolean]$SecondPassUnneededContentFiles = $True

# Third Pass Variables
[Boolean]$ThirdPassSupersededUpdates = $True
[Boolean]$ThirdPassExpiredUpdates = $True
[Boolean]$ThirdPassObsoleteUpdates = $False
[Boolean]$ThirdPassCompressUpdates = $False
[Boolean]$ThirdPassObsoleteComputers = $True
[Boolean]$ThirdPassUnneededContentFiles = $False

# Clean the Primary WSUS Server
# Load the Required .NET assembly
[void][reflection.assembly]::LoadWithPartialName(“Microsoft.UpdateServices.Administration”)

$servers = "wsus.domain1.local","wsus.domain2.local","wsus.domain3.local"

# Loop through all DownStream Servers
foreach ($server in $servers)
{
	$Wsus = ""
	# Connect to the WSUS Server
	Try {
		$Wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::getUpdateServer($server,$useSecureConnection,$portNumber)
	}
	Catch [System.Management.Automation.MethodInvocationException] {
		$errorMessage = $_.Exception.Message
		If ($errormessage.tostring() -eq 'Exception calling "GetUpdateServer" with "3" argument(s): "The request failed with an empty response."') {
			Write-Host "Error on port 80, trying 8530 for" $server
			Try {
				$Wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::getUpdateServer($server,$useSecureConnection,"8530")
			}
			Catch {
				$errorMessage = $_.Exception.Message
				If ($errormessage.tostring() -eq 'Exception calling "GetUpdateServer" with "3" argument(s): "The request failed with HTTP status 401: Unauthorized."') {
					Write-Host "Need different creds for" $server
				}
				Else {
					Write-Host "Port 8530 failed. The error is:" $errormessage
				}
			}
		}
		ElseIf ($errormessage.tostring() -eq 'Exception calling "GetUpdateServer" with "3" argument(s): "The request failed with HTTP status 401: Unauthorized."') {
			Write-Host "Need different creds for" $server
		}
		Else {
			Write-Host "Unknown error message for" $server
		}
	}
	If ($Wsus) {
		Write-Host "Connected to" $server
	}
}

Thanks.

Formatting multiple outputs of Cmdlets into a single HTML email

$
0
0

The object of the code is to get a summary list of events from the Windows Event Log and then produce a detailed list of each entry from the Windows event logs.  Later I will enhance the code to only get the detailed records of very specific entries.  My problem is in formatting the output of the detailed records.  Here is the Code:

$EventLog = "Application"
$NewestEvents = 10
$Events = get-eventlog -LogName $Eventlog -newest $newestEvents

#SMTP server name 
$smtpServer = "Your.smtp-server"
#Creating a Mail object
$msg = new-object Net.Mail.MailMessage

#Creating SMTP server object
$smtp = new-object Net.Mail.SmtpClient($smtpServer)

#Email structure
$msg.From = "Youraddress@yourdomain"
$msg.ReplyTo = "Youraddress@yourdomain"
$msg.To.Add("Youraddress@yourdomain")
$msg.subject = "From Powershell"
   
$body2 = ($events | group-object -property source -noelement | sort-object -property count –descending | ConvertTo-HTML -property count,name)    
$body2 += foreach ($Event in $events)
                  {$event | select-object -property EventID, MachineName,Categoy, EntyType, Message, Source, TimeGenerated |
                        ConvertTo-HTML -property EventID, MachineName,Categoy, EntyType, Message, Source, TimeGenerated } 
 
$msg.body = $body2
$msg.IsBodyHTML = $true

#Sending email
$smtp.Send($msg)

The output looks like this:

countname
2ESENT
2Windows Search Service
1LightScribeService
1gupdate
1Bonjour Service
1iPod Service
1SeaPort
1Intuit Update Service
EventIDMachineNameCategoyEntyTypeMessageSourceTimeGenerated
3044DEN2008The gatherer index resumed. Context: Application, SystemIndex Catalog Windows Search Service9/4/2013 8:45:54 PM
EventIDMachineNameCategoyEntyTypeMessageSourceTimeGenerated
0DEN2008The description for Event ID '0' in Source 'iPod Service' cannot be found. The local computer may not have the necessary registry information or message DLL files to display the message, or you may not have permission to access them. The following information is part of the event:'Service started/resumed'iPod Service9/4/2013 8:45:53 PM
EventIDMachineNameCategoyEntyTypeMessageSourceTimeGenerated
1003DEN2008The Windows Search Service started. Windows Search Service9/4/2013 8:45:50 PM

The problem is each of the detailed rows ends up as a seperate table, with each row having the "headers".  What I would like instead is one set of headers for all of the detailed rows (with the values falling under their correct headers for all rows).

Is this possible?

reset the mailbox quota through script/powershell

$
0
0

Hello friends, Using exchange 2010 Sp2

I have AD group called “Advance Users” in which there are 700 users whose mailbox are set to Issues warning at (MB) - 525 and Prohibit send at (MB) – 550 now we are going to increase the default mailbox size limit to 1 GB for all; so my query is how can I change the settings of those 700 users so that they can get the limits from database instead of what we had set manually with the help of Ad group.

If I will remove all the users from the group then they won’t get the default database settings as the option “Use mailbox database defaults “ are unchecked for all those 700 users so is there any way through script I can change the setting for all 700 users so that they can get the default mailbox settings.

Read a comma delimited file in vbs and ignoring the last line

$
0
0

I got a text file like this.

 

BeginWord, Word1, Word2, Word3, Word4, Word5, Word6

Word, Word1, Word2, Word3, Word4, Word5, Word6

Word, Word1, Word2, Word3, Word4, Word5, Word6

End

I want to read the whole file and only get the first word and the last word of each line, but when my code reaches the last line I get an error (OutofBound??) due to "End" in an Array of 0-6.

My code is not finished but you kind of get what I mean.

Const ForReading = 1
 
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("c:\Read.txt", ForReading)

 

Do Until objTextFile.AtEndOfStream
    strNextLine = objTextFile.Readline
    arrServiceList = Split(strNextLine , ",")
 
 
    output = output & "Process name: " & arrServiceList(0) & "QUE Length: " & arrServiceList(6) & vbCrLf
   
 Wscript.Echo output
   
Loop

 

Copy Last six Months data from NAS Folder

$
0
0

HI All,

 We have a lots of folders by date and millions of small files in thoes folders.  \\NAS\Recordings  So i want to copy last six months data to a another location and backup. backing up this NAS folder take 3 days.

Pls help me to create the script to copy. Then i can backup those 6 months data to a tape.

As

Viewing all 15028 articles
Browse latest View live


Latest Images

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