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

Powershell wait for an action

$
0
0

Hello,

i created this PS script

## IdentifyingNumber will be stored in a vraiable

$myApp = “7-z”
$app = Get-WmiObject win32_product | Where-Object {$_.name -match $myApp}

WAIT

$app.IdentifyingNumber
$appIN = $app.IdentifyingNumber

## Unisntallation

start msiexec.exe /X$appIN /qn

Where i put in WAIT the script should be stopped until the Get-Wim command is done.


Read XML file to dropdown list and sort alphabetically

$
0
0


I have a custom vbs script that reads a text file and creates a dropdown list to web page. How I can sort the list alphabetically? Should I read the values to array, sort it and after that put sorted values to dropdown list?


problem with record terminator on ftp'd files

$
0
0

Using Win7 Pro 64bit

This is not strictly a scripting issue, but it doesn't seem to fit neatly into any other forum, so I figured that there might be sufficient expertise here.

and I am doing this in a script ... ;-)

I ftp a plain text file from a linux server.  File gets proper record-delimiter translation.  Open the file with a hex editor and I can see the x'0D0A'.  But if I open the file in Notepad, it comes up as one long run-on line.  And if I try to process it with a vbscript, a Line Input command returns the entire file. 

I've done a lot of ftp across multiple systems (dos, Windows, OS/2, OS/MVS, various *nix) over many years, and have never seen anything like this.

Ideas?

Direct Report Lookup

$
0
0

Hi Scripting Guys,

I'm trying to search Active Directory (one specific user) so I can not only see all of this user's direct reports, but any of these accounts that have direct reports themselves.  Ideally, I'd like to output their email addresses rather than distinguished names.  This is causing me considerable grief and stress.  I'm hoping you can help.  I've included a script that I found which will give me the entire AD database, but I only need one user (manager).

Thanks

G

'========================

Option Explicit

Dim objRootDSE, strDNSDomain, adoCommand, adoConnection
Dim strBase, strAttributes

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

' Use ADO to search Active Directory.
Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Open "Active Directory Provider"
Set adoCommand.ActiveConnection = adoConnection
adoCommand.Properties("Page Size") = 100
adoCommand.Properties("Timeout") = 30
adoCommand.Properties("Cache Results") = False

' Search entire domain.
strBase = "<LDAP://" & strDNSDomain & ">"

' Comma delimited list of attribute values to retrieve.
strAttributes = "distinguishedName,directReports"

' Document organization.
Call Reports("Top", "")

' Clean up.
adoConnection.Close

Sub Reports(ByVal strManager, ByVal strOffset)
    ' Recursive subroutine to document organization.

    Dim strDN, adoRecordset, arrReports, strReport
    Dim strFilter, strQuery

    If (strManager = "Top") Then
        ' Search for all managers at top of organizational tree.
        ' These are objects with direct reports but no manager.
        strFilter = "(&(!manager=*)(directReports=*))"
    Else
        ' Output object that reports to previous manager.
        Wscript.Echo strOffset & strManager
        strOffset = strOffset & "    "
        ' Search for all objects that report to this manager.
        strFilter = "(manager=" & strManager & ")"
    End If

    ' Construct the LDAP query.
    strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"

    ' Run the query.
    adoCommand.CommandText = strQuery
    Set adoRecordset = adoCommand.Execute

    ' Enumerate the resulting recordset.
    Do Until adoRecordset.EOF
        ' Retrieve values.
        strDN = adoRecordset.Fields("distinguishedName").Value
        Wscript.Echo strOffset & strDN
        arrReports = adoRecordset.Fields("directReports").Value
        If Not IsNull(arrReports) Then
            For Each strReport In arrReports
                Call Reports(strReport, strOffset & "    ")
            Next
        End If
        adoRecordset.MoveNext
    Loop
    adoRecordset.Close

'==============

End Sub



Replacing entries in a csv file

$
0
0

Hi,

