r/usefulscripts • • Aug 10 '15

[Powershell] Staff scheduled standardization script

19 Upvotes

Hello all,

I have an environment with AD linked with 365 and an issue where information needs to be put in via ADSI. if a new user is created, company details have been forgotten to be entered, in addition to no email policy (due to no onsite exchange). I've cooked together this script to help resolve what is required in my environment, but figure there's lots of useful commands inside to be cannibalized for other purposes. Figured i'd share the love


<#Used for setting users information in AD & 365 excahnge with dirsync#>

Import-Module ActiveDirectory

<#Specify email alais domains to be set later, as there is no email policy (no onsite exchange)#>

$firstdomain = "@domain.com"

$Seconddomain = "@domain.ca"

$Thirddomain = "@branchemail.com"

<#Group that calendar shares will be exempt from#>

$group = "CN=domain admin*"

<#Pre-programed 365 creds#>

$PlainPassword = "Password"

$SecurePassword = $PlainPassword | ConvertTo-SecureString -AsPlainText -Force

$UserName = "[email protected]"

$LiveCred = New-Object System.Management.Automation.PSCredential -ArgumentList $UserName, $SecurePassword

<#$LiveCred = Get-Credential #use if you want to be prompted for password #>

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection Import-PSSession $Session

$Employees = import-csv "I:\Scripts\Active Directory\employeeinfo.csv"

<#


A CSV with user information that is also posted to a company directory webpage

here is sample of layout

Branch,Employee Name,Cell,Bus Phone,Ext,Bus Fax,Business E-mail,Job Title BranchIT,Andrew Krahn,.,123456789,.,8888888888,[email protected],Service Detailer BranchIT,Andy Livingston,.,123456789,01234,88888888,[email protected],Parts Sales BranchNS,Barry Kluz,987654321,123456789,01235,9999999999,[email protected],Sales Rep

branchIT compnay phone is 12345689, with fax 8888888888 branchNS compnay phone is 987654321, with fax 9999999999

I've set it so that . = clear in the script later


>

<#$Users is the OU that the program looks under, and $site is the folder that the files will be created. multi users for multi branches#>

$userou = "OU=branhces,DC=domain,DC=com"

$users = Get-ADUser -Filter * -SearchBase $userou -Properties *

$ITuserou = "OU=IT,OU=Branches,DC=Domain,DC=com"

$ITSite = "\Domain.com\Shares\Home\IT"

$ITusers = Get-ADUser -Filter * -SearchBase $ITuserou -Properties *

$ITPath = "$ITSite$($ITuser.SamAccountName)"

$NSuserou = "OU=NS,OU=Branches,DC=Domain,DC=com"

$NSSite = "\Domain.com\Shares\Home\NS"

$NSusers = Get-ADUser -Filter * -SearchBase $NSuserou -Properties *

$NSPath = "$NSSite$($NSuser.SamAccountName)"

<#Runs for each branch: Sets home drive, creates home drive folder and sets access to admin and users only,loads address informaiton for branch (multiple for loops for each branch), and sets multiple email alaises (SMTP = primary smtp, again why we run for each branch, as branches may have different primary smtps)#>

ForEach ($ITUser in $ITUsers)

{

Set-ADUser -Identity $ITUser.SamAccountName -HomeDirectory "$ITSite$($ITuser.SamAccountName)" -HomeDrive H:

mkdir "$ITSite$($ITuser.SamAccountName)"

Get-Acl "$ITSite$($ITuser.SamAccountName)" | Format-List

$acl = Get-Acl "$ITSite$($ITuser.SamAccountName)"

$acl.SetAccessRuleProtection($True, $True)

$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("Administrators","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")

$acl.AddAccessRule($rule)

$rule = New-Object System.Security.AccessControl.FileSystemAccessRule($ITUser.SamAccountName,"FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")

$acl.AddAccessRule($rule)

Set-ACL -path "$ITSite$($ITuser.SamAccountName)" -aclobject $ACL

Set-ADUser -Identity $ITuser.samaccountname -Replace @{streetAddress="123 fake street";L="Bluff";postalCode="r1r 1r1";st="MB";co="Canada"}

Set-ADUser -Identity $ITuser.samaccountname -Replace @{Proxyaddresses=("SMTP:"+$ITuser.samaccountname+$firstdomain),("smtp:"+$ITuser.name+$firstdomain -replace '\s',''),

("smtp:"+$ITuser.samaccountname+$Seconddomain),("smtp:"+$ITuser.samaccountname+$thirddomain)}

}

