Showing posts with label Scripts. Show all posts
Showing posts with label Scripts. Show all posts

Thursday, 12 July 2018

Use VBS to remote execute powershell on a device (even if remote powershell is disabled)

Sometimes you will want to execute some powershell script on a machine , but most IT systems now block remote powershell as its to big a security risk. Also the normal IPC$ are also often disabled which stops our old favourite PSEXEC from working.

I found this VBS WMI call does however seem to work in this circumatnaces. It basically lets you do a remote call to powershell.exe and pipe a path to the powershell PS1 file you want to execute.

Eg.

Strcomputername = "remote computer name"
ScommandLine = "powershell.exe C:\temp\myscript.ps1"

set objWMIService = GetObject("winmgmts:{impersonationlevel=impersonate}!\\ & StrComputername & "\root\CIMV2:Win32_Process)

oError = ObjWMIService.Create(ScommandLine, null, null, iProcessID)


Saturday, 29 November 2014

Appsense Environment Manager Powershell Execution Policy

The following is an extract from the documentation surrounding powershell being embedded into Appsense Environment manager configurations.

The basics are if the powershell is to run in the user context you will need to ensure that powershell execution is allowed. 

You can control the powershell execution mode using GPO managed inside the appsense policy. 

Environment Manager overrides execution policies and bypasses any restrictions to enable the PowerShell scripts to run.

Execution polices for users and computers can also be set through Group Policy which override all PowerShell execution policies. A user policy which does not allow any scripts, or only those which are signed, will not affect the running of PowerShell Custom conditions if they are run as System. However, if run as the current user the user policy will not allow the scripts and the Custom condition will fail. A computer policy which does not allow any scripts or only those which are signed, will not allow the running of any PowerShell Custom conditions. Therefore, to successfully run Custom conditions which use PowerShell, your Group Policy must be set to allow these scripts to run for users and computers.

Tuesday, 28 October 2014

Microsoft Word Table Color Macro

The following macros can be used to change the color of the first columns in a table, and also to control the border color.

Sub ApplyBordersToAllTables()

Dim oTable As Table
Dim oBorderStyle As WdLineStyle
Dim oBorderWidth As WdLineWidth
Dim oBorderColor As WdColor
Dim n As Long 'used to count tables for message
Dim i As Long 'used with array
Dim oArray As Variant

'Change the values below to apply other borders
oBorderStyle = wdLineStyleSingle
oBorderWidth = wdLineWidth050pt
oBorderColor = wdColorBlue

'Define array with the borders to be changed
'Diagonal borders not included here
oArray = Array(wdBorderTop, _
wdBorderLeft, _
wdBorderBottom, _
wdBorderRight, _
wdBorderHorizontal, _
wdBorderVertical)

For Each oTable In ActiveDocument.Tables
n = n + 1
With oTable
For i = LBound(oArray) To UBound(oArray)
With .Borders(oArray(i))
.LineStyle = oBorderStyle
.LineWidth = wdLineWidth050pt
.Color = wdColorBlack
End With
Next i
End With
Next oTable

MsgBox "Finished applying borders to " & n & " tables."
End Sub
   
   
Sub decolordocument()
'
' decolordocument Macro
'
'
Dim first As Boolean
Dim tbl As Table
n = 0
For Each tbl In ActiveDocument.Tables
tbl.Shading.BackgroundPatternColor = wdColorWhite
n = n + 1
y = 1
    For Each Col In tbl.Columns
                ActiveDocument.Tables(n).Cell(1, y).Shading.BackgroundPatternColor = wdColorLightBlue
                y = y + 1
    Next
Next

Wednesday, 18 June 2014

PowerShell Create a Large file with random content and fixed size

In order to test storage its sometime handy to be able to generate large files with random content. This allows us to test such things as

Deduplication engines
Thin Provisioning
SDelete
VMWware space reclaimation VMFKTOOL
Vmware PunchtoZero features

To this end i created this powershell script to create random content into a file. There are some thirdparty applications and other utils out there but i found them wanting and often not containing unique random data. There tended to be alot of whitespace. 

Powershell means no install required and we can customise. 
This script grabs a file full of content and randomly picks out the data and then writes it to a file until the file is the desired size. This script is not the quickest but it should be fast enough. It created a 1GB file for me in about 2 minutes.

You will need to create a c:\temp\content.txt file containing random words or sentences. 