I am working on a code where I need to replace certain entries in a csv file. In the Get Content command, I need to use a wildcard for "Server". I tried replacing SERVER with * ,however that did not work. Any idea's, how this can be done.

TSR-SERVICE-MESSAGE ERROR SERVER@@"


Get-Content C:\VPS\TRH_VPS_DB.csv | ForEach-Object { $_ -replace "%CATD_I_066, serviceMessageTrap: errorMessage: TSR-SERVICE-MESSAGE ERROR SERVER@@", "" } | Set-Content C:\VPS\TRH_VPS_DB_1.csv

Thanks

Overwrite Parameter in Do loop

$
0
0

When I attempt to run the following function I am unable to overwrite the $nametocheck variable using read-host.  This is passed as a parameter and I want to return it for use in another function. The $mailboxes and $groups are arrays with groups and mailboxes from Office 365.

Function UserGroupCheck
{
param(
		[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
		[string] $nametocheck
	)
    $errorcheck = $error.count

    $mailboxes = get-mailbox
    $groups = Get-group

    
  
    Do{
         $endloop = $false

        
        If($mailboxes -contains $nametocheck){
            $endloop = $true}
        
        ElseIf($groups -contains $nametocheck){
            $endloop = $true}

        If($endloop -ne $true){
        Write-Output "Did you mean one of these?"

        $mailboxes -like "*$nametocheck*"
        $groups -like "*$nametocheck*"
        $nametocheck = Read-Host -Prompt 'Enter the correct name'
        }

    }while ($endloop -ne $true)

  
       If ($errorcheck -lt $error.count)
        {
            Write-Output "There seems to be a problem, Please check the error."
            Write-Output $error
            KeyPause
        } 

  return $nametocheck
}

silent batch file (no dos window)

$
0
0

Hello All,

I'm a newbie...

I have found this code in a forum (claiming it would make the .cmd or a .bat run invisible) But I don't how to make it work!!!

Where do I paste this code? in the batch file? beginning? end? what about the reference to "main.bat" do I replace that with the name of my batch file? Thanks in advc!

"---
Set WshShell = CreateObject("WScript.Shell")
cmds=WshShell.RUN("c:\main.bat", 0, True)
Set WshShell = Nothing"

Basically all I'm trying to do is silently execute a batch file to delete a specific file.

This is the content of my batch file:

ECHO OFF
Start /d "C:\" DEL aa.txt

Simple isn't it! It deletes the file BUT always opens a DOS prompt and I I have to close it manually :(

I've tried adding EXIT at the end of my batch file, but to no avail..I'm running this on WinXP

Thanks again for your help!


Using a variable in a Powershell search and replace string

$
0
0

Hi

a couple of days ago I posted a question about doing a search and replace with wildcards

Search and repalce with Widcards

I got a swift and very helpful answer but now I need to build on it.

In a text file I wanted to replace all the text between two defined words.  the script I got was this

$text = 'Some Server this bit of text varies Language stuff'
$text -replace '(.*Server) .+? (Language.*)','$1 it will always say this $2'

It works great but now I want to replace "it will always say this" with a variable and I can't figure out the correct grammar to make this happen.

Can anyone help??

Thanks

Alex



Last Windows Update except DefinitionUpdate for Microsoft Endpoint Protection

$
0
0

Heres the script

Set objSession = CreateObject("Microsoft.Update.Session")
Set objSearcher = objSession.CreateUpdateSearcher

Set colHistory = objSearcher.QueryHistory(1, 1)

For Each objEntry in colHistory
    Wscript.Echo "Title: " & objEntry.Title
    Wscript.Echo "Update application date: " & objEntry.Date
Next

I dont want any result about the definition update if thats that latest update that been installed...

Please thank you

How to determine which week it is in the month in PowerShell?

$
0
0

Hello,

I am writing a script that needs to name Excel spreadsheets based on the week of the month it is (i.e. Week 1, Week 2).

What would be a good way of doing this? I would consider Week 1 to be the first Monday of the month.

Thank you for your time.

Event Viewer Boot performance ID100 etc

$
0
0

Hi Scripting Guys,

Another question for you here....

I have a script to display boot performance for machines. I have been testing my script on Windows 7 and 8.1 and all works great!

We still have a number of XP workstations (slow migration) running and my script doesnt work because you can use the Get-Winevent on XP ahh!!

Could you take a look at the code and tell me if theres a way to get this working on XP... I can't even find the event in XP but I know your knowledge will guide me in the right direction.

$events = Get-WinEvent -FilterHashtable @{logname = "Microsoft-Windows-Diagnostics-Performance/Operational"}
#get the main details first
$eventtitle = $events[0]
$eventtitle |format-table -auto -wrap
#create ID value for file output
$id = $eventtitle | select-object ID 
# get the first event raw XML
$event = [xml]$events[0].ToXml()
# display its content
$event.Event.EventData.Data
#create table
$a = "<style>"
$a = $a + "BODY{background-color:White;}"
$a = $a + "TABLE{border-width: 1px;padding: 1px; border-style: solid;border-color: black;border-collapse: collapse;}"
$a = $a + "TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:thistle}"
$a = $a + "TD{width:250px;border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:PaleGoldenrod}"
$a = $a + "</style>"
#Get-Service | Select-Object Status, Name, DisplayName | 
#Set export1 - this will be for the high detial
$export1 = $event.Event.EventData.Data |Select-Object Name, "#text"| ConvertTo-HTML -fragment
#set export2 -  this will be for the short detial
$export2 = $eventtitle  |Select-Object ID, Message| ConvertTo-HTML -fragment
#start the convert to html
ConvertTo-HTML -head $a -body  "<H2>Boot Infomation for ($env:computername) $(Get-Date -Format 'dd/MM/yyy HH:mm tt') </H2> $export2 <p> $export1" -Title "Details"| 
Out-File C:\Scripts\"Startup_($env:computername)_$(Get-Date -Format 'dd_MM_yyy HH_mm tt') $id.html"
#Invoke-Expression C:\Scripts\Bootinfo.html
#To just get one line of code user the following
#  $event.SelectSingleNode("//*[@Name='BootStartTime']")."#text"

Thanks in advance!!


Joe

VBS: Cannot create folder under %systemroot%(C:\windows) in win8.1

$
0
0

I has two scripts to create folder under %systemroot%(C:\windows), It work fine in win7, but fail in win8.1(I had disabled uac.).  It also work when create folder under Drive C (C:\Mylogs) in win8.1

I use vbsedit to convert them to exe, run as administrator, ScriptA still fail, ScriptB work.

What's the difference between Win8.1 and Win7?

How can I use vbs script to create folder under %systemroot%(C:\windows) in win8.1?

 ScriptA   
set fso = CreateObject("Scripting.FileSystemObject")
CreateFullPath "%systemroot%\MyLogs"   

sub CreateFullPath (byval path)
 	set fso = CreateObject("Scripting.FileSystemObject")
	dim parent                             
	path   = fso.GetAbsolutePathname(path) 
	parent = fso.GetParentFolderName(path) 
	if not fso.FolderExists(parent) then   
	    CreateFullPath parent 
	end if
	if not fso.FolderExists(path) then     ' if necessary create subfolder
	   fso.CreateFolder(path)
	end if
end sub

ScriptB

Createfolder("%systemroot%\MyLogs")

Function CreateFolder(path) Dim Wsl,Fso Set Wsl=createobject("wscript.shell") set Fso = CreateObject("Scripting.FileSystemObject") path=Wsl.ExpandEnvironmentStrings(path) If Not Fso.FileExists(path) Then Wsl.Run "cmd /c md " & Chr(34) & path & Chr(34),0,True End If End Function



How do I know if the user is belong to Mail Restricted Group/s? Do anyone know how to do this in Powershell?

$
0
0

Hi Guys,

Good day, I'm new in powershell scripting. Will someone can help me about my problem?

Thanks.

Need help with writing data to file + formatting

$
0
0

I have created a script which the purpose is to grab everyone's mailbox in the environment and list their name, mailbox size, item count, last person to log on, last log on time and when it was created.  I'm going to use this to review mailboxes that have been in our environment for a while but have very little content.

The below script works.  I'm using "smith" as a test so that it pulls everyone who has smith in their display name.  

The problem I have is it out puts the data with the table headers every single time.  I'd like it if possible to just list the headers once and then output everyone's data below that.  


Secondly I need to pipe it out to a file (csv) so I can work with the data.  I've tried >, out-file and add-content but it either exports just one persons data or giberish.

$mailbox = get-mailbox -identity "*smith*"
foreach ($person in $mailbox){
$whencreated = $person.whencreated
Get-mailboxstatistics -Identity "$person" | ft displayname, totalitemsize, itemcount,lastloggedonuseraccount, lastlogontime,  @{Label="WhenCreated";Expression={$whencreated} } 

Deleteing folder for multiple users

$
0
0

Good morning all -

As most people would admit, I am terrible at scripting in any form.  In short, I need assistance with a dummy proof script to delete the contents of a folder for multiple (150+) users, without  having to touch each users profile.  I would prefer to be able to execute the script when needed.  This won't be listed as a scheduled task or setup as a netlogon. The path is as follows:

C:\Users\michael.jannise.ctr\NS5\tmp

It can either be set to delete the tmp folder entirely, or just the contents of the folder.  Which ever is easier. 

I would greatly appreciate any assistance provided!

Regards,

Michael


powershell script to monitor mcAfee status

$
0
0

Hi, 
I am very new to powershell. Is there any way through which we may monitor Mcafee update

scenario: if its not gettting updated and failing, we shall recive mail that update failed

i checked for the log file i.e C:\ProgramData\McAfee\DesktopProtection\Updatelog.txt

where all the logs are getting updated daily.

Anyway throgh which we may filter data from the text file and copy into another text file and filtering could be when it fails or the keyword"Update process failed". the same will be copied in another text file.

and in a way i can monitor the other text file.

and the text file is getting updated with timestamp

Sorting array with VBS

$
0
0

I am reading data from file to array with For Next loop. I get the data to array but when I try to pass this unsorted array to bubblesort function I get type mismatch error. I don't understand why.

'This causes type mismatch

arrTestArray = BubbleSort(arrTestArray)

Function BubbleSort(arrValues)

    Dim j, k, Temp
    For j = 0 To UBound(arrValues) - 1
        For k = j + 1 To UBound(arrValues)
            If (arrValues(j) > arrValues(k)) Then
                Temp = arrValues(j)
                arrValues(j) = arrValues(k)
                arrValues(k) = Temp
            End If
        Next
    Next
 BubbleSort = arrValues
End Function

HTA dropdown list default value

$
0
0

I have a VBS script that reads values from XML file and creates a dropdown list from those values. Everything works, but I want to automatically choose one of the values as default but still let the user change it if needed. This is simple question but I haven't been able to figure it out how to do this :(


Using Powershell as COMSPEC

$
0
0

Hi Folks,

I am trying to setup COMSPEC as powershell as default interpreter. This helps me to handle the situation if the current directory is an UNC for applications being launched using system(..).  We also have thirdparty tools for to support unix utilities under Windows. One of them is ls.exe.  In my testing, I found system("ls -al") was being picked from Powershell instead of the thirdparty directory which is already in PATH. Is there any way I can avoid using powershell alias through an environment variable? Or use a custom alias redirecting to thirdparty directory by an environment variable? Or is there any way to stop using alias from powershell and just use as interpreter by environment variable?

-Karthik


Karthik

How to Change the Screen Saver Settings to Mystify in Windows 7 using vbscript: disscussing reply...

$
0
0

just because jrv asked for it:

what specifically was beneficial in your post?

continuation of the thread.


Bob Blork - Mark as answer if it helped!

Viewing all 15028 articles
Browse latest View live


Latest Images

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