ForEach ($NSUser in $NSUsers)

{

Set-ADUser -Identity $NSUser.SamAccountName -HomeDirectory "$NSSite$($NSuser.SamAccountName)" -HomeDrive H:

mkdir "$NSSite$($NSuser.SamAccountName)"

Get-Acl "$NSSite$($NSuser.SamAccountName)" | Format-List

$acl = Get-Acl "$NSSite$($NSuser.SamAccountName)"

$acl.SetAccessRuleProtection($True, $True)

$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("Administrators","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")

$acl.AddAccessRule($rule)

$rule = New-Object System.Security.AccessControl.FileSystemAccessRule($NSUser.SamAccountName,"FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")

$acl.AddAccessRule($rule)

Set-ACL -path "$NSSite$($NSuser.SamAccountName)" -aclobject $ACL

Set-ADUser -Identity $NSuser.samaccountname -Replace @{streetAddress="456 liar street";L="spoot";postalCode="t1t 0t0";st="ON";co="Canada"}

Set-ADUser -Identity $NSuser.samaccountname -Replace @{Proxyaddresses=("smtp:"+$NSuser.samaccountname+$firstdomain),("smtp:"+$NSuser.name+$firstdomain -replace '\s',''),

("smtp:"+$NSuser.samaccountname+$Seconddomain),("SMTP:"+$NSuser.samaccountname+$thirddomain)}

}

<#Phone informaiton from csv. goes through ad and compares them to CSv list#>

Foreach ($user in $users) {

foreach ($Employee in $Employees)
{

    If ($user.name -eq $Employee."Employee Name")
    {
    
        if ($Employee."Bus Phone" -eq ".")
        {
        Set-ADUser -Identity $user.samaccountname -Clear TelephoneNumber
        }           
        else
        {
        Set-ADUser -Identity $user.samaccountname -Replace @{TelephoneNumber=$Employee."Bus Phone"}
        }
    
        if ($Employee."Ext" -eq ".")
        {
        Set-ADUser -Identity $user.samaccountname -Clear otherTelephone,ipPhone
        }
        else
        {
        Set-ADUser -Identity $user.samaccountname -Replace @{otherTelephone=$Employee."Ext";ipPhone=$Employee."Ext"}
        }
               
        if ($Employee."Cell" -eq ".")
        {
        Set-ADUser -Identity $user.samaccountname -Clear Mobile
        }
        else
        {
        Set-ADUser -Identity $user.samaccountname -Replace @{Mobile=$Employee."Cell"}
        }
        
        if ($Employee."Bus Fax" -eq ".")
        {
        Set-ADUser -Identity $user.samaccountname -Clear facsimileTelephoneNumber
        }
        else
        {
        Set-ADUser -Identity $user.samaccountname -Replace @{facsimileTelephoneNumber=$Employee."Bus Fax"}
        }
        
        if ($Employee."Job Title" -eq ".")
        {
        Set-ADUser -Identity $user.samaccountname -Clear title
        }
        else
        {
        Set-ADUser -Identity $user.samaccountname -Replace @{Title=$Employee."Job Title"}
        }
        
        if ($Employee."Branch" -eq ".")
        {
        Set-ADUser -Identity $user.samaccountname -Clear physicalDeliveryOfficeName
        }
        else
        {
        Set-ADUser -Identity $user.samaccountname -Replace @{physicalDeliveryOfficeName=$Employee."Branch"}
        }   
    }
}

}

<#to enabled sent items in 365 shared mailboxes#>

foreach($user in Get-Mailbox -RecipientTypeDetails SharedMailbox)

{ set-mailbox ($user.alias+$firstdomain) -MessageCopyForSentAsEnabled $True }

<# to disable sent items in 365 shared mailboxe

foreach($user in Get-Mailbox -RecipientTypeDetails SharedMailbox)