$Input = get-content C:\temp\content.txt
$OutputFile = "Abigfile.txt"
$stream = [System.IO.StreamWriter] $Outputfile
   do {
   $Counter = 0
       do {
           $Counter=$Counter+1
           $a = $Input | get-random
           $Text = $Text + $a
           }
       While ($Counter -le 50)
   $stream.WriteLine($text)
   $FileSize = (Get-Item $Outputfile).length
   }
   While ($FileSize -le 2000000000)
$stream.close()
$WshShell = new-object -comobject Wscript.shell
$WshShell.Popup("Complete",5,"Title")

Monday, 10 February 2014

Citrix XenDesktop Reboot Powershell

The following powershell could be used on a Desktop controller to perform reboots. This script could be run with a scheduleded task.

This can be handy for things like Physical machine catalogs which dont have Xendesktop power management control.

$machines = Get-BrokerMachine -CatalogName "CatalogXX" -PowerState On

foreach ($machine in $machines)
{
write-host $machine.hostedMachineName $machine.LastHostingUpdateTime
if ( ( get-date $machine.LastHostingUpdateTime ).day -lt ( get-date ).day )
{
New-BrokerHostingPowerAction -Action Restart -MachineName $machine.HostedMachineName
}
}

Wednesday, 3 July 2013

Citrix XenDesktop show peak hours from CLI Powershell

The GUI for setting peak hours is a little wobbly with the slider bars.
If you want to see the power schedule with a PS command use the following

$WeeklyPeakHours = Get-BrokerPowerTimeScheme -name "DesktopGroup_Weekdays"

or

$WeekendPeakHours = Get-BrokerPowerTimeScheme -name "DesktopGroup_Weekend"

Then the following commands will show a display of the hours

$WeeklyPeakhours.PeakHours
$WeekendPeakHours.Peakhours

The Output is in the format of the hours and either a true or false value as to if it set as a peak hour.

eg.

FALSE
FALSE
FALSE
FALSE
TRUE
TRUE

Friday, 25 January 2013

Random Sleep with Powershell

I like nothing better than a random sleep.

With powershell this is very easy and configurable. We can grab a random number within a defined range, and then sleep for that duration in seconds.

$Timer = Get-Random -Maximum 10 -Minimum 1
Start-Sleep $Timer

Wednesday, 15 February 2012

Bypass powershell execution policy

I was given this information by a collague but have not tested this as yet.

Bypassing Execution Policy for Powershell
When execution policy prevents execution of PowerShell scripts, you can still execute them. There is a secret parameter called "-". When you use it, you can pipe a script into powershell.exe and execute it line by line
Get-Content 'C:\somescript.ps1' | powershell.exe -noprofile -

Wednesday, 25 May 2011

Oracle Java Digital Certificates Pre-install

Oracle Form Applications will often prompt users about the digital certificate (certainly on first launch)
We can pre-populate the user with the required digital certificate by placing the file in the following location

%userprofile%\Appdata\LocalLow\Sun\Java\Deployment\Security\trusted.certs

(note : this is the path on win7 and server 2008 environments)

I also found this tip which i have not tested
keytool -importcert -file my.cer -keystore "%USERPROFILE%\AppData\LocalLow\Sun\Java\Deployment\security\trusted.certs" -storepass "" -noprompt -v


also some good info here on pre-populated the config

Tuesday, 24 May 2011

VBS to edit Proxy server bypass list

The following is a VB Script that can amend a users Proxy server bypass list.
This script is great in that it appends the list so that it can be run multiple times during logon or applicaiton launch without losing setting made previosuly.




'--------------------------------------------------
'Aim:       To add exceptions to the proxy settings
'           Developed to avoid duplicates being in the list
'--------------------------------------------------
Option Explicit

Const HKCU = &H80000001
Const SUB_KEY = "Software\Microsoft\Windows\CurrentVersion\Internet Settings"
Const VALUE_NAME = "ProxyOverride"
Const BYPASS_SITES = "*.thinworld.net"
'--------------------------------------------------
'HKCU = value for the HKEY_CURRENT_USER hive
'SUB_KEY = location for the security zone map
'VALUE_NAME = value name to look for
'BYPASS_SITES = sites to bypass the proxy
'--------------------------------------------------

Dim objReg
Dim strValue, strNewValue, strSite
Dim arrTemp, arrTempSites
'--------------------------------------------------
'objReg = WMI class to manipulate the registry
'strValue = the value retrieved from the registry
'strNewValue = the value to write to the registry
'--------------------------------------------------

'-- get the existing bypass list --'
Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
objReg.GetStringValue HKCU, SUB_KEY, VALUE_NAME, strValue

