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

ActiveX Windows Script Host Error 800A01AD

$
0
0

Hello,

The following error occurs when running a script through a command prompt of a program I am using: 

Windows Script Error

Error: ActiveX component can't create object: 'synergy.Synergy'

Code: 800A01AD

Source: Microsoft VBScript runtime error

I found the following 'bug' listed for Windows XP, however I am using a Windows 7 64-bit computer. http://support.microsoft.com/kb/311269/en-us

Could this bug have carried over from XP?

Thank you!


Powershell - SNMP Service Install (Server 2008)

$
0
0

Hello, so this is a follow up to the assistance that was provided to me yesterday about checking to see if the SNMP service was installed across multiple servers.  I was able to gather a list of devices that require the SNMP service to be installed, and (thankfully) most of them are Server 2008 machines.  The pre-2008 machines I will just hit manually, since there are less than 20 of them, and to minimize confusion, and a lack of powershell knowledge from my side.

I have approximately 120 servers that will require the service to be installed onto them, and was looking to do this via powershell.  Luckily, I was able to find this great script online, and I have tested it with my own variables inserted, and it works great (for one server, ran manually on it).  I was wondering if somebody could help me figure out how to get the script to do the following two things:

1.  Install the SNMP service to multiple servers from a text file (I attempted this with the get-content).
2.  Output the results to either a text file or a csv file (also tried this as can be seen below).

Here is the script, with what I tried (and failed).  The only two lines of code that are mine, are the very top one and the very bottom one, I will bold them to indicate that.  Thanks for any help that may be offered.

    #Powershell Script To Install SNMP Services (SNMP Service, SNMP WMI Provider)
     
    Get-Content .\servers.txt
    #Variables :)
    $pmanagers = "MY VARIABLE 1"
    $commstring = "MY VARIABLE 2"
         
    #Import ServerManger Module
    Import-Module ServerManager
     
    #Check If SNMP Services Are Already Installed
    $check = Get-WindowsFeature | Where-Object {$_.Name -eq "SNMP-Services"}
    If ($check.Installed -ne "True") {
            #Install/Enable SNMP Services
            Add-WindowsFeature SNMP-Services | Out-Null
    }
     
    ##Verify Windows Servcies Are Enabled
    If ($check.Installed -eq "True"){
            #Set SNMP Permitted Manager(s) ** WARNING : This will over write current settings **
            reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\SNMP\Parameters\PermittedManagers" /v 1 /f /t REG_SZ /d localhost | Out-Null
            #Used as counter for incremting permitted managers
            $i = 2
            Foreach ($manager in $pmanagers){
                    reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\SNMP\Parameters\PermittedManagers" /v $i /f /t REG_SZ /d $manager | Out-Null
                    $i++
                    }
            #Set SNMP Community String(s)- *Read Only*
            Foreach ( $string in $commstring){
                    reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\SNMP\Parameters\ValidCommunities" /v $string /f /t REG_DWORD /d 4 | Out-Null
                    }
    }
    Else {Write-Host "Error: SNMP Services Not Installed"}| Export-Csv .\SNMP_Install.csv -NoTypeInformation

Powershell Issue

$
0
0

I have the following script I am testing and cannot get it to format correctly.

When I run everything from the Sort lline up it works as it should with the grouping.

When I run the entire script the html file created looks terrible and no legible information as below.

Can anyone help.

$a = "<style>"
$a = $a + "BODY{background-color:peachpuff;}"
$a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$a = $a + "TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;}"
$a = $a + "TD{border-width: 1px;padding: 0px;border-style: solid;border-color: black;}"
$a = $a + "</style>"



Get-ADComputer -Filter * -Properties * | 
select Name,OperatingSystem,OperatingSystemServicePack | 
Sort-Object Name | Format-Table Name,OperatingSystem -GroupBy OperatingSystem -AutoSize |
ConvertTo-Html |
out-file C:\scripts\test.html

THIS IS THE FILL RUN HTML SAMPLE

ClassId2e4f51ef21dd47e99d3c952918aff9cdpageHeaderEntrypageFooterEntryautosizeInfoshapeInfogroupingEntry
033ecb2bc07a4d43b5ef94ed5a35d280Microsoft.PowerShell.Commands.Internal.Format.AutosizeInfoMicrosoft.PowerShell.Commands.Internal.Format.TableHeaderInfo
9e210fe47d09416682b841769c78b8a3Microsoft.PowerShell.Commands.Internal.Format.GroupingEntry
27c87ef9bbda4f709f6b4002fa4af63c
27c87ef9bbda4f709f6b4002fa4af63c
27c87ef9bbda4f709f6b4002fa4af63c
27c87ef9bbda4f709f6b4002fa4af63c
27c87ef9bbda4f709f6b4002fa4af63c
4ec4f0187cb04f4cb6973460dfe252df
9e210fe47d09416682b841769c78b8a3Microsoft.PowerShell.Commands.Internal.Format.GroupingEntry
27c87ef9bbda4f709f6b4002fa4af63c
4ec4f0187cb04f4cb6973460dfe252df
9e210fe47d09416682b841769c78b8a3Microsoft.PowerShell.Commands.Internal.Format.GroupingEntry
27c87ef9bbda4f709f6b4002fa4af63c
27c87ef9bbda4f709f6b4002fa4af63c

Using Task Scheduler for a powershell script on server 2008

$
0
0
I have a powershell script I am trying to run as a scheduled task, but I cannot get it to run. if I run in from within powershell or in an elivated command prompt it runs fine. Task Scheduler says it completes, but nothing happens. Here is the action I am using in Task Scheduler:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noninteractive -nologo -command "& {d:\backup\createVM.ps1}"

I do have powershell set to "allsigned" and my script is signed. (it was a pain to do , but I decided the added security was worth it)
I have also tried running it as System and the local admin, but that does not seem to matter.

Powershell script calling batch file, how to "echo" or otherwise pass in two or more values asked for by batch file

$
0
0

I've been having a lot of problems trying to get an old batch file we have laying around, to run from my powershell script. The batch file actually asks for two inputs from the user. I've managed to put together a powershell that echos a response, but of course, that only will answer one of the prompts. As usual, I've simplified things here to get my testing done. The batch file looks like this:

@ECHO OFF
SET /P CUSTID=Customer Number:

SET /P DBCOUNT=Number of Live Databases:

ECHO Customer Id was set to : %CUSTID%
ECHO Database Count was set to : %DBCOUNT%

Two inputs, two echos to verify values have been set. Now, the powershell looks like this:

Param(
 [string]$ClientADG,
    [string]$ClientDBCount,
    [scriptblock]$Command
)

$ClientADG = '1013'
$ClientDBCount = '2'
$Response = $ClientADG + "`r`n" + $ClientDBCount

$Command = 'Invoke-Command -ComputerName localhost -ScriptBlock {cmd /c "echo ' + $ClientADG + ' | E:\Scripts\Setup\Company\DatabaseSetupTest.bat"}'

powershell -command $Command

Output looks like:

Customer Number: Number of Live Databases: Customer Id was set to : 1013
Database Count was set to :