{ set-mailbox ($user.alias+$firstdomain) -MessageCopyForSentAsEnabled $False }

>

<#to set 365 calendar permissions#>

foreach($user in Get-Mailbox -RecipientTypeDetails UserMailbox) {

$cal = $user.alias+":\Calendar"

<# if member of group, sets default access to none#>

if ((Get-ADUser $User.alias -Properties memberof).memberof -like $Group)

{ Set-MailboxFolderPermission -Identity $cal -User Default -AccessRights None }

<# if not member of group, sets default access to AvailabilityOnly#>

Else

{ Set-MailboxFolderPermission -Identity $cal -User Default -AccessRights AvailabilityOnly }

}


Enjoy

*edit: formatting :/ edit #2: changed order of set-ADUser otherwise it gives random formatting errors


r/usefulscripts • • Apr 14 '15

[PowerShell] Create a Report of Exchange Server Message Tracking Log Configuration

Thumbnail
exchangeserverpro.com
19 Upvotes

r/usefulscripts • • Feb 17 '15

[PYTHON] A script that periodically calls a command, like watch, but graphs the first integer in the output in your terminal.

Thumbnail
github.com
19 Upvotes

r/usefulscripts • • Feb 06 '15

[POWERSHELL] Get-EASDeviceReport.ps1 - Report on ActiveSync devices in your Exchange Server environment

Thumbnail
exchangeserverpro.com
19 Upvotes

r/usefulscripts • • Jan 23 '15

[BATCH] SINstaller script

19 Upvotes

Hey everyone. A while ago I posted the script I use to do some silent installations. Forgot my username so made a new one to post some updates. Hope you enjoy!

3 files:
(save as RUN_ME.bat http://i.imgur.com/xRbPdZz.png sorry reddit formatting is leaving out the _'s): http://pastebin.com/7nsrfWsA
(save as sin.bat): http://pastebin.com/YnL2qHCn
(save as addctrl.reg): http://pastebin.com/FPLsxK5P

First screen (flags):
http://i.imgur.com/04KHiUg.png

Second screen (config):
http://i.imgur.com/elD0pHi.png

Final screen:
http://i.imgur.com/Rf6kiWk.png

Changes:
-added: Unchecky
-updated applications to current version
-added: execution timer
-added: delete temp, driver temp files
-added: enable F8 menu on Win8
-added: add control panel option to right click

===========

TO USE: Download the appropriate setup files (I've decided not to post them this time since no one downloaded the full package last time I posted it). You can find the file names I used on lines 38-57 of sin.bat or here: http://i.imgur.com/ZfS71d9.png

edit:
full download since someone asked:
download: https://mega.co.nz/#!0Isl2ZKA!Ngu2mJFZy2DRebTbmlMLfH_KIXjc0UChExlognmcCb4
and md5's: http://pastebin.com/5DzXQcbA


r/usefulscripts • • Aug 21 '14

[BATCH] Reset Windows Update

19 Upvotes

I find it very common in my life that I have to do a Windows Update reset to clear a bad download, a poor server connection, etc, so I wrote this sucker to do that. The 'winsock reset' is an XP holdover, so it's not necessary if you aren't on XP. Took parts of this from around the web, so credit is most certainly not all mine. Also open to suggestions!

net stop bits
net stop wuauserv
Del "%ALLUSERSPROFILE%\Application Data\Microsoft\Network\Downloader\qmgr*.dat"
Rmdir "%Windir%\SoftwareDistribution\Download" /s /q 
Rmdir "%systemroot%\SoftwareDistribution\DataStore" /s /q 
Rmdir "%systemroot%\system32\catroot2" /s /q
::: Windows XP & 2003 - Delete %systemroot%\SoftwareDistribution\ as well
ver | findstr /i "5\.1\." > nul
IF %ERRORLEVEL% EQU 0 goto XP_OR_2003
ver | findstr /i "5\.2\." > nul
IF %ERRORLEVEL% EQU 0 goto XP_OR_2003
GOTO CONTINUE
:XP_OR_2003
Rmdir "%Windir%\SoftwareDistribution" /s /q 
:CONTINUE
sc.exe sdset bits D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;AU)(A;;CCLCSWRPWPDTLOCRRC;;;PU)
sc.exe sdset wuauserv D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;AU)(A;;CCLCSWRPWPDTLOCRRC;;;PU)
cd /d %windir%\system32
regsvr32.exe /s atl.dll
regsvr32.exe /s urlmon.dll
regsvr32.exe /s mshtml.dll
regsvr32.exe /s shdocvw.dll
regsvr32.exe /s browseui.dll
regsvr32.exe /s jscript.dll
regsvr32.exe /s vbscript.dll
regsvr32.exe /s scrrun.dll
regsvr32.exe /s msxml.dll
regsvr32.exe /s msxml3.dll
regsvr32.exe /s msxml6.dll
regsvr32.exe /s actxprxy.dll
regsvr32.exe /s softpub.dll
regsvr32.exe /s wintrust.dll
regsvr32.exe /s dssenh.dll
regsvr32.exe /s rsaenh.dll
regsvr32.exe /s gpkcsp.dll
regsvr32.exe /s sccbase.dll
regsvr32.exe /s slbcsp.dll
regsvr32.exe /s cryptdlg.dll
regsvr32.exe /s oleaut32.dll
regsvr32.exe /s ole32.dll
regsvr32.exe /s shell32.dll
regsvr32.exe /s initpki.dll
regsvr32.exe /s wuapi.dll
regsvr32.exe /s wuaueng.dll
regsvr32.exe /s wuaueng1.dll
regsvr32.exe /s wucltui.dll
regsvr32.exe /s wups.dll
regsvr32.exe /s wups2.dll
regsvr32.exe /s wuweb.dll
regsvr32.exe /s qmgr.dll
regsvr32.exe /s qmgrprxy.dll
regsvr32.exe /s wucltux.dll
regsvr32.exe /s muweb.dll
regsvr32.exe /s wuwebv.dll
netsh reset winsock
proxycfg.exe -d
net start bits
net start wuauserv
bitsadmin.exe /reset /allusers
wuauclt /resetauthorization /detectnow

