Script Requests - Itarian team will write the scripts for you :) for FREE

Can you “convert” this PowerShell? It will enable BitLocker on the system drive and backup the key to Azure AD

<#
DESCRIPTION
This script will enable bitlocker on the systemdrive and backup the key to Azure AD.
#>



[cmdletbinding()]
param(
[Parameter()]
[ValidateNotNullOrEmpty()]
[string] $OSDrive = $env:SystemDrive
)
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

#Create directory is not exist
$psdirectory = "$osdrive\Program Files (x86)\Scripts\Bitlocker"
If(!(test-path $psdirectory))
{
New-Item -ItemType Directory -Force -Path $psdirectory
}

#Start session log
Start-Transcript -Path $psdirectory\pslogmainscript.txt -Append

try
{

#Check if bitlocker already have a recoverykey, if it dosent it will enable bitlocker and create new recoverykey
$checkifexist = (Get-BitLockerVolume -MountPoint $OSDrive).KeyProtector | Where-Object {$_.KeyProtectorType -eq 'RecoveryPassword'}
if($checkifexist) {
Write-host "Bitlocker is already enabled and have recoverykey"
}
else{

$bdeProtect = Get-BitLockerVolume $OSDrive | Select-Object -Property VolumeStatus
if ($bdeProtect.VolumeStatus -eq "FullyDecrypted")
{
# Enable Bitlocker using TPM
Enable-BitLocker -MountPoint $OSDrive -TpmProtector -ErrorAction Continue
Enable-BitLocker -MountPoint $OSDrive -RecoveryPasswordProtector

}
}

#Check if we can use BackupToAAD-BitLockerKeyProtector commandlet
$cmdName = "BackupToAAD-BitLockerKeyProtector"
if (Get-Command $cmdName -ErrorAction SilentlyContinue)
{
#BackupToAAD-BitLockerKeyProtector commandlet exists
$BLK = (Get-BitLockerVolume -MountPoint $OSDrive).KeyProtector | Where-Object {$_.KeyProtectorType -eq 'RecoveryPassword'}
if ($BLK.count -gt 1){
Write-Host "There are multiple recovery keys, will backup key number 1 to AzureAD"
$key = $BLK[0]
BackupToAAD-BitLockerKeyProtector -MountPoint $OSDrive -KeyProtectorId $key.KeyProtectorId
}

else {
Write-Host "There are only one recovery key, will start to backup to AzureAD"
BackupToAAD-BitLockerKeyProtector -MountPoint $OSDrive -KeyProtectorId $BLK.KeyProtectorId
}

}
else{

# BackupToAAD-BitLockerKeyProtector commandlet not available, using other mechanisme
# Get the AAD Machine Certificate
$cert = Get-ChildItem Cert:\LocalMachine\My\ | Where-Object { $_.Issuer -match "CN=MS-Organization-Access" }

# Obtain the AAD Device ID from the certificate
$id = $cert.Subject.Replace("CN=","")

# Get the tenant name from the registry
$tenant = (Get-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Control\CloudDomain Join\JoinInfo\$($id)).UserEmail.Split('@')[1]

# Generate the body to send to AAD containing the recovery information
# Get the BitLocker key information from WMI
(Get-BitLockerVolume -MountPoint $OSDrive).KeyProtector| Where-Object {$_.KeyProtectorType -eq 'RecoveryPassword'} | ForEach-Object{
$key = $_
write-verbose "kid : $($key.KeyProtectorId) key: $($key.RecoveryPassword)"
$body = "{""key"":""$($key.RecoveryPassword)"",""kid"":""$ ($key.KeyProtectorId.replace('{','').Replace('}',' '))"",""vol"":""OSV""}"

# Create the URL to post the data to based on the tenant and device information
$url = "https://enterpriseregistration.windows.net/manage/$tenant/device/$($id)?api-version=1.0"

# Post the data to the URL and sign it with the AAD Machine Certificate
$req = Invoke-WebRequest -Uri $url -Body $body -UseBasicParsing -Method Post -UseDefaultCredentials -Certificate $cert
$req.RawContent

}
}
#>

} catch
{
write-error "Error while setting up AAD Bitlocker, make sure that you are AAD joined and are running the cmdlet as an admin: $_"
}

Stop-Transcript