'-- write the new bypass list --'
objReg.GetStringValue HKCU, SUB_KEY, VALUE_NAME, strValue
arrTempSites = Split(BYPASS_SITES, ";")
strNewValue = strValue
For Each strSite In arrTempSites
  arrTemp = Split(strNewValue, ";")
  If Not Array_InArray(strSite, arrTemp) Then
   strNewValue = strSite & ";" & strNewValue
  End If
Next
objReg.SetStringValue HKCU, SUB_KEY, VALUE_NAME, strNewValue

WScript.Quit 0

'--------------------------------------------------
'Aim:       To determine is the given text is in the given array
'Returns:   True if found, False if not found
'--------------------------------------------------
Function Array_InArray(ByVal needle, ByVal haystack)

  Dim idx
  Dim blnFound
  '--------------------------------------------------
  'idx = index in an array
  'blnFound = whether the item is found or not
  '--------------------------------------------------

  blnFound = False

  For Each idx In haystack
    If LCase(needle) = LCase(idx) Then
     blnFound = True
     Exit For
    End If
  Next

  Array_InArray = blnFound

End Function

Tuesday, 17 May 2011

Automate Personal Certificate Import

A VB Script to silently install a personal certficate for users. This can be used to automate certificate installation for users. You will need to get a copy of  winhttpcertcfg.exe utility to import the certificate.

 --------------------------------------------------
'Aim:       To silently install the given personal certificate
'--------------------------------------------------
Option Explicit

Dim objShell
Dim strCertTool, strCertPath, strCertPwd, strUserName, strAppCache, StrUserID, StrAppCacheServer
'--------------------------------------------------
'objShell = Windows Script Host Shell Object
'strCertTool = path to the tool used to do the import
'strCertPath = path to the certificate file
'strCertPwd = certificate password
'strUserName = current user in form DOMAIN\Username
'strAppCache = application cache location
'--------------------------------------------------

'-- build the required variables --'
Set objShell = CreateObject("WScript.Shell")
strAppCache = "\\msgchhost\" & StrUserID  &  "$\tsprofile\"
strUserName = objShell.ExpandEnvironmentStrings("%userdomain%") & "\" & objShell.ExpandEnvironmentStrings("%username%")
StrAppCacheServer = objShell.ExpandEnvironmentStrings("%app_cache%")
strCertTool = strAppCacheServer & "\Certificates\winhttpcertcfg.exe"
strCertPath = strAppCache & "certificatename.pfx"
strCertPwd = "xxxx"
msgbox strCertpath
'-- run the tool in a hidden window --'
objShell.Run strCertTool & " -i " & strCertPath & " -a " & strUserName & " -c CURRENT_USER\My -p " & strCertPwd, 0, True

'-- Clean Up --'
Set objShell = Nothing

WScript.Quit 0

Friday, 4 February 2011

Emdedding a WebPage within a WebPage

Sounds Strange i know but sometime this might be handy.
It basically lets you display another webpage within your own. I was considering using it to display my Blog directly inside my www.thinworld.net website but eventually chose against it.

I still might use it in the future so posting the code here. It could also be used to make your own cool portal type page.

Thursday, 13 January 2011

VBS display of DFS path location

If you want to create a scripted method of managing DFS path you can use the DFSCMD.EXE tool.

eg. DFSCMD.EXE /view \\server\share /full

This command will output all the folder on that share and their DFS path.
The output from this command can be sent to a text file where the usual VB Script manipulation can take place.

Friday, 7 January 2011

Enable PowerShell Scripting

By default powershell script execution is disabled on Server 2008 R2

To enable it launch the Powershell console as Administrator and run
Set-ExecutionPolicy unrestricted

 

Wednesday, 1 December 2010

VBS Encryption of text

This VB script can be used to encrypt and unencrypt data.


'
' file either contains Encrypt : userid : password
' or
' the result of the encryption
'

strFileName ="StoreSecure.dat"
strCryptMarker ="[ENCRYPT]"

Set objNet = WScript.CreateObject("WScript.Network")
cryptkey = "wscript.exe"

Const ForReading = 1
Const ForWriting = 2

Set fso = CreateObject("Scripting.FileSystemObject")

on error resume next
Set tfr = fso.OpenTextFile(strFileName,ForReading,False)
if err.number <> 0 then
wscript.echo "Error " & strFileName & " is missing - Unable to map directories "
wscript.quit 1
End if
on error goto 0

readText = tfr.readLine
splitText = Left(readText,Len(strCryptMarker))

if ucase(splitText) = strCryptMarker then
NewText = CryptVBS(mid(readText,Len(strCryptMarker) + 1),cryptkey)
close_it = tfr.close
Set tfw = fso.OpenTextFile(strFileName,ForWriting,True)
writeIt = tfw.write(NewText)
close_it = tfw.close
readText = NewText
End if

