r/usefulscripts • • Dec 05 '17

How do I use a batch file to create a folder in each subfolder with the name based on the level of the subfolder

16 Upvotes

My boss has decided to create a folder in each folder level on our server to designate what level it is from the base folder, so _A will be the first folder level, _B will be the second level, _C the third and so on as shown below

  • C:\Stuff

  • C:\Things

  • C:_Level A

  • C:\Stuff\Things

  • C:\Stuff_Level B

  • C:\Stuff\Things\More Things

  • C:\Stuff\Things_Level C

  • C:\Stuff\Things\More Things_Level D

  • C:\Things\Things

  • C:\Level B

  • C:\Things\Things\More Things

  • C:\Things\Things_Level C

  • C:\Things\Things\More Things_Level D

For what its worth I don't think its a great idea but it not my call. What annoyed me was watching one of our office staff doing this manually. I asked if it could wait a day or to while I figure out a more efficient way of doing it.

I'm sure there'll be a way to do it with a batch file but I can't figure it out.

Can anyone give me some direction.

Edit:- I've just been told we only need to go down 4 levels, so down to C:/Stuff/Things/More Stuff.


r/usefulscripts • • Dec 04 '17

Request: CMD, PowerShell, EXE with CMD script for backing up Chrome, Firefox profiles

16 Upvotes

As the title says.

We are working with SCCM task sequencing to create in-house tools for User State Migration. One of the current road blocks is figuring out command line scripts to automate backing up browser profiles.

Basically, would any of you happen to be able to provide some guidance for scripted commands that run in CMD, PowerShell, EXE with CMD to accomplish the above task?


r/usefulscripts • • Sep 26 '17

[Help] Powershell- Trying to create a variable that specifies arguments to tack on... Sort of?

16 Upvotes

Hey Scripters,

I'm working on some things in powershell and I came to a standstill.