Hi @Cronus,

It’s quite easy, in fact. You will need two files, the .cmd script and the .reg file with the font names. And, of course, a folder with all the font files.

The .cmd script file is quite simple. Our internal script is way more complex because it includes logging and error handling routines, but the basic installation process is the following:

echo Copying Montserrat font family to system font folder
xcopy %~dp0Montserrat\*.otf "%SystemRoot%\Fonts" /V /C /I /F /Y
echo Importing Montserrat font family information to the registry.
reg import "%~dp0Montserrat_FontFamily.reg"

The registry file just contains the necessary entries to tell the system the associated font name for each font file. To create the .reg file, we just install the fonts manually on a testing computer and then we export the required branches. This is a sample .reg file for the Montserrat font family:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Fonts]
"Montserrat Bold (TrueType)"="Montserrat-Bold.otf"
"Montserrat Bold Italic (TrueType)"="Montserrat-BoldItalic.otf"
"Montserrat Italic (TrueType)"="Montserrat-Italic.otf"
"Montserrat Light (TrueType)"="Montserrat-Light.otf"
"Montserrat Light Italic (TrueType)"="Montserrat-LightItalic.otf"
"Montserrat Medium (TrueType)"="Montserrat-Medium.otf"
"Montserrat Medium Italic (TrueType)"="Montserrat-MediumItalic.otf"
"Montserrat Regular (TrueType)"="Montserrat-Regular.otf"

[HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\ Windows NT\CurrentVersion\Fonts]
"Montserrat Bold (TrueType)"="Montserrat-Bold.otf"
"Montserrat Bold Italic (TrueType)"="Montserrat-BoldItalic.otf"
"Montserrat Italic (TrueType)"="Montserrat-Italic.otf"
"Montserrat Light (TrueType)"="Montserrat-Light.otf"
"Montserrat Light Italic (TrueType)"="Montserrat-LightItalic.otf"
"Montserrat Medium (TrueType)"="Montserrat-Medium.otf"
"Montserrat Medium Italic (TrueType)"="Montserrat-MediumItalic.otf"
"Montserrat Regular (TrueType)"="Montserrat-Regular.otf"

This way the installation is done of all the users on the computer and it’s completely silent and unattended. The only drawback is that the fonts will only be available to be used after the next reboot, so you might want to add a “shutdown” command to your script.

That’s all so far. Let me know if it works fine for you.

Have a nice day!

– Javier Llorente
Endpoint Security - Devoteam

Can someone assist me in combining two scripts?

  1. Execute Batch commands
  2. Download files

I want to kill a process running
Transfer new File(s)
Start a program back up with specific start directory

Basically…
taskill /f /im app.exe
-Transfer New file or Files-
cd c:\App && app.exe

Another option is a script to download an installer.exe I can create with NSIS. and then have the script execute it, it can do all the commands i need. It can run silent

Batch Script
#To define a particular parameter, replace the 'parameterName' inside itsm.getParameter('variableName') with that parameter's name
BAT=r'''
taskill /f /im app.exe
cd c:\App && app.exe
'''
import os
import sys
import platform
import subprocess
import ctypes

class disable_file_system_redirection:
_disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirect ion
_revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirecti on
def __enter__(self):
self.old_value = ctypes.c_long()
self.success = self._disable(ctypes.byref(self.old_value))
def __exit__(self, type, value, traceback):
if self.success:
self._revert(self.old_value)

path=os.environ['programdata']+"\Sample.bat"
with open(path,"w") as f:
f.write(BAT)
try:
with disable_file_system_redirection():
print "Excuting Bat File"
process = subprocess.Popen([path],stdout=subprocess.PIPE)
stdout = process.communicate()[0]
print "---------------------------"
print stdout

except:
print "Excuting Bat File"
process = subprocess.Popen([path],stdout=subprocess.PIPE)
stdout = process.communicate()[0]
print "---------------------------"
print stdout


if os.path.exists(path):
try:
os.remove(path)
except:
pass
Download files
url=r'https://example.conf/font.txt' #Provide the website url which you need to install as a font
fileName='free3of9.ttf' # Provide the filename of the font

import os
import ssl
import urllib2
import shutil
import ctypes

