PowerShell to re-run the users logon script - powershell

I have a VBScript that re-runs the users login script, I use Task Scheduler to trigger the script to run whenever the user's network status changes. (to ensure drives are mapped when necessary). I'm looking to convert this into PowerShell but am getting stumped. How would you do it?
This is the VBScript I'm using:
Dim objNet
Dim wshShell
Dim wshProcess
Dim domain, username, dc
Set objNet = CreateObject("WScript.NetWork")
Set wshShell = CreateObject("Wscript.Shell")
Set wshProcess = wshShell.Environment("Process")
Domain = objNet.UserDomain
UserName = objNet.UserName
DC = wshProcess("LogonServer")
Set UserObj = GetObject("WinNT://" & domain & "/" & username)
loginScript = DC & "\netlogon\" & UserObj.LoginScript
On Error Resume Next
wshShell.Run(loginscript)
Set UserObj = Nothing
Set wshProcess = Nothing
Set wshShell = Nothing
Set objNet = Nothing

Related

Outlook email script read UTF8 file

On Error Resume Next
Set objSysInfo = CreateObject("ADSystemInfo")
Set WshShell = CreateObject("WScript.Shell")
strUser = objSysInfo.UserName
Set objUser = GetObject("LDAP://" & strUser)
strName = objUser.FullName
strTitle = objUser.Description
strCred = objUser.Info
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add()
Set objSelection = objWord.Selection
strFailas1 = "1.jpg"
strFailas2 = "2.jpg"
strFailas3 = "3.jpg"
strFailas4 = "4.jpg"
strSPath1 = CreateObject("WScript.Shell").ExpandEnvironmentStrings("%USERPROFILE%") & "\Appdata\Roaming\Microsoft\Signatures\" & strFailas1
strSPath2 = CreateObject("WScript.Shell").ExpandEnvironmentStrings("%USERPROFILE%") & "\Appdata\Roaming\Microsoft\Signatures\" & strFailas2
strSPath3 = CreateObject("WScript.Shell").ExpandEnvironmentStrings("%USERPROFILE%") & "\Appdata\Roaming\Microsoft\Signatures\" & strFailas3
strSPath4 = CreateObject("WScript.Shell").ExpandEnvironmentStrings("%USERPROFILE%") & "\Appdata\Roaming\Microsoft\Signatures\" & strFailas4
Set objEmailOptions = objWord.EmailOptions
Set objSignatureObject = objEmailOptions.EmailSignature
Set objSignatureEntries = objSignatureObject.EmailSignatureEntries
If (strCred) Then objSelection.TypeText strName & ", " & strCred Else objSelection.TypeText strName
objSelection.TypeParagraph()
Set adoStream = CreateObject("ADODB.Stream")
adoStream.Open
adoStream.Charset = "UTF-8"
adoStream.LoadFromFile "file.txt"
BodyTEXT = adoStream.ReadText(-1)
adoStream.TypeText BodyTEXT
adoStream.Close
Set adoStream = Nothing
Set objSelection = objDoc.Range()
objSignatureEntries.Add "Full Signature", objSelection
objSignatureObject.NewMessageSignature = "Full Signature"
objDoc.Saved = True
objWord.Quit
I'm trying to create a VBScript to automatically genarate email signature for all users in Active Directory, but I have a problem. I want to insert UTF8 *.txt file as email signature body but it's not displayed after I run this script. Maybe I need to set it as different variable or something?
VBScript troubleshooting 101: remove On Error Resume Next, so you can actually see what goes wrong. Contrary to popular belief the statement doesn't magically make errors disappear. It just prevents the interpreter from telling you about them.
Never ever use globel On Error Resume Next in production code.
*steps off soap box*
With that said, you read the text into the variable BodyTEXT, which works just fine. However, you then try to call adoStream.TypeText with it. Without the global On Error Resume Next that statement would have raised an error
Object doesn't support this property or method.
because ADODB.Stream objects don't have such a method.
You probably intended to write objSelection.TypeText BodyTEXT instead.

How can I run a VBScript file silently in the background?