r/usefulscripts • • Oct 28 '26

[PowerShell] Azure Network Topology to Draw.io Files

Thumbnail
gallery
18 Upvotes

Maybe it is useful for others as well:

As a security analyst, I’ve always found Azure network reviews tedious. In environments without consistent naming or structure, things get chaotic quickly, and understanding the setup can take a hundreds clicks in the portal. I usually ended up drawing the network in draw.io by hand.

Since draw.io files are XML, I wondered how much of that work I could automate. That became VNetAtlas. It generates editable diagrams showing VNets, subnets, peerings, resources, and connected components such as gateways, NSGs / Azure FW (including the rules), and public IPs. It uses the AZ PS Module for authentication and to run the KQL queries.

I mainly use it to get an overview of the network and its components, review NSG / Azure FW rules.

Note: The code was written with substantial help from AI coding assistants. I’m sharing it in case it saves someone else a few clicks, or a few tokens spent building something similar.

Feel free to try it, share feedback, down-vote or ignore it:

https://github.com/zh54321/VNetAtlas


r/usefulscripts • • Jan 24 '25

[PowerShell] A module for auditing activity on Microsoft 365 OneDrive Accounts

Thumbnail
github.com
18 Upvotes

Soon, Microsoft will begin billing for the storage used by unlicensed OneDrive accounts.

Microsoft doesn’t make it easy to find detailed activity information for OneDrive accounts. While their reports provide a last activity date and time, this can be influenced by various sources, leaving critical gaps in understanding how accounts are actually being used.

So, I made a PowerShell module for auditing activity on OneDrive accounts using the Unified Audit Log.

Check out the project on GitHub: https://github.com/cstringham/onedrive-activity


r/usefulscripts • • May 03 '24

[BATCH] Java Runtime Nuker - purge EVERY version of Java Runtime from a machine (excludes JDK)

18 Upvotes

Bottom line: "Gotta catch 'em all"

If a JRE manages to squeak through, post here or PM me and I'll update the script to catch it.

UPDATE 2024-04-30: I am still actively maintaining this script and will continue to do so for the foreseeable future. PM me if you have any problems with it.