ssl._create_default_https_context = ssl._create_unverified_context
temp=os.environ['PROGRAMDATA']+r'\c1_temp'

if not os.path.exists(temp):
os.makedirs(temp)



vbs=r'''
Set objShellApp = CreateObject("Shell.Application")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Const FONTS = &H14&
Set objFolder = objShellApp.Namespace(FONTS)
strNewFontsFolder = "%s"
If objFSO.FolderExists(strNewFontsFolder) = True Then
For Each objFile In objFSO.GetFolder(strNewFontsFolder).Files
If LCase(right(objFile,4)) = ".ttf" OR LCase(right(objFile,4)) = ".otf" Then
If objFSO.FileExists(objFolder.Self.Path & "\" & objFile.Name) = False Then objFolder.CopyHere objFile.Path
Wscript.Echo "Installed " & objFile.Name
End If
Next
Else
Wscript.Echo "Unable to find " & strWindowsFonts
End If

'''

def Download(temp,url):
fp = os.path.join(temp, fileName)
request = urllib2.Request(url, headers={'User-Agent' : "Magic Browser"})
parsed = urllib2.urlopen(request)
if os.path.exists(temp):
pass
if not os.path.exists(temp):
os.makedirs(temp)
with open(fp, 'wb') as f:
while True:
chunk=parsed.read(100*1000*1000)
if chunk:
f.write(chunk)
else:
break
return fp

Fontpath=Download(temp,url)

class disable_file_system_redirection:
_disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirect ion
_revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirecti on
def __enter__(self):
self.old_value = ctypes.c_long()
self.success = self._disable(ctypes.byref(self.old_value))
def __exit__(self, type, value, traceback):
if self.success:
self._revert(self.old_value)


def runvbs(vbs,Fontpath):
if not os.path.isdir(temp):
os.mkdir(workdir)
vbs_script= vbs % (temp)
with open(temp+r'	emprun.vbs',"w") as f :
f.write(vbs_script)
with disable_file_system_redirection():
print os.popen('cscript.exe "'+temp+r'	emprun.vbs"').read()
print('Script execution completed successfully')
if os.path.isfile(temp+r'	emprun.vbs'):
os.remove(temp+r'	emprun.vbs')

try:
shutil.rmtree(temp)

except:
pass

runvbs(vbs,Fontpath)


I changed my mind… Now I just need a script to download a file and run it. I got the installer working. I’ll look in the script repo for such a script. if someone already has one that would be great to share :slight_smile:

I got this script below working, if anyone needs to download an exe and just run it.

DownTo='C:\Updates' ## Here mention the path where the application to download
fromURL='https://example.com/file.exe' ## Here mention the download Link


import ctypes

class disable_file_system_redirection:
_disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirect ion
_revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirecti on
def __enter__(self):
self.old_value = ctypes.c_long()
self.success = self._disable(ctypes.byref(self.old_value))
def __exit__(self, type, value, traceback):
if self.success:
self._revert(self.old_value)

import subprocess
with disable_file_system_redirection():
import urllib
import os
#Download File
def downloadFile(DownTo, fromURL):
try:
fileName = fromURL.split('/')[-1]
DownTo = os.path.join(DownTo, fileName)
with open(DownTo, 'wb') as f:
f.write(urllib.urlopen(fromURL).read())
if os.path.isfile(DownTo):
return '{} - {}KB'.format(DownTo, os.path.getsize(DownTo)/1000)
except:
return 'Please Check URL or Download Path!'

if __name__=='__main__':
print downloadFile(DownTo, fromURL )

#Run File
out=os.popen('C:\FilePathHere\App.exe').read();
print(out);


I could really use a script to delete a specific file from Mac computers.

Hi,
I am looking for a script to disable IPv6 in a Network Connection (ncpa.cpl) named “Ethernet”

Hi @keith.ketcher,

Thanks for your script request. We have asked our script developers to check and provide feedback.

Kind Regards,
PremJK

Hi @josuefpcb,

Thanks for your script request. We have asked our script developers to analyze your request.

Kind Regards,
PremJK

Hi josuefpcb@gmail.com,

Please run this script prepared by our script developers and provide feedback
https://scripts.itarian.com/frontend/web/topic/script-to-disable-ipv6-ethernet

Kind Regards,
PremJK

