I am trying to create a script that will ask the user if they want to set a network printer as their default. My problem is that no matter what they select (yes or no) it set it up as the default and it always echo's my the echo statement under else. Can someone tell me what I am doing wrong?
` ' Printers.vbs - Windows Logon Script.
printername = "DCPTTEAM462W"
server = "DCDEPLOY03"
Dim objectNetwork, printer
printer = "\\DCPRINT03\DCPTTEAM462W"
Msgbox printername & " will now install on your computer.",0, "Add printer" & printername
intRespnseY = Msgbox("Would you like " & printername & " to be set as your default printer", vbYesNo, "Set as Default")
If intResponseY = vbNo Then
Set objNetwork = CreateObject("WScript.Network")
objNetwork.AddWindowsPrinterConnection printer
WScript.Echo "DCPTTEAM462W was added as a printer."
Else
Set objNetwork = CreateObject("WScript.Network")
objNetwork.AddWindowsPrinterConnection printer
objNetwork.SetDefaultPrinter printer
WScript.Echo "DCPTTEAM462W has been set as your default printer."
End If
`
You have a typo:
intRespnseY = Msgbox(....
Should be
intResponseY = Msgbox(....
Use
Option Explicit
to avoid blunders like:
intRespnseY = Msgbox("...")
If intResponseY = vbNo Then
(mark the missing "o")
Related
How can I get xTextFields from .odt document properly?
I tried something like that, but it doesn't work (Any returns a nullptr address):
Reference <XTextFieldsSupplier> xTextFieldsSupplier (xTextDoc, UNO_QUERY);
if (!xTextFieldsSupplier.is())
return { };
Reference<XNameAccess> xTextFieldsInfo = xTextFieldsSupplier->getTextFieldMasters();
if (!xTextFieldsInfo.is())
return { };
Sequence<OUString> xTextFieldsNames = xTextFieldsInfo->getElementNames();
Any any;
for (::rtl::OUString* field = xTextFieldsNames.begin();
field != xTextFieldsNames.end();
field++) {
std::stringstream field_string;
field_string << *field;
QString fieldName = QString::fromStdString(field_string.str());
any = xTextFieldsInfo->getByName(*field);
Reference< XTextField > xField(any, UNO_QUERY);
// other code to work with xField
}
UPD:
I got a solution that helped me here:
Libreoffice API (UNO): need to change user's xTextField text
XTextFieldsSupplier has two methods, and it looks like you chose the wrong one. The method to get text fields is getTextFields().
Example code:
Reference< XEnumerationAccess > xFieldsEnumAccess = xTextFieldsSupplier->getTextFields();
Reference< XEnumeration > xFieldsEnum = xFieldsEnumAccess->createEnumeration();
Reference< XTextRange > xTextRange;
while ( xFieldsEnum->hasMoreElements() )
{
Any aNextElement = xFieldsEnum->nextElement();
Reference< XTextField > xField(aNextElement, UNO_QUERY);
OUString presentation = xField->getPresentation(true);
xTextRange = xText->getEnd();
xTextRange->setString(presentation + OUString::createFromAscii("\n"));
}
If you want to deal with text field masters instead, then your code is mostly correct.
Any aFieldMaster;
aFieldMaster = xNamedFieldMasters->getByName(*field);
EDIT:
Here is where xText comes from.
Reference < XTextDocument > xTextDocument (xComponent,UNO_QUERY);
Reference< XText > xText = xTextDocument->getText();
EDIT 2:
Here is an example of changing a text field. Start with a new Writer document and go to Insert -> Field -> More Fields. Under the Functions tab, double-click Input Field. Enter "hello" in the text box area and press OK.
Then, run the following code.
Reference< XServiceInfo > xInfo (xField, UNO_QUERY);
OUString sContent;
if (xInfo->supportsService("com.sun.star.text.TextField.Input"))
{
Reference< XPropertySet > xProps (xField, UNO_QUERY);
Any aContent = xProps->getPropertyValue(OUString::createFromAscii("Content"));
aContent >>= sContent;
sContent += OUString::createFromAscii(" there");
aContent <<= sContent;
xProps->setPropertyValue(OUString::createFromAscii("Content"), aContent);
Reference< XRefreshable > xRefreshable (xFieldsEnumAccess, UNO_QUERY);
xRefreshable->refresh();
}
Now, the field contains "hello there".
For more information, please review Andrew's Macro Document section 5.18 User Fields.
Is there any proper way to change text in the user's created xTextField using C++ UNO?
These fields names are com.sun.star.text.fieldmaster.User.[FIELD NAME]
I tried this before, but it didn't help:
Libreoffice API (UNO) : text and data from xTextField
Also I've tried something like this but still didn't help:
// current_field - xTextField I got before
Reference<XText> xText = Reference<XText>(current_field, UNO_QUERY);
if (!xText.is())
{
qDebug() << "XText FROM xTextField IS NULL!";
return;
}
OUStringBuffer bufText;
bufText.append( new_value.utf16() );
std::stringstream textStr;
textStr << bufText.toString();
xText->setString( bufText.toString() );
Any suggestions?
Did you read section 5.18 of Andrew's Macro Document as recommended in my other answer? Here is Listing 5.49 translated into C++. It seems there is a bug in that listing because I had to add "." to make it work.
OUString sName = OUString::createFromAscii("Author Name");
OUString sServ = OUString::createFromAscii("com.sun.star.text.FieldMaster.User");
OUString sFieldName = sServ + OUString::createFromAscii(".") + sName;
Reference< XMultiServiceFactory > xDocFactory (xTextDocument, UNO_QUERY);
if (xNamedFieldMasters->hasByName(sFieldName))
{
fieldMaster = xNamedFieldMasters->getByName(sFieldName);
Reference< XPropertySet> xProps (fieldMaster, UNO_QUERY);
Any aContent;
aContent <<= OUString::createFromAscii("Andrew Pitonyak");
xProps->setPropertyValue(OUString::createFromAscii("Content"), aContent);
}
else
{
fieldMaster <<= xDocFactory->createInstance(sServ);
Reference< XPropertySet> xProps (fieldMaster, UNO_QUERY);
Any aName;
aName <<= sName;
xProps->setPropertyValue(OUString::createFromAscii("Name"), aName);
Any aContent;
aContent <<= OUString::createFromAscii("Andrew Pitonyak");
xProps->setPropertyValue(OUString::createFromAscii("Content"), aContent);
}
If this code is run on a blank document, the newly created field can be seen by going to Insert -> Fields -> More Fields, Variables, User Field.
In my VBScript I am trying to run another VBScript to create a desktop shortcut if that desktop shortcut doesn't exist. If the desktop link does exist, it should not do anything. However, currently even if the desktop shortcut exists, the VBScript still runs. Why? No syntax error.
Dim objFSO, strDirectory, strFile
Set oShell = CreateObject ("WScript.Shell")
'getting script location
strPath = WScript.ScriptFullName
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(strPath)
strFolder = objFSO.GetParentFolderName(objFile)
'define directory & file
strDirectory = oShell.ExpandEnvironmentStrings("%USERPROFILE%")
strFile = strDirectory & "\Desktop\My Program.lnk"
If objFSO.FileExists(strFile) Then
'DO NOTHING
Else
strDesk = "desktoplink.vbs"
oShell.Run strDesk, 0, False
End If
'enclosing path to support spaces
HMIpath = strFolder & "\CHK.bat"
HMIpath = """" & HMIpath & """"
Dim strArgs
strArgs = "cmd /c " & HMIpath
oShell.Run strArgs, 0, False
I m trying to mount a vhd on windows 2012 hyperV core datacenter edition. For mounting the vhd I m using the MSVM_Imagemanagementservice class and mount method inside that. The disk is mounted but the problem is no drive letter is getting assigned. I have tried it on other 2012 datacenter edition and 2012 core as well it works fine. i.e after mount the drive letter gets assigned.
Any thoughts on this will help.
You can query for the drive letters list and then assign the drive letter as per your requirement. Given below is the function to get the drive letters list.
Function GetDriveLetterList(path)
'Where path is path of VHD
Dim mountedImage, diskDevice, diskPartition, diskPartitions, logicalPartition, timeout, query
Dim logicalPartitionList
timeout = 0
driveLetterList = ""
path = Replace(path,"\","\\")
Set wmiServiceCIM = GetObject("winmgmts:\\.\root\cimv2")
Do
WScript.Sleep(3000)
timeout = timeout + 3
Set mountedImage = (wmiService.ExecQuery("SELECT * FROM Msvm_MountedStorageImage WHERE Name='" & path & "'")).ItemIndex(0)
query = "SELECT * From Win32_DiskDrive WHERE Model='Msft Virtual Disk SCSI Disk Device' and SCSITargetId='" & mountedImage.TargetId & "' and SCSILogicalUnit='" & mountedImage.Lun & "' and SCSIPort='" & mountedImage.PortNumber & "'"
Set diskDevice = wmiServiceCIM.ExecQuery(query).ItemIndex(0)
query = "ASSOCIATORS OF {" & diskDevice.Path_.Path & "} where AssocClass=Win32_DiskDriveToDiskPartition"
Set diskPartitions = wmiServiceCIM.ExecQuery(query)
For Each diskPartition In diskPartitions
query = "ASSOCIATORS OF {" & diskPartition.Path_.Path & "} WHERE AssocClass=Win32_LogicalDiskToPartition"
Set logicalPartitionList = wmiServiceCIM.ExecQuery(query)
If logicalPartitionList.count > 0 Then
Set logicalPartition = logicalPartitionList.ItemIndex(0)
'WScript.Echo logicalPartition.DeviceID
driveLetterList = driveLetterList + logicalPartition.DeviceID
End If
Next
End Function
If you want to check for systems drive . Then you can do this ...
folderPath = driveLetter + ":\Windows\System32"
Set fileSys = CreateObject("Scripting.FileSystemObject")
If filesys.FolderExists(folderPath) Then
//doStuff
End If
Hi I am using WMI to change the remote registry value for USBSTOR. I want to change the value of start attribute to 4 or 3 for enabling and disabling.
But the datatype for Start attribute in registry is DWORD, if i can the datatype to size it does not work .
I need to keep the Datatype to DWORD. Can someone please tell me how to setDWORDValue using WMI, following is the piece of code that i tried, it worked succesfully but still the value of start field is unchanged in registry.
const uint HKEY_LOCAL_MACHINE = 0x80000002;
ManagementBaseObject methodParams = registryTask.GetMethodParameters(typeOfValue);
methodParams["hDefKey"] = HKEY_LOCAL_MACHINE;// BaseKey;
methodParams["sSubKeyName"] = #"SYSTEM\\CurrentControlSet\\Servic\\USBSTOR";
methodParams["sValueName"] = "Start";
try
{
methodParams["sValue"] = "3";
}
catch
{
methodParams["uValue"] = (UInt32)Convert.ToInt32("3");
}
ManagementBaseObject exitValue = registryTask.InvokeMethod(typeOfValue, methodParams, null);
Simple solution using python.
import wmi
import win32api,_winreg
c = wmi.WMI()
# To get the binary value of particular subkey
# Please note that 0x80000002 represents HKEY_LOCAL_MACHINE
ReturnValue, uValue = c.StdRegProv.GetBinaryValue(0x80000002,"AFD","SYSTEM\CurrentControlSet\Services")
# To get the list of all the subkeys available in particular key
ret, subKeys = c.StdRegProv.EnumKey (0x80000002, "SYSTEM\CurrentControlSet\Services")
print ret
for key in subKeys:
print key
ReturnValue=c.StdRegProv.SetDWORDValue(0x80000002,"Type","SYSTEM\CurrentControlSet\Services\USBSTOR",0x4)
#HKEY_CLASSES_ROOT (2147483648 (0x80000000))
#HKEY_CURRENT_USER (2147483649 (0x80000001))
#HKEY_LOCAL_MACHINE (2147483650 (0x80000002))
#HKEY_USERS (2147483651 (0x80000003))
#HKEY_CURRENT_CONFIG (2147483653 (0x80000005))
#HKEY_DYN_DATA (2147483654 (0x80000006))
Yes it can be done. Here's the code, referencing this Microsoft link and this one. Replace 3389 with the new value you want to use, and change the key as needed:
const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
'Set StdOut = WScript.StdOut
Set oReg=GetObject( _
"winmgmts:{impersonationLevel=impersonate}!\\" &_
strComputer & "\root\default:StdRegProv")
strKeyPath = "SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp"
strValueName = "PortNumber"
' Display old value
oReg.GetDWORDValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,dwValue
WScript.Echo "Old RDP value=" & dwValue
' Set new value
dwValue= 3389
oReg.SetDWORDValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,dwValue
If Err = 0 Then
oReg.GetDWORDValue _
HKEY_LOCAL_MACHINE,strKeyPath,strValueName,dwValue
WScript.Echo "New RDP Value =" & dwValue
Else
WScript.Echo "Error in creating key" & _
" and DWORD value = " & Err.Number
End If