I have a script that has pretty much ONLY GWMI commands to get system info(let's call it script2). I have another script that I would like to call that will specify specific options for the script: stuff like how to execute the commands in remote or local contexts.(script1)

Each command looks like this:

$var = gwmi Win32_Bios -Computer $name -Credential $cred -Impersonation 3

What I would like to do, if possible, is make a variable that houses the -computer,-credential,and -impersonation arguments so that they can be modified upon execution. That way the block could just be "$var = gwmi Win32_Bios", and IF the command SHOULD have additional args, they could be appended.

Essentially, i want to have a single block of code that I can add functions to, instead of having a switch or something that has redundantly written commands.

Script1 will pass options to script2, which will handle the options, and modify the commands accordingly. But alll the commands would still be gathered together in a single block, no matter what methods are used. If I could have a variable that would house these options for example, it would allow me to keep control and execution separate. Does that make sense?

I would also love to know if there is a way to do remote wmi queries(-computer arg) and save each output of them to a CSV(on the scriptrunner's host) , without passing in the remote machine's credentials every single time. I know you can do this with psRemoting but I don't know how I could work it with just direct remote queries.

Thanks for the help!


r/usefulscripts • • Aug 02 '17

Echoargs help, script request

16 Upvotes

I have the rest of my powershell working except when using this third party utility to stamp pdfs, it calls a cpdf from the same directory that powershell is ran and works if I manually type it, but when it gets to the $inputfile name and $outputfilename it acts as if nothings there, I echoed the contents of the inputfile name and output and it works, manually copied and pasted it from a log and it worked.

I'm thinking I have to do an invoke expression or & call program but I don't know how the argument list would work?

 .\cpdf.exe -add-text "%filename" -top 100pt -font "Times-Roman" -font-size 20 $inputfile -o $outputfile  

r/usefulscripts • • Jul 14 '17

[REQUEST] How to "FIND /V" more than one entry, without having to pipe every entry separately

16 Upvotes

I'm trying to make a one-liner script that displays some basic details of all locally installed printers but does not include virtual printers like CutePDF or Send to OneNote.

So far I have

wmic printer where local=TRUE get name, drivername, systemname, portname, location, description  

I would like to pipe this into a FIND /V to eliminate many common virtual printers from the results, ideally using a text file, but I can't seem to find a way to do this.
I'd really like to avoid having to pipe it separately for each entry, because this would look really ugly and be hard to manage:

wmic printer where local=TRUE get name, drivername, systemname, portname, location, description | find /v "Send To OneNote" | find /v "XPS Document Writer" | find /v "Foxit Reader PDF Printer" | find /v "your mom" | find /v "CutePDF Writer"  

Any ideas on a better way to accomplish this?

(I'm also open to finding a way to do this in Powershell, but I'm still learning it so haven't found a way yet)


r/usefulscripts • • Mar 06 '17

[Request] Merge multiple excel files into one big one

16 Upvotes

I need to script our timesheet system as it is a time drain on the finance department.

So far I am saving all excel attachments from a mailbox to a network storage location. Now what I want to do is merge all these files into one and save in the finance drive.

I have made a few attempts but the formating isn't right. Note, the timesheet is using a formula.


r/usefulscripts • • Jan 12 '17

[Request] export zip files of backups to network drive in Veeam

16 Upvotes

I'm looking for a script that would run down a list of VM backups in Veeam and export zip files of each backup to a network drive using stored credentials. Any help would be appreciated, even if you could just tell me what steps the script would need and I can google how to get it done myself.


r/usefulscripts • • Dec 27 '16

[PowerShell]Show-InputForm • /r/PowerShell x-post

Thumbnail
reddit.com
16 Upvotes

r/usefulscripts • • Dec 15 '16

[REQUEST]Script to RoboCopy user profiles based on AD group

16 Upvotes

I am quite new to PowerShell, but haven't mastered it enough to figure this out.

So, I have a 'Role-Managers' group that has nested groups for the different types of managers that we have. I need to somehow pull all of these usernames from this group, then go out to their PCs to backup their data using RoboCopy or anything else that would copy just the new data. The problem is that the PCs all have generic names, so I will also need to create another group in AD with nothing but the Manager PCs included. I feel like an array of the Role-Manager usernames needs to be created, then cross-referenced with the Manager PCName group, then allow RoboCopy to step in and update as needed. It'd be even better if I could get it to exclude AppData or other folders, but I am not expecting that much.

If anyone has anything like this that is commented to help me through the process, it would be greatly appreciated! I want to learn more of PowerShell, so the more I go through commented scripts, the better off I am for later, but this particular request is far more than I know.


r/usefulscripts • • Nov 29 '16

script to close open files from server (xpost from r/sysadmin)

16 Upvotes

Hello - i was pointed in this direction from r/sysadmin. below is my original post.

hello r/sysadmin - i am hoping you can help me.

I am looking for a way to run a batch script to close all open files from our file server. I have done some googling and found the following fixes:

net session /DELETE

net files [file id] [/close]

this script: from [here] (http://stackoverflow.com/questions/14672479/how-do-i-close-all-open-network-files-in-powershell)

for /f "skip=4 tokens=1" %a in ('net files ^| findstr C:\Apps\') do net files %a /close 

and this powershell script: from [here] (https://social.technet.microsoft.com/Forums/office/en-US/e03753fa-3f93-4677-ae21-3480dce103b7/help-with-powershell-script-to-close-open-files?forum=winserverpowershell)

$results = net file | Select-String -SimpleMatch "D:\Sap_Labels\"
foreach ($result in $results) {
#Get id
$id = $result.Line.Split(" ")[0]

#Close file
net file $id /close

}

However, if you read down the link where i found the second script people start talking about how "the script is closing them, but as they are still open on the destination client the session reopens as the resource is still being used." I can confirm this as I ran the script and checked through Computer Management -> Shared Folders -> Open Files and saw the files were closed, then upon a refresh in the Open Files window, the files would reopen automatically.

Am I correct in thinking that this is because the files are still open on the client side they auto-connect after the cmds/scripts are done running?

I read a bit about the Get-OpenSMBFiles cmdlet and wish that i could use it, but from what i can tell it is only available on Windows Server 2012 and above and our file server is running on Windows Server 2008 R2.

I am crossing my fingers that someone out there has run across this problem and can point me in the right direction.

Edits: because words are hard...


r/usefulscripts • • Oct 18 '16

[REQUEST] Script to copy cells from a column in a systematic order (vertically downwards) and replace them in iterations of a repeated spring in a text document

16 Upvotes

If I have a excel document with list of first names for instance, and I want to copy and paste those into a text file where the place holder value is continually iterated inside snippets of text, how would I do that or can someone assist me in making it.

More verbose example:

the below is just an example Excel: Take values from "A" column in excel, 1 by 1, and paste them into the textfile.txt in order (as if using find and replace and pressing next) and pasting them twice into the text file.

Column A values: matt, john, mary, bill

textfile.txt: is a script in php i wrote, it is very long but the portion in question which i must replace is this

//
// 'replacedvalue(with matt)' => array(
//     'nicename' => 'replacedvalue(with matt)' // optional
//     'price' => 'price here',
//     'description' => 'description here',
//     'not_for_sale' => false,
//     'image' => '' // background override
// ),
// 'replacedvalue(with john)' => array(
//     'nicename' => 'replacedvalue(with john)' // optional
//     'price' => 'price here',
//     'description' => 'description here',
//     'not_for_sale' => false,
//     'image' => '' // background override
// ),
// 'replacedvalue(with mary)' => array(
//     'nicename' => 'replacedvalue(with mary)' // optional
//     'price' => 'price here',
//     'description' => 'description here',
//     'not_for_sale' => false,
//     'image' => '' // background override
// ),
//

r/usefulscripts • • Jul 11 '16

[POWERSHELL] Move Computer Objects based on IP CIDR or based on Sites and Services

16 Upvotes

Two scripts to share.

The first allows you to move computer AD objects by CIDR value and the ou specified. That can be found on pastebin here Or on my github here

The second actually integrates with Sites and services to get the subnets. It can be found on pastebin here or on my github here

If you'd like a full run down on how the configuration works or a break down on some of the useful functions in the script check out my blog here

Thanks!


r/usefulscripts • • Jun 02 '16

[POWERSHELL] Detect if a word is a first name

16 Upvotes

One of the things I don't see done well as companies grow is verifying Ad users/Email Accounts were disabled. This task is often dumped on helpdesk and never completed properly. In order to facilitate fixing this I created a very simple function:

#BehindtheName APi
#Please read api rules: http://www.behindthename.com/api/

function firstname_search($name) {
$local_Name_Storage_File = ".\namestore.txt"
$key = "<read api rules and add key>"
$url = "http://www.behindthename.com/api/lookup.php?name=" + $name + "&key=$key" 
[xml] $content = invoke-webrequest $url | select -expandproperty Content

        if(get-content $local_Name_Storage_File -ea silentlycontinue | select-string "$name") {
        return $true
        } else {
         
        if($content.response.error | select-string "$content.response.error") {
        return $false
        sleep 1
        } else {
        echo "$name" >> $local_Name_Storage_File
        return $true
        sleep 1
        }
    }
}

It ties into the API from www.behindthename.com to verify the username's GivenName/Firstname So using Get-aduser such as:

import-module activedirectory
$lastloginrange = (get-date).adddays(-90)
$user_list = Get-ADUser -properties * -filter {(lastlogondate -le $lastloginrange) -AND (enabled -eq $True) -and (PasswordNeverExpires -eq $false)} | select-object GivenName, Surname, Displayname, Samaccountname, passwordExpired

foreach($user in $user_list) {
$firstName = $user.GivenName
$lastname = $user.Surname

echo "$firstname, $lastname"
    if(firstname_search $firstname) {
    echo "$firstName,$lastname" >> HR.csv
    } else {
    echo "$firstName,$lastname" >> it.csv
    }
}

We are able to generate 2 CSV files. 1 for IT/Helpdesk to review and 1 for HR to review.

You can get your api key by registering with behindthename and going to the api gateway. I urge you to read there usage rules. I also added a local file to search. Set a static path for the variable $local_Name_Storage_File. This lets you add very rare names that are not found on the API and over all decreases your API call count.


r/usefulscripts • • May 17 '16

[REQUEST] Every morning check if the contents of a file are correct. If not, replace the file with a file that contains the correct content.

16 Upvotes

I don't know where to start. I've never done scripting before. I desperately want to learn, however I don't know where to start. I am wondering if this script can be created for me or at least point me in the direction of creating it myself.

I basically want a script that checks a file for certain content in a file. If the file does not have the correct information. It'll replace it all with the correct information. If it has the correct information. It will just do nothing. Or maybe it'll still replace it. Idk what works best.

Here's the deal. Something on this network is causing a Quickbook's .ND file to change itself at least once a week. This breaks the Multi-User mode function of that company file.

Good File //This is QuickBooks configuration File. It exists while users are connected // to a company file. Do not delete this file yourself. QuickBooks may not // operate correctly IF you manually delete this file.

[NetConnect]

ServerIp=192.168.x.x

EngineName=QB_(redacted servername)_26

ServerPort=(redacted)

FilePath=(redacted)

ServerMode=1

FileConnectionGuid=(redacted)

Bad File //This is QuickBooks configuration File. It exists while users are connected // to a company file. Do not delete this file yourself. QuickBooks may not // operate correctly IF you manually delete this file.

[NetConnect]

EngineName=QB_data_engine_26

FilePath=(redacted)

ServerMode=2

FileConnectionGuid=(redacted)

So to sum up. I want the good file to be there every time. If it gets changed, then in the morning or even more routine checks to then replace the bad content with the good content. I am not sure if this will solve the issue. However I have not been able to find exactly where the issue is being caused. So I figured this may be a temporary fix.


r/usefulscripts • • Mar 15 '16

Mella – ownCloud upload in bash via WebDAV using curl

Thumbnail
github.com
16 Upvotes

r/usefulscripts • • Dec 21 '15

[POWERSHELL]Get Access Mask for ACLs - Windows Security-Tab GUI Style

Thumbnail
github.com
16 Upvotes

r/usefulscripts • • Oct 28 '15

[BATCH] Access phone storage over WiFi with WebDAV Server for Android

Thumbnail
gist.github.com
16 Upvotes

r/usefulscripts • • Sep 18 '15

Script Headers

16 Upvotes

What's in yours? Examples, if you want to share.


r/usefulscripts • • Sep 04 '15

Version Control Systems for Scripts

16 Upvotes

What do you use?


r/usefulscripts • • Jul 22 '15

Bash script for vHost creation and SSL Certificate installs

16 Upvotes

Hey guys,

UPDATED: http://pastebin.com/TR7tTS0Z Took the advice from you kind people and made some updates. Only thing I'm still working out is how to get it to do an apache check before breaking. Syntax checks don't work for SSL errors it would seem. Any suggestions?


r/usefulscripts • • Jul 15 '15

looking for a way to AUTO print a log file anytime its created.

16 Upvotes

looking for a way to AUTO print a log file anytime its created.

needs to be running all the time, looking in a directory for a log, when it sees it, needs to print, then delete the log...

any ideas?


r/usefulscripts • • Jul 04 '15

[POWERSHELL]Malicious Microsoft Office Documents: Generate-Macro

Thumbnail
github.com
16 Upvotes

r/usefulscripts • • Jun 03 '15

[Request] [POWERSHELL] Update attributes in AD based on unique attribute (not using SAMAccountName)

16 Upvotes

Hello,

A bit of history to explain why its set up the way it is. Working in higher education student accounts are created from a MIS system which has unique admission numbers for each student. We use this unique number in our AD under the attribute State but as this number is about 16 characters we create the SAMAccountName based on their intake year, surname and firstname to make it easier for the students (although they even forget this! but that's not important).

Tutor groups are also added to the account under Office this is used for dynamic email groups so staff can contact students in their group easy. This can also be used for other attributes but only worried about Office for now.

I am looking for a way so when information is exported from our MIS system into csv it will include the unique admission number and form group. I then pass this csv into a PS script which will

  • Load the records from CSV

  • For each record search for the Admission Number in the attribute State

  • If it finds it then it will update tutor group in the attribute Office

  • Move onto next record.

Is this possible? I know scripts exist similar to this but it requires knowing the SMAccountName. Any help or guides to the right direction will save me a lot of time managing 2000+ users.


r/usefulscripts • • May 19 '15

[Powershell] Bulk user account creation script with some input checking, many automatic features

16 Upvotes

Here it is: http://nonprofittechy.blogspot.com/2015/05/user-account-creation-script.html

Others asked for it in the /r/sysadmin sub, and I have actually been meaning to share it for a couple of years.

Any improvements are welcome, it is a little quick and dirty to get it to meet our needs. Some things I know are not ideal, such as the password saving, but I haven't fixed yet because the solutions I ran into so far have been difficult to adapt to my environment (multiple users need to run the script from different computers, so just locking the credentials won't work, e.g.).

But hopefully this will give people an idea of a real-world user account creation script that does a fair amount of automation.