I want to run a VBScript file silently, because it is just a part of a hidden script.
I'm using the VBScript to export automatically documents out of SAP, that is working perfectly, unless showing each step in the SAP-GUI.
The VBScript file is started in a PowerShell, where I already tried to hide the process like:
$vbsPDPPath = "$env:userprofile\AppData\Roaming\KPIReport"
$vbsPDPName = "SAP-ExportPDP.vbs"
$processNamePDP = $vbsPDPPath + "\" + $vbsPDPName
Start-Process $processNamePDP -WindowStyle Hidden
Didn't work out though.
I'm looking for a solution like in VBA, where you can just add:
Application.ScreenUpdating = False
Still have no idea how to solve it. I thought it would be helpful to let you see the vbs-code, there must be the fault.
I noticed that I haven't mentioned to hide the SAP GUI as well as the Excel Application.
Dim Number_PDP
Dim testNode
Dim WshShell
Dim profile
Set WshShell = WScript.CreateObject("WScript.Shell")
profile = WshShell.ExpandEnvironmentStrings("%USERPROFILE%")
'read XML file
Set xmlDoc = CreateObject("MSXML.DomDocument")
xmlDoc.Load profile & "\AppData\Roaming\KPIReport\DIS.xml"
For Each testNode In xmlDoc.selectNodes("/Reports/Report")
Number_PDP = testNode.SelectSingleNode("DIS_PDP").Text
'connect to SAP GUI
If Not IsObject(application) Then
Set SapGuiAuto = GetObject("SAPGUI")
Set application = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(connection) Then
Set connection = application.Children(0)
End If
If Not IsObject(session) Then
Set session = connection.Children(0)
End If
If IsObject(WScript) Then
WScript.ConnectObject session, "on"
WScript.ConnectObject application, "on"
End If
SapGuiAuto.Visible = false
'not working, thought it is possible to hide SAP
session.findById("wnd[0]").resizeWorkingPane 132,31,false
session.findById("wnd[0]/tbar[0]/okcd").text = "/n cv04n"
session.findById("wnd[0]").sendVKey 0
...
'cutted a couple of rows, just opens a document in Excel with SAP
'after SAP opens Excel I used this code to save the documents
set objExcel = getobject(,"Excel.Application")
if err.number<>0 then
err.clear
end if
'this part should be hidden as well, not working
objExcel.Visible = false
objExcel.ActiveWorkbook.SaveAs profile & "\AppData\Roaming\KPIReport\" & Number_PDP
objExcel.ActiveWorkbook.Close
objExcel.Quit
Next
I would use a workaround in both cases.
For example:
. . .
'session.findById("wnd[0]").resizeWorkingPane 132,31,false
session.findById("wnd[0]").iconify
. . .
and
. . .
'objExcel.Visible = false
objExcel.WindowState = 2
. . .
Regards,
ScriptMan

VBA code to check if Outlook is Setup before sending mail

I have a code in Access where it will send an email to the person in charge when the user click on save button. The code will use Outlook.application to send the email.
The code works fine but if outlook is not setup (i.e. fresh install without any user account setup) then the my email code will get stuck until user reactivates Access to acknowledge the error.
Sub Send_Email()
Dim oApp As Outlook.Application
Dim oMail As MailItem
On Error GoTo MailErr
If IsNull(Email) Then
MsgBox "You do not have an email account! No email will be sent!" & vbNewLine & "Email updates will be sent to your supervisor!" Me.Email.Value = DLookup("[Email]", "tblEmployeeList", "EmpName = '" & Me.txtSupName & "'")
Else
Set oApp = CreateObject("Outlook.application")
Set oMail = oApp.CreateItem(olMailItem)
oMail.Body = "IT Incident " & Me.ReqID & " has been created."
oMail.Subject = "Alert: New IT Incident"
oMail.to = Forms!MainForm!lblITAdminEmail.Caption
oMail.Send
Set oMail = Nothing
Set oApp = Nothing
End If
MailErr:
'MsgBox Err
If Err = 287 Then
AppActivate "Microsoft Access"
MsgBox "Error 287: Mail not sent! Pls contact IT/BI"
ElseIf Err <> 0 Then
MsgBox "Pls contact BI/IT admin! Error " & Err & " occured!"
End If
Set oMail = Nothing
Set oApp = Nothing
End Sub
Is there a way to use VBA to check if Outlook has been setup properly prior to running this code?
Assuming that you are using at least Outlook 2007; take a look at the DefaultProfileName property of your Outlook.Application Object. This will return an empty string if no profile has been created or if there is no default profile.
You could just check this, but I believe that it's possible that an Outlook profile could exist but no actual e-mail accounts are configured within it (for instance if the user aborted the set-up wizard part way through). In this instance you could look at the Accounts Object which includes a Count property. Obviously if this is 0 then you know there are no accounts configured within the profile.
A simple example of how you could implement this.
Dim oApp As Outlook.Application
Set oApp = Outlook.Application
If Not oApp.DefaultProfileName = "" Then
If oApp.Session.Accounts.Count > 0 Then
' Send the e-mail
End If
End If
Set oApp = Nothing