As expected, as I'm only passing in one value. I can't figure out how to get a second value passed in for the second prompt. Instead of $ClientADG, I tried to mash the two value together in the $Response variable with a cr/lf or a cr or a lf in between, but no go there either. The first input gets set to the second value, and second input is blank still. In the essence of time, I need to get this batch file called from Powershell to get some folks productive while I actually rewrite what the batch file does in another powershell, so it can be integrated into other things. (I'm automating what a bunch of people spend hours doing into multiple scripts and eventually one BIG script so they can focus on doing their real jobs instead).

How do I get this right in powershell? I don't want to modify the batch file at all at this point, just get it running from the powershell.

Thanks in advance!

mpleaf

Batch Script using System Varriable for Hostname and FQDN results in large space between

$
0
0

I have a batch script running on Windows 7 that I've created to help a physical computer, connect to his virtual cousin.  Problem is when I try to make it use the FQDN (required by the View Client) it puts a large space between the hostname and the domain.

Result

ECHO Connecting View Client to PREFIX-SERIAL .domain.com

OR

"C:\Program Files\VmWare\View.exe" -Args -serverURL PREFIX-SERIAL       .domain.com


Our computers are named a combination of a prefix and the serial number.  Our virtual computer names are the same, but with a different prefix.  So my attempt was to make a connection script, using the computer serial number.  My Process:

Setting %serial% variable.

for /F "skip=1 tokens=*" %%b in ('wmic bios get serialnumber') do if not defined serial set serial=%%b

Set %hostname% variable.

set hostname=PREFIX-%serial%

Installation command line

"C:\Program Files\VmWare\View.exe" -Args -serverURL %hostname%.domain.com

That results in the output at the beginning of my post.

I've also tried

%hostname%.%userdomain%.com

PREFIX-%serial%.%userdomain%.com

PREFIX-%serial%.domain.com

SET FQDN=.domain.com
PREFIX-%serial%%FQDN%

%hostname%%FQDN%

I also tried carets and quotes on set commands without any improvement.

I'm sure I'm missing something simple here.  Any advise?


There's no place like 127.0.0.1



Temp files deletion on log off

$
0
0

Hi Guys,

I was wondering if someone can provide me a script for me to have ran automatically on log off so all my temp un-needed files are deleted. I am on a windows 7 client.

I have tried to run various scripts on log off but none execute at all, one script I used is below, but if that can be fixed or a better one that works can provided that would be much appreciated.

cleanmgr /sageset:99
del /q /s "C:\Users\Ted\AppData\Local\Temp\*.*"
del /q /s "C:\Windows\Temp\*.*"
del /q /s "C:\Temp\*.*"
cleanmgr /sagerun:99

Editing security settings in Dcom Configuration

$
0
0

Hi

Is there a way I can edit dcom Configuration objects via powershell

I have to change an object in:

Component services->Computers->This computer->Dcom-Configuration->{objectname}

I haven't found much on this... 

any help will be severely appreciated!


Kindest regards, Martin


Vbscript

$
0
0

Hello does this code still work in windows7?

Iget this error:

WinsockObject Error!Script will exit now.

client.vbs



'
' CLIENT WINSOCK VBSCRIPT
'
' NOTES: (FEBRUARY 19, 2007)
'
' Delays are required where they are located,
' or it sends data too quick, and errors.
' 
' Uses Port 80 by default.
' IP and Port are user settings.
'
' Creates a Log file.
' c:\WSClient.log
'
' this only sends basic text, no long essays or files.
' for that, it would require some minor but required changes.
'

Option Explicit
Dim winsock, SendData, RecieveData, secs

'****** CHANGE THESE SETTINGS *********

Const RemoteHost           = "192.168.0.100"
Const RemotePort           = 80

'***************************************

Const sckClosed            = 0 '// Default. Closed 
Const sckOpen              = 1 '// Open 
Const sckListening         = 2 '// Listening 
Const sckConnectionPending = 3 '// Connection pending 
Const sckResolvingHost     = 4 '// Resolving host 
Const sckHostResolved      = 5 '// Host resolved 
Const sckConnecting        = 6 '// Connecting 
Const sckConnected         = 7 '// Connected 
Const sckClosing           = 8 '// Peer is closing the connection 
Const sckError             = 9 '// Error 

MsgBox "Client Started."
WriteData Now & " - Client Started"

'// CREATE WINSOCK
On Error Resume Next
Set winsock = Wscript.CreateObject("MSWINSOCK.Winsock", "winsock_")
If Err.Number <> 0 Then
    MsgBox "Winsock Object Error!" & vbCrLf & "Script will exit now."
    WriteData Now & " - Winsock Object Error."
    WScript.Quit
End If
On Error Goto 0

'// CONNECT NOW
winsock.RemoteHost = RemoteHost
winsock.RemotePort = RemotePort 
winsock.Connect
        
'// MAIN DELAY - WAITS FOR CONNECTED STATE
'// SOCKET ERROR RAISES WINSOCK ERROR SUB
while winsock.State <> sckError And winsock.state <> sckConnected And winsock.state <> sckClosing And secs <> 25
    WScript.Sleep 1000  '// 1 sec delay in loop
    secs = secs + 1     '// wait 25 secs max
Wend

'// CONNECTION TIMED OUT
If secs > 24 Then
    MsgBox "Timed Out"
    WriteData Now & " - Client Timed Out"
    ClientClose()
End If

'// SEND DATA NOW
winsock.SendData "Test" 

'// WAIT INCASE NO RESPONSE
Wscript.Sleep 25000
WriteData Now & " - Client No Response. Winsock State: " & winsock.state
ClientClose()

'// WINSOCK DATA ARRIVES
Sub winsock_dataArrival(bytesTotal)
    Dim strData
    winsock.GetData strData, vbString
    RecieveData = strData 
    WriteData Now & " - Client Recieved: " & RecieveData
    winsock.SendData "Test"  
    WScript.Sleep 1000
    WriteData Now & " - Client Sent Data"
    ClientClose()
End Sub

'// WINSOCK ERROR
Sub winsock_Error(Number, Description, SCode, Source, HelpFile, HelpContext, CancelDisplay)
    MsgBox "Cient Error: " & Number & vbCrLf & Description
    WriteData Now & " - Cient Error: " & Number & ". " & Description
    ClientClose()
End Sub

'// EXIT SCRIPT
Sub ClientClose()
    If winsock.state <> sckClosed Then winsock.Close
    Set winsock = Nothing
    WriteData Now & " - Client Closed."
    Wscript.Quit
End SUb

'// CREATE LOG ENTRY
Function WriteData(Data)
    Dim fso, file
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set file = fso.OpenTextFile("C:\WSClient.log", 8, True)
    file.write Data & vbCrLf
    file.Close
    Set file = Nothing
    Set fso = Nothing
End Function

server.vbs




'
' SERVER WINSOCK VBSCRIPT
'
' NOTES: (FEBRUARY 20, 2007)
'
' Delays are required where they are located,
' or it sends data too quick, and errors.
' 
' Listens on Port 80 by default.
' Port is user setting.
'
' Creates a Log file.
' c:\WSServer.log
'
' if winsock not registered it will try to register
' if winsock ocx is in path it will register
' if cannot register it will error and quit
'
' server listens for connection from client
' server Receives connection from client
' server checks data received from client
' server sends reply to client if data valid
' server closes whether valid or invalid
' server listens for more connections
'
' this only receives basic text, no long essays or files.
' for that, it would require some minor but required changes.
'

Option Explicit
Dim winsock

'****** CHANGE THESE SETTINGS *********

Const LocalPort            = 80
Const DataToReceive        = "Test"

'***************************************

Const sckClosed            = 0 '// Default. Closed 
Const sckOpen              = 1 '// Open 
Const sckListening         = 2 '// Listening 
Const sckConnectionPending = 3 '// Connection pending 
Const sckResolvingHost     = 4 '// Resolving host 
Const sckHostResolved      = 5 '// Host resolved 
Const sckConnecting        = 6 '// Connecting 
Const sckConnected         = 7 '// Connected 
Const sckClosing           = 8 '// Peer is closing the connection 
Const sckError             = 9 '// Error 

MsgBox "Start Server"
WriteData Now & " - Server Started"

'********* CREATE & CONNECT **********

'// CREATE WINSOCK
On Error Resume Next
Set winsock = Wscript.CreateObject("MSWINSOCK.Winsock", "winsock_")
If Err.Number <> 0 Then
    '// REGISTER WINSOCK IF ERROR
    WriteData Now & " - Registering Winsock"  '// log action
    Set winsock = Nothing
    If RegWinsock = False Then
        '// REGISTER ERROR SO EXIT
        MsgBox "Winsock Object Error!" & vbCrLf & "Script will exit now."
        WriteData Now & " - Winsock Object Error."
        WScript.Quit
    Else
        Set winsock = Wscript.CreateObject("MSWINSOCK.Winsock", "winsock_")
    End If
End If
On Error Goto 0

'// LISTEN NOW
winsock.LocalPort = LocalPort
ServerListen

'********* WAIT FOR EVENTS ***********

'// MAIN DELAY - INFINITE LOOP

'// SOCKET ERROR RAISES WINSOCK ERROR SUB
while winsock.State <> sckError
    WScript.Sleep 200
Wend

'// JUST INCASE
ServerClose()

'********** WINSOCK EVENTS ***********

'// WINSOCK CONNECT REQUEST // CONNECTED
Sub winsock_ConnectionRequest(requestID)
    If winsock.State <> sckClosed Then
        winsock.Close
    End If
    winsock.Accept requestID
    WriteData Now & " - Server Requested ID: " & requestID
    WScript.Sleep 1000  '// REQUIRED OR ERRORS
End Sub

'// WINSOCK DATA ARRIVE // GET DATA AND SEND REPLY
Sub winsock_dataArrival(bytesTotal)
    Dim strData: strData = ""
    WriteData Now & " - Server Data Arrives"
    winsock.GetData strData, vbString
    WriteData Now & " - Server Received: " & strData
    Select Case CStr(strData)
        Case DataToReceive
            winsock.SendData DataToReceive
            WriteData Now & " - Server Sent Reply: " & DataToReceive
        Case Else
            WriteData Now & " - Invalid Data Received"
    End Select
    WScript.Sleep 2000  '// REQUIRED OR ERRORS
    ServerListen()
End Sub

'// WINSOCK ERROR // ERROR SO EXIT
Sub winsock_Error(Number, Description, SCode, Source, HelpFile, HelpContext, CancelDisplay)
    MsgBox "Server Error " & Number & vbCrLf & Description
    WriteData Now & " - Server Error: " & Number & ". " & Description
    ServerClose()
End Sub

'******** COMMON PROCEDURES **********

'// LISTEN FOR REQUEST
Sub ServerListen()
    If winsock.State <> sckClosed Then
        WriteData Now & " - Server Closed (Listen)"
        winsock.Close
    End If
    WriteData Now & " - Server Listen"
    winsock.Listen
End SUb

'// EXIT SCRIPT
Sub ServerClose()
    If winsock.state <> sckClosed Then winsock.Close
    Set winsock = Nothing
    WriteData Now & " - Server Closed."
    Wscript.Quit
End SUb

'// CREATE LOG ENTRY
Function WriteData(Data)
    Dim fso, file
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set file = fso.OpenTextFile("C:\WSServer.log", 8, True)
    file.write Data & vbCrLf
    file.Close
    Set file = Nothing
    Set fso = Nothing
End Function

'******** REGISTER WINSOCK **********

Function RegWinsock()
    Dim RegCmd, RegOcx, TmpOcx
    If CheckObject("MSWINSOCK.Winsock", "winsock_") Then
        RegWinsock = True
        Exit Function
    End If
    RegOcx = SystemDirectory & "\MSWINSCK.OCX"
    TmpOcx = ScriptPath & "\MSWINSCK.OCX"
    RegCmd = "regsvr32.exe /s " & RegOcx
    If Not FileExists(TmpOcx) Then Exit Function
    If FileCopy(TmpOcx, RegOcx) = False Then Exit Function
    If FileExists(RegOcx) = False Then Exit Function
    If ShellCmd(RegCmd) = False Then Exit Function
    If CheckObject("MSWINSOCK.Winsock", "winsock_") Then
        RegWinsock = True
    End If
End Function

'// SHELL COMMAND PROMPT
Function ShellCmd(ByVal pCmd)
    Dim ShellWsck, Rtrn
    On Error Goto 0: On Error Resume Next
    Set ShellWsck = CreateObject("WScript.Shell")
    Rtrn = ShellWsck.Run(pCmd, 0, True)
    If Rtrn = 0 Then
        If Err = 0 Then ShellCmd = True
    End If
    Set ShellWsck = Nothing
    On Error Goto 0
End Function

'// GET THIS SCRIPT PATH
Function ScriptPath()
    On Error Goto 0: On Error Resume Next
    ScriptPath = CreateObject("Scripting.FileSystemObject")._
        GetParentFolderName(Wscript.ScriptFullName)
    On Error Goto 0
End Function

'// GET WINDOWS SYSTEM DIRECTORY
Function SystemDirectory()
    Dim objFso
    On Error Goto 0: On Error Resume Next
    Set objFso = CreateObject("Scripting.FileSystemObject")
        SystemDirectory = objFso.GetSpecialFolder(1)
    Set objFso = nothing
    On Error Goto 0
End Function

'// COPY A FILE
Function FileCopy(ByVal pFile1, ByVal pFile2)
    Dim objFso
    On Error Goto 0: On Error Resume Next
    Set objFso = CreateObject("Scripting.FileSystemObject")
        If objFSO.FileExists(pFile2) Then
            If Err = 0 Then FileCopy = True    
            Exit Function
        End If
        If objFSO.FileExists(pFile1) Then
            objFso.CopyFile pFile1, pFile2
            If Err = 0 Then FileCopy = True
        End If
    Set objFso = nothing
    On Error Goto 0
End Function

'// FILE EXISTS
Function FileExists(ByVal pFile)
    Dim objFSO
    On Error Goto 0: On Error Resume Next
    Set objFSO = CreateObject("Scripting.FileSystemObject")
        If objFSO.FileExists(pFile) = True Then
            If Err = 0 Then FileExists = True
        End If
    Set objFSO = Nothing
    On Error Goto 0
End Function

'// CHECK IF OBJECT IS REGISTERED
Function CheckObject(ByVal pObj, ByVal pAram)
    Dim objTemp
    On Error Goto 0: On Error Resume Next
    If Len(pAram) <> 0 Then
        Set objTemp = WScript.CreateObject(pObj, pAram)
    Else
        Set objTemp = CreateObject(pObj)
    End If
    If Err = 0 Then CheckObject = True
    Set objTemp = Nothing
    On Error Goto 0
End Function

VBScript to read the content of a .csv file and delete old files mentioned in the .csv

$
0
0

I have a Windows 2003 file server.

I have generated a report in .csv format, about the files which are older than 1 year.

I need a VBScript to read the .csv file and delete the files which are enlisted there.

Can someone please help me with this?

vbscript for outlook signature not work with office 2013

$
0
0
hi,
i wrote a script that set a new mail signature for my company users.
my code use a word doc as a template and change some key-words to another (user name, title and more).
it work great with office 2010 and 200, i have a problem with 2013. sometimes it work fine but sometimes my script fail to change the key-word.

my code:

On Error Resume Next '================================================== 'Create Outlook signature from Word template '================================================== 'search text and replace function Sub SearchAndRep(searchTerm, replaceTerm, objWord) objWord.Selection.GoTo 1 With objWord.Selection.Find .ClearFormatting .Replacement.ClearFormatting .MatchWholeWord = True .Text = searchTerm .Execute ,,,,,,,,,replaceTerm End With End Sub '----- Declarations ----- Const wdWord = 2 Const wdParagraph = 4 Const wdExtend = 1 Const wdCollapseEnd = 0 '-------------------------------------------------------------- '----- Modify these variables appropriately ---- '-------------------------------------------------------------- strTemplatePath = "\\DOMAINNAME\SYSVOL\scripts\" strTemplateName = "SignTemplate.docx" '----- Connect to AD and get user info -----' Set objSysInfo = CreateObject("ADSystemInfo") Set WshShell = CreateObject("WScript.Shell") strUser = objSysInfo.UserName Set objUser = GetObject("LDAP://" & strUser) strName = objUser.FullName strTitle = objUser.Title strPhone = objUser.TelephoneNumber strMobile = objUser.Mobile strCompany = objUser.Company strEmail = objUser.mail strWeb = objuser.wWWHomePage '----- Apply any modifications to Active Directory fields ----- '----- Open Word template in read-only mode {..Open(filename,conversion,readonly)} ----- Set objWord = CreateObject("Word.Application") objWord.Visible = FALSE Set objDoc = objWord.Documents.Open(strTemplatePath & strTemplateName,,False) Set objEmailOptions = objWord.EmailOptions Set objSignatureObject = objEmailOptions.EmailSignature Set objSignatureEntries = objSignatureObject.EmailSignatureEntries '----- Replace template text placeholders with user specific info ----- SearchAndRep "[Name]", strName, objWord SearchAndRep "[Title]", strTitle, objWord if strCompany = ("blabla LTD") then SearchAndRep "[Company]", strCompany, objWord Else SearchAndRepDel objWord End if SearchAndRep "[Phone]", strPhone, objWord SearchAndRep "[Mobile]", ("M: " & strMobile), objWord SearchAndRep "[email]", strEmail, objWord '----- Replace template hyperlink placeholders with user specific info ----- 'SearchAndRepHyperlink "[email]", strWeb, objDoc 'SearchAndRepHyperlink "[web]", strWeb, objDoc '----- Set signature in Outlook ----- Set objSelection = objDoc.Range() objSignatureEntries.Add "Default", objSelection objSignatureObject.NewMessageSignature = "Default" 'see note below if a different reply signature is desired objSignatureObject.ReplyMessageSignature = "Default" '----- Close signature template document ----- objDoc.Saved = TRUE objDoc.Close objWord.Quit '-----close outlook----- Set objOutlook = CreateObject("Outlook.Application") objOutlook.Quit '----- Subrouting to search and replace template hyperlink placeholders ----- ' Note this can be picky...if it does not work re-create hyperlink in the template 'Sub SearchAndRepHyperlink(searchLink, replaceLink, WordDoc) ' Set colHyperlinks = WordDoc.Hyperlinks ' For Each objHyperlink in colHyperlinks ' If objHyperlink.Address = searchLink Then ' objHyperlink.Address = replaceLink ' End If ' Next 'End Sub '---sub for solar---- Sub SearchAndRepDel(objWord) objWord.Selection.GoTo 1 With objWord.Selection.Find .ClearFormatting .Wrap = wdFindStop .Text = "[Company]" Do While .Execute objWord.selection.Bookmarks("\Line").Range.Delete Loop End With End Sub


any idea?
TNX

NTFS File Permissions PowerShell Error

$
0
0

I keep getting this message after the $aclsepminetpub.AddAccessRule($accessrulesepminetpub), as well as sepminetpubreporting and sepmhome and symhome:

Exception calling "AddAccessRule" with "1" argument(s): "Some or all identity references could not be translated."

I thought it was the System account but I don't get the error with the other ACLs. Can anyone see any issues? Thanks!
#Users
$objUserSystem = New-Object System.Security.Principal.NTAccount("NT AUTHORITY\SYSTEM")
$objUserNetworkService = New-Object System.Security.Principal.NTAccount("NT AUTHORITY\Network Service")
$objUserAdministrators = New-Object System.Security.Principal.NTAccount("BUILTIN\Administrators")
$objUserUsers = New-Object System.Security.Principal.NTAccount("BUILTIN\Users")
#
#Gets ACL for appdataphp
$appdataphpdir = "C:\Users\All Users\Symantec\Symantec Endpoint Protection Manager\Php"
$aclappdataphp = Get-Acl $appdataphpdir
#Clears appdataphp ACL by un-inheriting permissions
$aclappdataphp.SetAccessRuleProtection($True, $False)
#Access rule to assign permissions to appdataphp
$accessruleappdataphp = New-Object system.security.AccessControl.FileSystemAccessRule("$objUserAdministrators", "FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
$aclappdataphp.AddAccessRule($accessruleappdataphp)
$aclappdataphp | Set-Acl $appdataphpdir
#
#Gets ACL for appdataphptemp
$appdataphptempdir = "C:\Users\All Users\Symantec\Symantec Endpoint Protection Manager\Php\Temp"
$aclappdataphptemp = Get-Acl $appdataphptempdir
#Clears appdataphptemp ACL by un-inheriting permissions
$aclappdataphptemp.SetAccessRuleProtection($True, $False)
#Access rule to assign permissions to appdataphptemp
$accessruleappdataphptemp = New-Object system.security.AccessControl.FileSystemAccessRule("$objUserAdministrators", "FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
$aclappdataphptemp.AddAccessRule($accessruleappdataphptemp)
$aclappdataphptemp | Set-Acl $appdataphptempdir
#
#Gets ACL symhome
$symhomedir = "C:\Symantec"
$aclsymhome = Get-Acl $symhomedir
$aclsymhomespecial = Get-Acl $symhomedir
#Clears symhome ACL by un-inheriting permissions
$aclsymhome.SetAccessRuleProtection($True, $False)
#Access rule to add permissions to symhome
$accessrulesymhome = New-Object system.security.AccessControl.FileSystemAccessRule("$objUserAdministrators, $objUserSystem", "FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
$aclsymhome.AddAccessRule($accessrulesymhome)
$aclsymhome | Set-Acl $symhomedir
#Access rule special permissions to symhome
$accessrulesymhomespecial = New-Object system.security.AccessControl.FileSystemAccessRule("$objUserUsers", "ReadAndExecute", "ContainerInherit, ObjectInherit", "None", "Allow")
$aclsymhomespecial.AddAccessRule($accessrulesymhomespecial)
$aclsymhomespecial | Set-Acl $symhomedir
#
#Gets ACL sepmhome
$sepmhomedir = "C:\Symantec\Symantec Endpoint Protection Manager"
$aclsepmhome = Get-Acl $symhomedir
$aclsepmhomespecial = Get-Acl $symhomedir
#Clears sepmhome ACL by un-inheriting permissions
$aclsepmhome.SetAccessRuleProtection($True, $False)
#Access rule to add permissions to sepmhome
$accessrulesepmhome = New-Object system.security.AccessControl.FileSystemAccessRule("$objUserAdministrators, $objUserSystem", "FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
$aclsepmhome.AddAccessRule($accessrulesepmhome)
$aclsepmhome | Set-Acl $sepmhomedir
#Access rule special permissions
$accessrulesepmhomespecial = New-Object system.security.AccessControl.FileSystemAccessRule("$objUserUsers", "ReadAndExecute", "ContainerInherit, ObjectInherit", "None", "Allow")
$aclsepmhomespecial.AddAccessRule($accessrulesepmhomespecial)
$aclsepmhomespecial | Set-Acl $sepmhomedir
#
#Gets ACL sepmdata
$sepmdatadir = "C:\Symantec\Symantec Endpoint Protection Manager\Data"
$aclsepmdata = Get-Acl $sepmdatadir
$aclsepmdataspecial = Get-Acl $sepmdatadir
#Clears sepmdata ACL by un-inheriting permissions
$aclsepmdata.SetAccessRuleProtection($True, $False)
#Access rule to add permissions to sepmdata
$accessrulesepmdata = New-Object system.security.AccessControl.FileSystemAccessRule("$objUserAdministrators, $objUserSystem", "FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
$aclsepmdata.AddAccessRule($accessruleappdataphp)
$aclsepmdata | Set-Acl $sepmdatadir
#Access rule special permissions
$accessrulesepmdataspecial = New-Object system.security.AccessControl.FileSystemAccessRule("$objUserNetworkService", "Modify", "ContainerInherit, ObjectInherit", "None", "Allow")
$aclsepmdataspecial.AddAccessRule($accessrulesepmdataspecial)
$aclsepmdataspecial | Set-Acl $sepmdatadir
#
#Gets ACL sepminetpub
$sepminetpubdir = "C:\Symantec\Symantec Endpoint Protection Manager\Inetpub"
$aclsepminetpub = Get-Acl $sepminetpubdir
#Clears sepminetpub ACL by un-inheriting permissions
$aclsepminetpub.SetAccessRuleProtection($True, $False)
#Access rule to add permissions to sepminetpub
$accessrulesepminetpub = New-Object system.security.AccessControl.FileSystemAccessRule("$objUserAdministrators, $objUserSystem", "FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
$aclsepminetpub.AddAccessRule($accessrulesepminetpub)
$aclsepminetpub | Set-Acl $sepminetpubdir
#
#Gets ACL sepminetpubreporting
$sepminetpubreportingdir = "C:\Symantec\Symantec Endpoint Protection Manager\Inetpub\Reporting"
$aclsepminetpubreporting = Get-Acl $sepminetpubreportingdir
#Clears sepminetpubreporting ACL by un-inheriting permissions
$aclsepminetpubreporting.SetAccessRuleProtection($True, $False)
#Access rule to add permissions to sepminetpubreporting
$accessrulesepminetpubreporting = New-Object system.security.AccessControl.FileSystemAccessRule("$objUserAdministrators, $objUserSystem", "FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
$aclsepminetpubreporting.AddAccessRule($accessrulesepminetpubreporting)
$aclsepminetpubreporting | Set-Acl $sepminetpubreportingdir
#End
$Exit-PSSession

Write-Output - Log File

$
0
0

Hello,

Please see my script. Should be able to understand how it works, if not, let me know. I want to create a log file which basically says, it didn't apply.

$FFTest = Test-Path "$env:userprofile\AppData\Local\Mozilla\Firefox\Profiles"
if ($FFTest -eq $false){

New-Item -Path "$env:userprofile\AppData\Local\Mozilla\Firefox\Profiles\CSTEMP.default"
New-Item -Path "$env:userprofile\AppData\Roaming\Mozilla\Firefox\Profiles\CSTEMP.default"

Copy-Item -Path "\\server\install\Browsers\CS\Firefox\CSTEMP.default\*" -Destination "$env:userprofile\AppData\Local\Mozilla\Firefox\Profiles\CSTEMP.default" -Recurse
Copy-Item -Path "\\server\install\Browsers\CS\Firefox\CSTEMP.default\*" -Destination "$env:userprofile\AppData\Roaming\Mozilla\Firefox\Profiles\CSTEMP.Default" -Recurse
Copy-Item -Path "\\server\install\Browsers\CS\Firefox\Config\profiles.ini" -Destination "$env:userprofile\AppData\Roaming\Mozilla\Firefox" -Recurse
}
else {
   #log file
}


$ChromeTest = Test-Path "$env:userprofile\AppData\Local\Google\Chrome\User Data\Default"
if ($ChromeTest -eq $false){

New-Item -Path "$env:userprofile\AppData\Local\Google\Chrome\User Data\Default"

Copy-Item -Path "\\server\install\Browsers\CS\Chrome\Default\*" -Destination "$env:userprofile\AppData\Local\Google\Chrome\User Data\Default" -Recurse
}
else {
 #log file

}

Any help would be appreciated.

Kind regards,

Sam Colman

Clear, own und use TPM 2.0 on Windws 8.1 via Powershell

$
0
0

Hallo,

I´m looking for information on how to completely setup tpm via PowerShell, some sort of walk through. The goal is to script equal behavior as if to prep and clear the tpm in the tpm.msc and thereafter setting the system up to use tpm and pin for Bit locker, encrypt the system volume and save all information to AD.

Unfortunately the mange-bde commands to handle tpm are no longer good for Windows 8.1 as I had to find out.

Additional information:

  • TPM and Bit locker GPOs are set and double checked.
  • Schema is extended.
  • The provisioning works fine manually and with wizards.

Any info is welcome any help appreciated!

How to use UDL file in Powershell script?

$
0
0

Hello Scripting Guys,

I have a VBScript that works great for connecting to an Oracle DB using a .UDL file. Here is the important part of the script:

Set dataconnect = CreateObject("ADODB.Connection")
	Path= "File name=C:\UDLs\TEST.udl"
	dataconnect.ConnectionString = Path
	dataconnect.open

		Set oCmd = CreateObject("ADODB.Command")
		oCmd.ActiveConnection = dataconnect

		oCmd.CommandText = "SYSTEM.JOB.INSERT_JOB"
		oCmd.CommandType = 4

		set oParam = oCmd.CreateParameter("job_name_val")
			oParam.type = 200
			oParam.direction = 1
			oParam.size = 255
			oParam.value = job_name
			oCmd.Parameters.Append oParam
		set oParam = oCmd.CreateParameter("description")
		        oParam.type = 200
			oParam.direction = 1
			oParam.size = 4000
			oParam.value = descrip
			oCmd.Parameters.Append oParam
		set oParam = oCmd.CreateParameter("status_val")
			oParam.type = 200
			oParam.direction = 1
			oParam.size = 50
			oParam.value = status
			oCmd.Parameters.Append oParam
		oCmd.Execute

As you can see, it creates "ADODB.Connection" and "ADODB.Command" objects. Everything works as intended here.

Now, I'm trying to convert this VBScript to a Powershell script.

Here's what I have so far with my PowerShell Script (non-working, but no errors):

$job_name = $args[0]
$status = $args[1]
$descrip = $args[2]


write-host "Job Name = " $job_name
write-host "Status = " $status
write-host "Description = " $descrip

#Create an object of type: ADODB class: Connection
$objConn = New-Object -com "ADODB.Connection"

#Create Connection String
$connString = "File name=C:\UDLs\TEST.udl"

#Open the connection
$objConn.open($connString)

#Command Object
$oCmd = New-Object -com "ADODB.Command"

#Assign DB connection To Command
$oCmd.ActiveConnection = $objConn

#Set Command text
$oCmd.CommandText = "SYSTEM.JOB.INSERT_JOB"

#Set Command Type
$oCmd.CommandType = 4

#Create parameter list For Command
#Job name Parameter	
$oParam1 = $oCmd.CreateParameter("job_name_val")
	$oParam1.type = 200
	$oParam1.direction = 1
	$oParam1.size = 255
	$oParam1.value = $job_name
	#Append parameter list
	$oCmd.Parameters.Append($oParam1)

#Description Parameter	
$oParam2 = $oCmd.CreateParameter("description")
	$oParam2.type = 200
	$oParam2.direction = 1
	$oParam2.size = 4000
	$oParam2.value = $descrip
	#Append parameter list
	$oCmd.Parameters.Append($oParam2)	

#Status Parameter
$oParam3 = $oCmd.CreateParameter("status_val")
	$oParam3.type = 200
	$oParam3.direction = 1
	$oParam3.size = 50
	$oParam3.value = $status
	#Append parameter list
	$oCmd.Parameters.Append($oParam3)

#Command Execution	
$oCmdX	= $oCmd.Execute

write-host $oCmdX

#Cleanup
#Set parameters = To NULL
$oParam1 = $null
$oParam2 = $null
$oParam3 = $null
#Set Command = To NULL
$oCmd = $null
#Close DB object
$objConn.Close()	


So, not too many changes with the syntax, but it doesn't actually send the ADODB Command to the Database. I have also tried hardcoding the connection string, but no luck there either. Am I not using the right syntax with the Command object? I am fairly new to both of these languages, so I appreciate any help/suggestions you can offer!

Thank you,

Brian


How do I determine what mointors are applied to an Agent

$
0
0

I am a powershell novice but my powershell knowledge is much better than my sql knowledge.

I am repeatedly asked, what are you monitoring on that server or this server or that group of servers? I would really like to have a relatively quick way of answering that without having to go thru the rules that the group has written, and check those against the server groups and come up with an answer.

We are running SCOM 2012 SP1. I did find 2 refs (which I can't post until they verify my account)

One is from Stefan Stranger ( a 2007 script) one is from Technet (List All Monitors and Rules per Group of Servers) and the 3rd deals with export-scomeffectivemonitoringconfiguration.

With the first two, I am not yet skilled enough to convert that to Scom 2012. With the last one, even the example fails when I try and run it, even when removing the } that errors at the end.

Has anyone else set something up using powershell to determine this in a Scom 2012 environment?

Thanks

-Dre

Formatting output to CSV

$
0
0

I'm looking for some help with my script that I have.

The process in how it works is as follows,

1. Gather all computer objects within a domain (dnshostname)

2. Ping test to see which ones are up and active.

3. For each active computer

 3.1 Print the hostname

 3.2 query the objects Sid,sAMAccountName, etc information

 3.3 Print the output from Get-LocalAcctInfo into a text file.

4. Repeat

Here's the code I'm using, I know it's not perfect but it's a work in progress.

function Get-LocalAcctInfo {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        $ComputerName
    )
    Process {
        Foreach ($Computer in $ComputerName) {
            Try {
                Add-Type -AssemblyName System.DirectoryServices.AccountManagement
                $PrincipalContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext([System.DirectoryServices.AccountManagement.ContextType]::Machine, $Computer)
                $UserPrincipal = New-Object System.DirectoryServices.AccountManagement.UserPrincipal($PrincipalContext)
                $Searcher = New-Object System.DirectoryServices.AccountManagement.PrincipalSearcher
                $Searcher.QueryFilter = $UserPrincipal
                $computer
                $Searcher.FindAll() | Format-List -Property Sid,SamAccountName,Enabled,LastPasswordSet,PasswordNotRequired,PasswordNeverExpires,UserCannotChangePassword
                }
            Catch {
                Write-Warning -Message "$($_.Exception.Message)"
            }
        }
    }
}


$rtn = $null
$count = 0

Get-ADComputer -Filter * |
ForEach-Object {
    if((Test-Connection -CN $_.dnshostname -Count 1 -Buffersize 16 -quiet) -match 'True') 
    {
    write-host -ForegroundColor green $_.dnshostname
    Get-LocalAcctInfo $_.dnshostname | Out-File C:\Users\UserAccount\Desktop\results.txt -append
    $count = $count + 1
    }
    else
    {
    write-host -ForegroundColor red $_.dnshostname
    }  
}

write-host $count " hosts are active and were enumerated on the domain."


What I'm trying to accomplish is to have the computer name along with the account information formatted nicely within a csv file. 

I have working code that is able to place all the information about the computer object within a csv when I use the following within my function and code.

$Searcher.FindAll() | Where-Object {$_.Sid -Like "*-*"}

...

Get-SWLocalAdmin $_.dnshostname | Export-Csv C:\Users\adsecure_rstrong\Desktop\text.csv


The output of the code that I pasted in the code block above is the following

"computername.domain.com

Sid                      : S-1-5-21-1213413474-1213434134760-84413413436-500
SamAccountName           : Administrator
Enabled                  : True
LastPasswordSet          : 1/1/2014 8:27:20 PM
PasswordNotRequired      : False
PasswordNeverExpires     : False
UserCannotChangePassword : False"

I'd like the computername to be placed with the rest of the output and in csv format


Any suggestions or recommendations are welcome. I'm new to Powershell and learning/teaching myself along the way. Note, that my original code works but I'd rather put it into a csv file so I can easily filter out different columns.

Thanks,

Rob.

powershell not mapping drive from bat file

$
0
0

Once again, this GREATLY dumbed down to simplify the error. I have a bat file that maps a local drive from a UNC share. Contents of my bat file (map.bat) are:

net use Z: "\\myserver\e$\apps\Data" /USER:mydomain\myuser mypass

The bat file works flawlessly, and I can then look at my Z: files from windows explorer. When I run the bat file from a powershell command, it says it completes successfully, yet I cannot see the Z: drive. Contents of my powershell are:

Invoke-Command-ComputerNamelocalhost-ScriptBlock{E:\Scripts\Setup\Company\Map.bat}

This makes no sense to me at all. If the bat works, why wouldn't the powershell?

mpleaf

DSC error: Cannot invoke the SendConfigurationApply method. The SendConfigurationApply method is in progress

$
0
0

Hello,

I ran a DSC configuration script, it seemed to hang, and I received an error that I can't find a resolution for anywhere:

"Cannot invoke the SendConfigurationApply method. The SendConfigurationApply method is in progress and must return before SendConfigurationApply can be invoked."

I'm experimenting with creating a deployment package with Desired State Configuration.  Huge thanks to Jacob Benson for his wonderful DSC journal, which has helped me enormously to work through problems caused by Microsoft's sparse DSC documentation.  I read the Day 11 post and was able to then proceed as described below to attempt to use a script to install a few utilities.

I have a configuration script that, first, recursively copies a File (directory type) Resource to a folder.  The script follows:

#Requires -version 4.0

Configuration NG_BackendDSC
{
param (
  [String[]]$ComputerName = $env:COMPUTERNAME
  ,
  $ReleaseSourcepath = "d:\download\ng"
  ,
  $NGTargetPath = 'd:\ng_backend'
   
)

Node $ComputerName
{
  File BackendInstallationFiles
  {
   Ensure = "Present"
  
   SourcePath = (Join-Path $ReleaseSourcepath '7.0\ng_backend')

   DestinationPath = $NGTargetPath
  
   Type = "Directory"
  
   Recurse = $true

  }
 
  Log AfterDirectoryCopy
        {
            # The message below gets written to the Microsoft-Windows-Desired State Configuration/Analytic log
            Message = "Finished running the file resource with ID BackendInstallationFiles"
            DependsOn = "[File]BackendInstallationFiles" # This means run "BackendInstallationFiles" first.
        }
# ... [package resources follow here as described below]
} # End configuration block

The Configuration script then continues with a Package Resource to install 7Zip and another for Winmerge:

Package 7Zip
{
DependsOn = '[File]BackendInstallationFiles'
  
Ensure = "Present"

Path = (Join-Path $ReleaseSourcepath 'Utilities\7z457-x64.msi')

Name = '7-Zip'

ProductID = '23170F69-40C1-2702-0457-000001000000'

LogPath = (Join-Path $ReleaseSourcepath '7zip_dsc.log')
}

Package WinMerge
{
DependsOn = '[File]BackendInstallationFiles'
  
Ensure = 'Present'

Path =  (Join-Path $ReleaseSourcepath 'Utilities\WinMerge-2.14.0-Setup.exe')

Name = 'WinMerge'

ProductID = ''

LogPath = (Join-Path $ReleaseSourcepath 'winmerge_dsc.log')
}

There are three more packages:

Package NotePadPlus
{
DependsOn = '[File]BackendInstallationFiles'
  
Ensure = 'Present'

Path =  (Join-Path $ReleaseSourcepath 'Utilities\npp.6.5.5.Installer.exe')

Name = 'Notepad++'

ProductID = ''

LogPath = (Join-Path $ReleaseSourcepath 'notepadplus_dsc.log')
}

Package FileZilla
{
DependsOn = '[File]BackendInstallationFiles'
  
Ensure = 'Present'

Path =  (Join-Path $ReleaseSourcepath 'Utilities\FileZilla_3.7.4.1_win32-setup.exe')

Name = 'FileZilla FTP Client'

ProductID = ''

LogPath = (Join-Path $ReleaseSourcepath 'FileZilla_dsc.log')
}

Package AgentRansack
{
DependsOn = '[File]BackendInstallationFiles'
  
Ensure = 'Present'

Path =  (Join-Path $ReleaseSourcepath 'Utilities\AgentRansack_820.exe')

Name = 'Agent Ransack'

ProductID = ''

LogPath = (Join-Path $ReleaseSourcepath 'Agent_Ransack_dsc.log')
}

At the end of the script, after the closing Configuration bracket, I create the MOF files and start off the implementation of the configuration:

    ng_backendDSC -OutputPath d:\dsc\MOF
    Start-DscConfiguration -Wait -Path d:\dsc\MOF -Verbose

I executed the script within the ISE.

The directory copy happened fine.  7zip was already installed, so DSC noticed this and skipped it.

Winmerge then began to install.  I waited a half-hour, but the script did not finish.  In fact Winmerge did install, which I could see from the Start Menu, but the log file 'winmerge_dsc.log' was only just created and has zero bytes.

Here's all I got from the verbose comments:
VERBOSE:  [[Package]WinMerge] The package WinMerge is not installed
VERBOSE: [[Package]WinMerge] Package configuration starting

I clicked the Stop button in the ISE.  The status bar says "Stopping" but not "Stopped."

I closed the ISE and checked the Event log (Diagnostics/Applications and Services Logs/Microsoft/Windows/Desired State Configuration.  There's an entry for the starting of the script and one for the ending of the script.  Both logs have the same message:

Job {66685F9E-D242-4A6C-9CA5-DD47AED6B62B} : 
Configuration is sent from computer NULL by user sid S-1-5-21-2621261384-2063666624-962377667-1000.

Great.  Nothing helpful there.  There was no debug log even though analytic and debug logging are enabled as described here.

I've seen scripts hang the ISE before, so I tried running the script from the PowerShell console.  As I had dreaded, I saw this output:

VERBOSE: Perform operation 'Invoke CimMethod' with following parameters, ''methodName' =
SendConfigurationApply,'className' = MSFT_DSCLocalConfigurationManager,'namespaceName' =
root/Microsoft/Windows/DesiredStateConfiguration'.
Cannot invoke the SendConfigurationApply method. The SendConfigurationApply method is in progress and must return before SendConfigurationApply can be invoked.
    + CategoryInfo          : NotSpecified: (root/Microsoft/...gurationManager:String) [], CimException
    + FullyQualifiedErrorId : MI RESULT 1
    + PSComputerName        : QAIDD7

VERBOSE: Operation 'Invoke CimMethod' complete.
VERBOSE: Time taken for configuration job to complete is 0.557 seconds

I had dreaded this because I have seen this before.  Jason's blog is so far just about the sole page on the Internet that I have found that even mentions this error.  When he saw it, it went away by itself.  When I first saw it on a different server, I waited several days and rebooted the server and still saw the message, preventing me from doing any other DSC script runs.

Before running this script, I had created a snapshot of the virtual machine, so I can recover, but I tried rebooting the server.  It's a Windows 2008 R2 machine by the way.  I understand that DSC is not PowerShell.  That only makes it more difficult to figure out ways to troubleshoot the underlying technology, when there is no helpful output into logs.

After the reboot, the "SendConfigurationApply method is in progress and must return before SendConfigurationApply can be invoked" error still came up, strangely.  The output recommends using -Force in this case, so I changed the command to delete the -Wait and add -Force:

Start-DscConfiguration -Wait -Path d:\dsc\MOF -Verbose

Cool.  The script seems to run this time:
HasMoreData     : True
StatusMessage   : Running
Location        :  Server1
StartParameters : {}
Command         : Start-DscConfiguration -Force -Path d:\dsc\MOF -Verbose
JobStateInfo    : Running
Finished        : System.Threading.ManualResetEvent
InstanceId      : 9282f535-6026-49eb-932b-c4cd58e3f815
Id              : 4
Name            : Job4
ChildJobs       : {Job5}
PSBeginTime     : 3/20/2014 2:33:16 PM
PSEndTime       :
PSJobTypeName   : ConfigurationJob
Output          : {}
Error           : {}
Progress        : {}
Verbose         : {}
Debug           : {}
Warning         : {}
State           : Running

VERBOSE: Time taken for configuration job to complete is 0.077 seconds

So what's a scripter to do?  Microsoft recommends using the -Wait, but the script won't run unless I use -Force instead.

I am still not seeing anything in the winmerge log file.  I ran a Get-Job | FormatList and see the job is still in the Running state:

HasMoreData     : True
StatusMessage   : Running
Location        : Server1
StartParameters : {}
Command         : Start-DscConfiguration -Force -Path d:\dsc\MOF -Verbose
JobStateInfo    : Running
Finished        : System.Threading.ManualResetEvent
InstanceId      : 9282f535-6026-49eb-932b-c4cd58e3f815
Id              : 4
Name            : Job4
ChildJobs       : {Job5}
PSBeginTime     : 3/20/2014 2:33:16 PM
PSEndTime       :
PSJobTypeName   : ConfigurationJob
Output          : {}
Error           : {}
Progress        : {}
Verbose         : {}
Debug           : {}
Warning         : {}
State           : Running

I then ran receive-job -id 4 -Keep.  No output at all.

Get-Job did show a ChildJobs property, so I tried Get-Member on it but didn't receive anything I can use.

PS D:\> get-job | select childjobs | gm

   TypeName: Selected.System.Management.Automation.ContainerParentJob

Name        MemberType   Definition
----        ----------   ----------
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
ChildJobs   NoteProperty System.Collections.Generic.List`1[[System.Management.Automation.Job, System.Management.Auto...

Get-Command *config* turned up a Get-DSCConfiguration cmdlet.  Sounds promising.  I was stopped by the same error as before:

get-dscconfiguration :Cannot invoke the GetConfiguration method. The SendConfigurationApply method is in progress and must return before GetConfiguration can be invoked.
At line:1 char:1
+ get-dscconfiguration
+ ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (MSFT_DSCLocalConfigurationManager:root/Microsoft/...gurationManager) [Get-DscConfiguration], CimException
    + FullyQualifiedErrorId : MI RESULT 1,Get-DscConfiguration


I can revert the VM, but I don't know how to proceed from here.  Is Winmerge installer not compatible with DSC?  How can I reset the Configuration Agent if rebooting doesn't do it? TIA!


Scott Saari

VBscript - Enter a value (variable windows) on the path of downloading the installation file

$
0
0

Hello All,

My name is Diego and i need so much help with this VBscript,

The script works well but I just need to call (SRV) windows System variable

that contains the name of the local server.

All client machines (winxp) already have a system variable name (SRV) with

value (name of local server)for example SRVADS001, because in our environment

we have many offices with low-speed links, so need to get the download installation  file on the local serverr, so we avoid bandwidth consumption.

How i can Call SRV Variable and puts it on path
FULL_INSTALL_PATH = (INSTALL_PATH & STR_PARAMETERS) ?

I need that the installation path of the file is correct to all offices, each office has a local server defined on Windows XP variable System :

INSTALL_PATH = Chr (34) & "\\SRV (Variable)\Agent\AgInstall.exe" & Chr (34)


FY = The SRV variable just contains the name of local server, do not contain \\

 

VBscript

' Variable Declarations
'==================================
Dim ipAddress, agentVersion, dataPath, xmlDoc, ElemList, regExist
Dim REQUIRED_AGENT_VERSION
Dim REQUIRED_SERVER_IP
Dim INSTALL_PATH
Dim STR_PARAMETERS
Dim FULL_INSTALL_PATH

'======================================
' MUST CHANGE VARIABLES IN THIS SECTION
'======================================
REQUIRED_AGENT_VERSION="4.6.0"
REQUIRED_SERVER_IP="192.168.1.100:12300"
INSTALL_PATH = Chr(34) & "\\Server\NETLOGON\AgInstall.exe" & Chr(34)
STR_PARAMETERS = " /FORCEINSTALL /INSTALL=AGENT /INSTDIR=" & Chr(34) &

"%PROGRAMFILES%\Framework\" & Chr(34) & " /SILENT"
FULL_INSTALL_PATH = (INSTALL_PATH & STR_PARAMETERS)

'======================================
' END CHANGE VARIABLES SECTION
'======================================
Const HKEY_LOCAL_MACHINE = &H80000002

CheckRegExist()

If (regExist=TRUE) Then

'==================================
' Get Registry Values
'==================================
agentVersion = ReadReg("HKEY_LOCAL_MACHINE\SOFTWARE\Network\Framework\Data

Path")
'WScript.Echo "Agent Version: " & agentVersion

dataPath = ReadReg("HKEY_LOCAL_MACHINE\SOFTWARE\Network\Framework\Data Path")
'WScript.Echo "Data Path: " & dataPath

'==================================
' Read XML Sitelist
'==================================

Set xmlDoc = CreateObject("Msxml2.DOMDocument")
xmlDoc.load(dataPath & "\SiteList.xml")

Set ElemList = xmlDoc.getElementsByTagName("SpipeSite")
ipAddress = ElemList.item(0).getAttribute("ServerIP")
' MsgBox ipAddress & " " & InStr(REQUIRED_SERVER_IP,ipAddress)

'==================================
' Check Agent Version, ServerIP
'==================================

IF (agentVersion<REQUIRED_AGENT_VERSION) OR InStr

(REQUIRED_SERVER_IP,ipAddress) < 1 THEN

InstallNewAgent(FULL_INSTALL_PATH)

'MsgBox("Your agent is now up to date and configured correctly.")

ELSE

'MsgBox("Your agent is currently up to date and configured correctly.")

END IF

'Install Agent if Reg Does NOT exist

ELSE
InstallNewAgent(FULL_INSTALL_PATH)
END IF

'==================================
' Registry Reader
'==================================

Function ReadReg(RegPath)
Dim objRegistry, Key
Set objRegistry = CreateObject("Wscript.shell")
Key = objRegistry.RegRead(RegPath)
ReadReg = Key
End Function

'==================================
' Agent Installation
'==================================

Function InstallNewAgent(FULL_INSTALL_PATH)
Dim wshShell
Set wshShell = WScript.CreateObject ("WSCript.shell")

' MsgBox("Installing New Agent...")

wshshell.run FULL_INSTALL_PATH, 6, True
set wshshell = nothing
End Function

'==================================
' Check if Reg Key Exists
'==================================

Function CheckRegExist ()
Dim strComputer, objRegistry, strKeyPath, strValueName, strValue
strComputer = "."
Set objRegistry = GetObject("winmgmts:\\" & strComputer & "\root

\default:StdRegProv")

strKeyPath = "SOFTWARE\Network\Shared Components\Framework"
strValueName = "Version"

objRegistry.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,strValue

If IsNull(strValue) Then
'Wscript.Echo "The registry key does not exist."
regExist=FALSE
Else
'Wscript.Echo "The registry key exists. (" & strValue & ")"
regExist=TRUE
End If
End Function

Viewing all 15028 articles
Browse latest View live


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