Because of inconsistencies in Sun/Oracle's installation methods and naming conventions, there's no "one way" to purge every outdated Java Runtime from a machine, so I spent 15 18 ~23 hours collecting various methods of removing Java and integrated them into a single script. This should give you a "clean slate" to work with for laying down new versions of Java.


---->> Download from Github here <<----


Notes:

  • Removes all versions of the Java Runtime Environment (series 3 through 11), x86 and x64

  • Will catch future updates to JRE 5, 6, 7, 8, 9, 10, 11+

  • Checks WMI before running, repairs if broken

  • Searches for residual registry keys, backs them up, then deletes them*

  • Searches for residual files and directories and deletes them

  • Removes the Java Quickstarter and Java Updater services

  • Leaves all Java Development Kit installations intact

  • Writes a logfile to C:\Logs\<hostname>_java_runtime_removal.log (configurable)

If you have additional methods that work for you, please post them below or do a PR on Github. If they catch something the script misses, I will integrate them. Critique and advice welcome.

*Registry cleanup is skipped on Windows XP. This is because of differences in the reg.exe binary on XP. If anyone can look at how to search the Windows XP registry for leftover keys, I can integrate it into the script, but right now that section is skipped.


r/usefulscripts • • Jan 07 '24

Batch Script that restarts all audio services, fixs many audio errors without a reboot.

Thumbnail self.batchfiles
18 Upvotes

r/usefulscripts • • Sep 25 '22

[Script Sharing] Teraterm Automated SSH command launcher.

18 Upvotes

I appreciate Teraterm and the scripting language it uses is old, however if someone else is using it and find something useful here then great.

These scripts were build for doing generic changes/data collection across Cisco networking devices cause the company I work for was too dumb and slow to invest in a management/monitoring platform for the last 10 years.

The scripts needs some text files and those files need to sit in the same directory as the macro.
ip.txt -> List all the addresses that need to be accessed
commands.txt -> Lists all the commands you want to run

The script will give you a prompt box for username and password, then it will create SSH connections to the IP addresses, listed in the ip.txt file. Once Teraterm forms a connection, it will input the username and password you supplied earlier and then run the commands listed from the commands.txt file.

If there are multiple commands the macro waits for a # character before launching the next command. If no connection is made a message is pasted to the test.txt file to mention that.

All text displayed on the screen will be saved in test.txt file.

Enjoy

getdir dir
setdir dir
timeout = 60

inputbox 'username:' ''
username = inputstr
passwordbox 'Enter password:' ''
password = inputstr
;test = 'test.txt'
fileopen addressfile 'ip.txt' 0

:nextaddress

filereadln addressfile ip
pause 1
if result=1 goto leave

msg = ip
strconcat msg ':22 /ssh /2 /auth=password /user='
strconcat msg username
strconcat msg ' /passwd='
strconcat msg password

timeout = 10
pause 1
connect msg
pause 1

if result=1 goto noconnect
pause 1
changedir dir
logopen 'test.txt' 0 1 1 0
logwrite #13#10#13#10
logwrite ip
logwrite #13#10
gettime time
logwrite time
logwrite #13#10
call loop3

goto nextaddress
;#####################################################################################################################
:noconnect
fileopen test 'test.txt' 1 0
filewrite test #13#10#13#10'Failed to connect'#13#10
filewrite test ip
filewrite test #13#10
gettime time
filewrite test time
filewrite test #13#10
fileclose  test
goto nextaddress

;#####################################################################################################################
:loop3
timeout = 300
wait '#'
mpause 500
logwrite ip 
logwrite #13#10
mpause 500
fileopen commandfile 'commands.txt' 0
:loop4
filereadln commandfile command
if result=0 then
sendln command
wait '#'
mpause 500
goto loop4
endif
fileclose commandfile
sendln 'logout'
return

;#####################################################################################################################
;#####################################################################################################################
:leave
end

r/usefulscripts • • May 15 '21

[PowerShell] Roll ASCII Art Dice in Powershell

Thumbnail
self.powershell
18 Upvotes

r/usefulscripts • • Jul 02 '19

[Request] Script to install Network Printer

18 Upvotes