Hi @Cronus

The following script from the repository is working fine for us:

Download and install any application from the URL
https://scripts.itarian.com/frontend/web/topic/download-and-install-any-application-from-the-url

We just clone the script and modify the parameters as many times as we need. It works with both EXE and MSI installers, you only have to enter the necessary parameters for running the installer silently.

Hope this will work for you, too.

Have a nice day!

– Javier Llorente
Endpoint Security - Devoteam

Please write a script to change the value of the following registry key: HKLM\System\CurrentControlSet\Services\NlaSvc\DependOnService

I want to add DNS and Netlogon to the existing list of values, which are: NSI RpcSs TcpIp Dhcp Eventlog

After running the script, the DependOnService should value should be: NSI RpcSs TcpIp Dhcp Eventlog DNS Netlogon

I am looking for a script that will alert us when an endpoint has been inactive for X number of days. I know ITarian will flag an inactive device and can automatically remove it after so long but I want a ticket to be generated for when a device has been inactive to bring it to our attention so we can determine if this is intentional due to retiring or a wipe/reload, or if we need to investigate further.

I am also looking for a script to alert/open a ticket when a device is first enrolled with endpoint manager so we can onboard it into SOCaaP but I think I can handle that one on my own.

Hi RussKinch,

Please try this script with the following parameters as provided and provide your feedback
https://scripts.itarian.com/frontend…registry-value

Key= “HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\NlaSvc”
Sub_Key= “DependOnService”
Field= “REG_MULTI_SZ”
value = “NSI RpcSs TcpIp Dhcp Eventlog DNS Netlogon”

Kind Regards,
PremJK

Hi @fastassist,

Please try this existing script and check if it suffice your needs
https://scripts.itarian.com/frontend/web/topic/monitoring-script-no-login-for-more-than-10-days-and-send-email

Please let us know if you have any issues.

Kind Regards,
PremJK

That script will generate an alert if a user login hasn’t occurred on the endpoint in X number of days. What I am wanting to do is get an alert when the endpoint has been inactive in Itarian for X number of days. As in the endpoint has been and is still offline and hasn’t checked into Itarian. I’m not sure if there is a way to do that with a script since the script would only queue for the device until it comes back online again, assuming it comes back online at all. So this might be something that has to be added to the platform itself rather than running a script.

There’s the device offline monitoring alert that triggers within a time range when a device is offline. But it has a max time frame of 24 hours. I am needing something exactly like it that will allow me to trigger an alert only for when the devices has been offline for 30 days or 720 hours. That way we know that the device has been inactive for a long time and get a ticket on it to investigate further.

Hello,

i urgently need a script to download and run a .exe file. i have the file in a publicly accessible s3 bucket url. so ideally i’d like to place this url into the script.

Thanks @mcfproservices I was able to find a script in the thread history for this. The indentation was off but after reading a python tut or two i figured it out.

Just go back a few pages, plenty of examples listed, but script webpage appears offline at present.

mcfproservices

I need a script that will install the Free Comodo Internet Security (CIS Premium) Silently. Allowing you to choose which options you want in advance. For example I don’t want to install the comodo browser or set yahoo as my homepage. At first I tried to use the script below but didn’t know how to make it silent because the /S doesn’t work.

That’s what I was attempting to use.

import urllib
import os

def main(URL='https://cdn.download.comodo.com/cis/download/installs/8040/standalone/cispremium_installer.exe', sCMD='/S'):
Path=os.environ['PROGRAMFILES']
if os.path.exists(Path):
fn = URL.split('/')[-1]
fp = os.path.join(Path, fn)
try:
with open(fp, 'wb') as f:
try:
f.write(urllib.urlopen(URL).read())
print fp
except Exception as e:
print e
except Exception as e:
print e
try:
os.chdir(Path)
os.popen(fn +' '+sCMD).read()
os.remove(fn)
return 'Great! Successfully Installed'
except Exception as e:
return e
else:
return 'No path: '+Path+' is exist'

print main()

Ahhh I see that makes sense. Well thank you for looking at it.

I am trying to figure out how to write a script to remove Chrome from a machine. We are switching to using Edge exclusively and don’t want to have both Chrome and Edge as it’s just an extra program we have to keep updated. And the Chrome auto updater is not very reliable.