on error goto 0
NewReadText = CryptVBS(readText,cryptkey)

wscript.echo NewReadText


wscript.quit


'---------------------------------------
' Encryption function -
'---------------------------------------

Function CryptVBS(Text, Keynm)

keyptr=0
hold_it = ""
KeyLen = Len(Keynm)

For i = 1 To Len(Text)
KeyPtr = (KeyPtr + 1) Mod KeyLen
sTxtChr = Mid(Text, i, 1)
wTxtChr = Asc(stxtchr)
wKeyChr = Asc(Mid(Keynm, KeyPtr + 1, 1))
hold_it = hold_it & Chr(wTxtChr Xor wKeyChr)
Next

CryptVBS = hold_it
End Function

VBS Display or List Shortcut Properties

If you want a script that lists/audits shortcut properties then the following code will come in handy.
The code below is set to display the properties of an icon xxx located on the desktop.
The code is a little strange as it trys to create an existing shortcut but this is the only method you can use to retrieve the properties of an existing shortcut as there is no Readshortcut method.

Set Shell = CreateObject("WScript.Shell")
DesktopPath = Shell.SpecialFolders("Desktop")
Set link = Shell.CreateShortcut(DesktopPath & "\xxx.lnk")
wscript.echo link.Description
wscript.echo link.TargetPath
wscript.echo link.WorkingDirectory

Friday, 26 November 2010

Robocopy Merge Syntax

To perform a merge of two similar directory structures the following robocopy command can be used. It will Move files from source to destination if they are unique. If there are any clashes it will leave them in the source. These clashes could then be copied to the destination into a "Clashes" folder for manual review.

robocopy source dest /E /MOVE /XC /XN /XO /XX /W:1 /R:1 /V >merge.txt

The command basically moves everything except clashing files.

Monday, 15 November 2010

their is no file extension in \\domain\sysvol\policies\script

I was getting an error message during logon

"their is no file extension in \\domain\sysvol\policies\{GUID}\scripts\logon"

A logon script called by GPO was failing to run. I created a shortcut the script within sysvol and the shortcut also failed to launch the script with the same error message.
Calling the script from a Batch file worked ok.

The problem turned out to be the GPO was calling a VBS script with a long name. Renaming the VBS script to 8 characters or less resolved the issue.

Thursday, 11 November 2010

Excel VLookup Data Manipulation

This is something i learnt in excel today. Its quite handy. It similar to a Advanced Filter for unique records but can be performed on more than 1 column

I used it to help filter a massive DUMPACL output. I wanted to know unique AD group names along with the starting path structure. I didnt care after that what folders that group had permissions.

eg.

AD-Group1 C:\folder1
AD-Group1 C:\folder1\folder2
AD-Group1 C:\folder1\folder2\folder3
AD-Group2 D:\dirz
AD-Group2 D:\Dirz\folder1

I wanted the output to be

AD-Group1 C:\folder1
AD-Group2 D:\dirz

To achive this i used this formula

=VLOOKUP(AD-Group1,A1:B100,2,FALSE)

This searched for AD-Group1 between A1 and B100 cells and returned me the result from Column 2 (B), The FALSE means not an exact match

Full details on this command syntax are on :
http://office.microsoft.com/en-us/excel-help/vlookup-HP005209335.aspx

Tuesday, 2 November 2010

Robocopy Syntax & throttling with IPG

I justed wanted to blog a couple of my commonly used robocopy syntax's

robocopy C:\source D:\dest /rh:2000-0600/pf /mir /copy:DATSO /R:3 /W:1 /v >log.txt

This performs a mirror copy that can only run between 2000-0600
It will also copy these attributes
D - Data
A - Attributes
T - Time stamps
S - NTFS ACLs
O - Ownership

It will output to log.txt


Throttling Bandwidth useage
A handy switch to use with robocopy is the Interpacket Gap /IPG
This will help throttle the robocopy job and prevent flooding small data links during a copy.
The IPG Gap is a time in Milliseconds the pause between copies.

The IPG Gap should be set according to network configuration but as a general rule
on 2MB/sec connection a setting of /IPG:256 is recommended.
(2.5 second delay between sends)

The formula for the calculation is

Ba - Bd
------------ x 512 x 1000 = IPG
Bd * Ba

Ba = Bandwidth available in kb
Bd = Bandwidth Desired in kb

IPG Calculator - This will help estimate how long a copy will take with throttling in place
http://www.zeda.nl/en/ToolsIPGCal