Hello, I am looking to have a script connect two network printers. One is an "HP ENVY 4500" and the other is an "EPSON Artisan 725". I have been looking online and have not found one that i can easily do. Can someone help me because I would like to add this to my PXE Deployment as part of the task so that everything is installed and working correctly. I have already added the drivers into the image so really all i need to do is connect them. Can someone please help me with this? My school has a script that it searches the network and then you type the name of the printer and it installs it. Something like that would work fine. Also both printers have a static IP set in DHCP reservations.


r/usefulscripts • • Dec 05 '18

[BASH] Verify, check, and install Veracrypt

18 Upvotes

Since posting the backup.sh script a couple days ago, I've improved upon it a lot. I'm writing scripts that automate things I do frequently, or things that are really annoying to do.

One of those annoying things for me is installing Veracrypt. I know I need to verify the download, but that involves adding their GPG key, trusting their GPG key, downloading the binaries and their GPG signature file, verifying the binaries, downloading the SHA512 sums and their GPG signature file, verifying the sums, and checking the sums. Frankly, I find doing all that annoying, so I wrote this script.

From the README on GitLab:

Invoke from terminal with bash install_veracrypt.sh and follow the printed instructions. That's it.

This script will...

  1. download VeraCrypt version 1.23 (which is the latest version as of december 4, 2018) and all relevant signature, GPG, and sum files from the official links on https://www.veracrypt.fr/en/Downloads.html,

  2. add the VeraCrypt GPG key to your keyring (after asking you if the fingerprints match),

  3. walk you through setting VeraCrypt's GPG key trust level to 4,

  4. validate the GPG signature of both the installation files and the sums text file,

  5. check the SHA512 sum of the installation files,

  6. and finally install either 32- or 64-bit VeraCrypt depending on your OS.

Here's the link to the repo: https://gitlab.com/krathalan/bash-veracrypt-installer-script

Merge requests and suggestions are welcome.


r/usefulscripts • • Mar 27 '18

[REQUEST][POWERSHELL] Convert from Date Time String into Date Time Object.

18 Upvotes

I'm pulling dates from various sources and I need to convert them into a datetime object for further manipulation in the script.

The date & time format is mostly consistent following this format:

Get-Date -Format 'M/d/yyyy h:mm tt'

So I'm using [DateTime]::TryParseExact to do the conversion:

$SampleDT1 = '‎9/‎2/‎2011 ‏‎6:47 AM'
$ResultDT1 = New-Object DateTime
[DateTime]::TryParseExact($SampleDT1, 'M/d/yyyy h:mm tt', [System.Globalization.CultureInfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::None, [ref]$ResultDT1)


$SampleDT2 = '8/‎30/‎2011 ‏‎2:42 PM'
$ResultDT2 = New-Object DateTime
[DateTime]::TryParseExact($SampleDT2, 'M/d/yyyy h:mm tt', [System.Globalization.CultureInfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::None, [ref]$ResultDT2)


$SampleDT3 = '‎9/‎1/‎2011 ‏‎1:47 PM'
$ResultDT3 = New-Object DateTime
[DateTime]::TryParseExact($SampleDT3, 'M/d/yyyy h:mm tt', [System.Globalization.CultureInfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::None, [ref]$ResultDT3)

Each time it comes back as false and I need some help demystifying why.


r/usefulscripts • • Dec 14 '17

Help with Local Account script

Thumbnail
self.powershell
18 Upvotes

r/usefulscripts • • Sep 15 '17

[Request] Get OS of Remote computer

18 Upvotes

Hello, I am not sure if this is possible or not, but I have an IP list with their OS and I need to verify if it is accurate or not. They are all different Operating Systems, some Unix, Linux, Windows, CISCO, etc. Is there a script I can run to be able to check the OS?


r/usefulscripts • • Jun 06 '17

Renaming files from a file?

18 Upvotes

I used the command:

"ls -LR > file-name.txt"

To generate the contents of a directory in a text file. I wanted to know if it is possible to go in and rename the files in the text file and then run a script to actually rename the files based on the modified text file. I know this is a difficult request, any help is appreciated.

OS: Linux Mint 18.1 File generated from command line: ls -LR > file-name.txt


r/usefulscripts • • May 15 '17

[Powershell] Need help fixing script

18 Upvotes

edit: I appreciate everyone's help - it turned out to be the firewall (not windows one that I initially turned off but the physical fortinet). I'm a network engineer and I didn't even check that. Not knowing anything about code, I immediately assumed it was a code issue between versions of powershell and posted it here. Thanks again!!

I'm hoping this will be easy for you guys. I am not a script writer and know very little about how it works but I do know this:

a) it worked on our windows 7 machines and now under windows 10 I receive an error message b) the error message is (slightly edited): Exception called "Send" with a "1" argument(s): "Failure Sending mail." position 24: char:2

  • $smtp.send($message) +categoryinfo: not specified: (:) [], MethodInvocationException +FullyQualifiedErrorID: SmtpException

script:

$SMTPServer = "smtp.gmail.com" $SMTPPort = "587" $Username = "[email protected]" #Enter your gmail address $Password = "12345" #Enter your google app password

$to = "[email protected]" #TO email address $subject = "Payroll" #Subject line $body = "X location, payroll file" #Email body text $attachment = "C:\payroll\PR001EPI.csv" #full (absolute) attachment file path

let's make sure the file exists before sending email

if( Test-Path $attachment -PathType Leaf) { $message = New-Object System.Net.Mail.MailMessage $message.subject = $subject $message.body = $body $message.to.add($to) $message.from = $username $message.attachments.add($attachment)

$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.send($message)

write-host "Email succesfully sent to $to with the following attachment: $attachment"

} else #unable to find file attachment, exit script { write-host "[ERROR] Unable to find $attachment" Return }

Any help would be greatly appreciated. The individual who wrote this script no longer works for us. It's simply supposed to grab a CSV file with payroll data, make a connection to a gmail account and email it to our accountant.


r/usefulscripts • • Sep 08 '16

[BASH] Tar intercept function for your .bashrc, to suppress output messages in STDERR (i.e. the annoying "SCHILY" messages from archives created in MacOS).

Thumbnail
github.com
18 Upvotes

r/usefulscripts • • Feb 11 '16

[CSV File] FCC Telemarketer and RoboCall Blacklist for Google Contacts 02/08/2016

Thumbnail
pastebin.com
18 Upvotes

r/usefulscripts • • Feb 09 '16

[PowerCLI] Storage vMotion a VM with 2 disks

18 Upvotes

X-post from /r/PowerCLI

Hello, I recently came across a need to storage vMotion a VM that had 2 disks on two different Luns and quickly realized that Move-VM couldn't handle this. So I threw a quick function together to be able to handle 2 disks. It could easily be modified to handle more, but two was all I needed and I figured was more common config than 3 or more disks. You just need to provide the LUN names where the disks reside and the corresponding LUN names where you want each one to go. The only caveat is I didn't write it to take into account if the VM has multiple disks on the same LUN. The script will detect this and exit with an error. Hope someone might find it helpful.

http://pastebin.com/EMs6V4RK

EDIT: I realized I hadn't tested this script in the situation where I might only want to move 1 of the 2 disks of a VM. Well, I just ran it where I had the original and destination LUN name the same for one of the disks and it doesn't process that disk at all and cuts the time of the task down. So it will still function to move only one disk, you'll just need to keep the LUN name the same for the corresponding original and destination names of the disk you don't want to move.


r/usefulscripts • • Dec 19 '15

[BASH] Simple Google Dynamic DNS update script with logging

Thumbnail
pastebin.com
18 Upvotes

r/usefulscripts • • Sep 11 '15

[Request][Batch] Shut down windows telemetry (and maybe windows 10 compatibility updates

18 Upvotes

I'm not sure if this is the right place to be asking as I won't have access to stuff like WSUS that many of you use, but I've been looking into stuff like this for blocking all the new windows 10 and new telemetry stuff.

It looks like I can uninstall those updates if already present, I know with vbs I can hide updates, the services should be trivial, and I think I can disable the tasks via command line too with setting a variable as a password and echoing it to schtasks.

I'm just wondering if anyone else has already done this and could save me the effort, if I'm heading about this the wrong way because I'm missing something, or if I should just do this and post the script here when I'm done.