sending outlook based email in VBScript - error (sfile as string) line?

im trying to send an email from a VBScript, it will eventually be added into a currently working script as an else if (if this is possible).
im getting an error at line 23 character 32?
Dim outobj, mailobj
Dim strFileText
Dim objFileToRead
Set outobj = CreateObject("Outlook.Application")
Set mailobj = outobj.CreateItem(0)
strFileText = GetText("C:\test\test 2.txt")
With mailobj
.To = "user#user.com"
.Subject = "Testmail"
.Body = strFileText
.Display
End With
Set outobj = Nothing
Set mailobj = Nothing
End Sub
Function GetText(sFile as String) As String
Dim nSourceFile As Integer, sText As String
nSourceFile = FreeFile
Open sFile For Input As #nSourceFile
sText = Input$(LOF(1), 1)
Close
GetText = sText
End Function
what do i need to add to get line 23 to work and the script to finally do what i need it to, i have copied most of this script from elsewhere due to a sincere lack of VBscripting knowledge?
Take a look at the Using Automation to Send a Microsoft Outlook Message article. It provides a sample code and describes all the required steps for sending emails.
Try this: remove the GetText function entirely, and replace the line
strFileText = GetText("C:\test\test 2.txt")
with
Set fso = CreateObject("Scripting.FileSystemObject")
strFileText = fso.OpenTextFile("C:\test\test 2.txt").ReadAll

Access 2007 to Word, Outlook for 2-step Mail Merge

My VBA does the email merge wonderfully ... except, I have to click on "allow" - from Outlook - twice, for each email generated. Is there a way to programatically get around this?
I am running Windows 7 Enterprise, SP1. MS Office 2007. Computer is tightly locked down. HTML format e-mail not supported - only plain text. I do not have local admin rights. I am not able to install additional add-ins or third party software, as I've found suggested numerous times.
Here is my working VBA:
Private Sub Send_Email_Merge()
Dim sDBPath As String
'Word variables
Dim oWD As Word.Application
Dim oDoc As Word.Document
Dim RecCount As Long
'Sanity check on how many e-mails to be sent
RecCount = DLookup("[Email Count]", "qry_EmailMerge_Count")
Debug.Print RecCount
Set oWD = CreateObject("Word.Application")
oWD.Visible = True
Set oDoc = oWD.Documents.Open("C:\MyTemp\MyDocs\MyEmailMerge.docx")
With oDoc.MailMerge
.MainDocumentType = wdFormLetters
sDBPath = "C:\MyTemp\MydBs\My_Engine.accdb"
.OpenDataSource Name:=sDBPath, _
SQLStatement:="SELECT * FROM [qry_E Mail Merge]"
End With
oWD.Activate
oWD.Documents.Parent.Visible = True
oWD.Application.WindowState = 1
oWD.ActiveWindow.WindowState = 1
With oDoc.MailMerge
.Destination = wdSendToEmail
.MailAddressFieldName = "Email Address"
.MailSubject = "Your Action Required"
.MailFormat = wdMailFormatPlainText
.Execute
End With
oWD.Activate
oWD.Documents.Parent.Visible = True
oWD.Application.WindowState = 1
oWD.ActiveWindow.WindowState = 1
oWD.ActiveDocument.Close
oWD.Quit
Set oWD = Nothing
Set oDoc = Nothing
End Sub
Any help is appreciated.
You can automate directly from Access. See How to automate Outlook from another program for more information. It describes all the required steps for automating Outlook from another applications.