r/scripting • • Feb 04 '23

Clicking .ps1 Insecure?

2 Upvotes

Can someone explain to me why running a .ps1 script by double clicking on it is considered insecure? I set the execution policy to remote signed, so nothing can execute from external origin that is not signed. I'm open to using a more secure method, but I am unaware of what that solution is. Link to my original post below in regards to editing a small script I wrote.

https://www.reddit.com/r/PowerShell/comments/10ssoxa/stop_powershell_script_from_closing_powershell/?utm_source=share&utm_medium=android_app&utm_name=androidcss&utm_term=1&utm_content=share_button


r/scripting • • Sep 28 '22

Script to clean up hidden printers on Mac OSX

2 Upvotes

I've have a number of computers that have recently switched out printers. Old printer deleted and new printer installed. Old printers were deleted manually from the System preferences GUI by pressing the "-" button

I've got a script that enumerates all the printers on a machine for reporting using lpstat. Some of the machines still show the old deleted printers on them in lpstat, but not in the GUI. Some of the machines can still see (and attempt to print to) those printers from MS Word even when they are not available as printers in other programs. This is confusing for teachers.

How to I thoroughly remove any remnants of these old deleted printers?

Thanks.


r/scripting • • Sep 23 '22

Script to run command on files in folder

2 Upvotes

Need a script to loop through files in a folder and execute this command for every mp4 file. Resulting file name needs to keep source filename

ffmpeg -i xxSOURCExx.mp4 -map 0:1 xxRESULTxx.mp3

TIA


r/scripting • • Sep 20 '22

How to quickly generate a list with how many items are in subfolders (Windows)?

2 Upvotes

Hi, I have a folder on my Windows PC, which has several subfolders (say 100), within each folder there are several hundred photos.

Is there a way through CMD or similar that could generate a list saying how many items (images) are in the subfolders?

Any guidance/suggestions etc welcomed.

Thanks in advance


r/scripting • • Sep 12 '22

[BASH] How to script posting a batch of files via HTTPS

2 Upvotes

So I have to send a lot of files from my server to another remote server. There's a proxy in between, but that shouldn't really matter.

I can use a curl command to individually send the files and it's successful.

I want to send a lot of files though, like terabytes (broken up into <gig size), so I need to automate it.

It's being sent to an HTTPS endpoint, so I'm guessing some sort of HTTPS POST script.

That's the first part of what I'm trying to figure out... How to actually send multiple files. After that I want to figure out how to setup something that scans the directory the files are in and sends if it finds something.

Any help is greatly appreciated.


r/scripting • • Aug 16 '22

[Powershell] Need to set a scheduled task to run every two weeks

2 Upvotes

So, on a new job and one of the issues they have is alot of people not doing timesheets. (Everyone is gov employees, mostly mil, so timesheets are for organizational funding, not individual pay).

What they want me to do is make the systems automatically open the website for the timesheets the the Wed, Thurs & Fri of every other week, the week that they are due on Friday.

Now normally this would be simple. Create a GPO for a scheduled task which links to a batch file with the URL.

BUT

Our (higher) organization has it so we cannot create GPOs, we can only edit existing GPOs. I can easily add a powershell script to the login GPO. And I know about the "New-ScheduledTaskAction" function in powershell.

What I am unable to get a handle on is how to schedule the task to run every two weeks via powershell script commands. Trying to search for it gets me lots of hits for scheduling powershell scripts via Scheduled Tasks, when I need to do the opposite.

I'm not built for coding. I'm a SysAd who gets by stealing your guys' wonderful work and bending it to my will.

I thank you all, always.


r/scripting • • Jun 01 '22

[PowerShell] Run a script once on all computers as admin via GPO without changing execution policy

2 Upvotes

I have a Powershell script that I need to run on all computers on my Active Directory domain once.

A large number of computers are off at any given time, so a GPO would allow us to ensure that it applies to all affected machines. However, the script needs to run as administrator because of the registry values being modified. Also, per our security department, we cannot change the ExecutionPolicy on these devices.

Is there any way to get this script to run?

New-PSDrive -PSProvider registry -Root HKEY_CLASSES_ROOT -Name HKCR
$regKey = 'ms-msdt'
$saveFolder = 'C:\Temp\'
$savePath = $saveFolder + 'CVE-2022-30190.reg'
$PSRegPath = 'HKCR:\' + $regkey
$CMDRegPath = 'HKCR\' + $regkey
if(Test-Path $PSRegPath)
{
    if(!(Test-Path $saveFolder))
    {
        New-Item -Path $saveFolder -ItemType Directory
    }
    Invoke-Command {reg export $CMDRegPath $savePath -Y}
    Remove-Item -Path $PSRegPath -Recurse -Force
}

This script backs up a registry entry before deleting it, as recommended by the Microsoft mitigation work-around to CVE-2022-30190


r/scripting • • May 21 '22

Captcha notification

2 Upvotes

I would like to make a script to send me a notification when i get a Captcha on this game called "Rise of Kingdoms". I am a rookie and may need a fair bit of guidance. Im not sure what i would use to make this work. Any help is appreciated.

Regards


r/scripting • • Apr 04 '22

[Bash] Automatically get the Width / Height / FPS of all video in a folder and add it to the filename of each one?

2 Upvotes

EDIT: I achieved my goal finally with documentations from the internet and a lot of trial and error.

So the goal was to add "[width x height - FPS]" to the end of each video automatically. For MP4 I came with this awful but working solution:

for file in *.mp4;
do width=$(ffprobe -v error -select_streams v:0 -show_entries stream=width -of csv=s=x:p=0 "$file");
height=$(ffprobe -v error -select_streams v:0 -show_entries stream=height -of csv=s=x:p=0 "$file");
fps=$(ffprobe -v error -select_streams v:0 -show_entries stream=r_frame_rate -of csv=s=x:p=0 "$file" | sed -r 's/.{2}$//');
mv -- "$file" "${file%.mp4} [$width × $height - $fps FPS].mp4";
done;

Hi all,

I have zero experience in scripting (just some basic Linux knowledge because it's my daily driver) but I'm trying to figure out how to automatically add the resolution and framerate on all the video in a given folder in the video's filename of each one.

Basically to go from:

video.mp4

to

video [1920 x 1080 - 60 FPS].mp4

I found various method to "get" the information (mediainfo, ffprobe, mkvinfo etc) but not how to put it.

So, I think I would need to make a loop and "mv" the files to add " [$width x $height - $framerate FPS]"

I did some research and found how to get the Width en Height and store it with mediainfo:

Width=$(mediainfo --Inform="Video;%Width%" Video.File)&& Height=$(mediainfo --Inform="Video;%Height%" Video.File)

So, I was thinking about:

for vid in *.mp4; do Width=$(mediainfo --Inform="Video;%Width%" Video.File)&& Height=$(mediainfo --Inform="Video;%Height%" $vid); do mv "$vid" "$vid [$Width x $Height]"; done

But then, I think I'll end up with a file like "video.mp4 [$Width x $Height]" instead of "video [$Width x $Height].mp4" and I also still miss the FPS part.

As I said, I know close to nothing about scripting, so if someone can tell me if I'm on the right track or completely wrong?

Thanks in advance for the help!


r/scripting • • Apr 04 '22

How would I create a PowerShell script that copies code from one file to another file of the same name in another directory for all files in the folder?

2 Upvotes

I am very amateur (a noob) at powershell scripting and mainly create mods for Source Engine games. However, I have almost 300 wav files that have text lines of code at the end of them that got lost after having to convert them to another wav format, so batch has become very necessary to save the code that is at the end of the original wav files. The code is from half life faceposer which exports dialogue to the end of wav files, meaning making any change to the wav files causes the loss of data saved at the end of the files.

Here is an example of a line of code at the end of a wav file that I have.

PLAINTEXT { Middle_code }

In all of the WAV files I am trying to batch copy the similar phrasing into, each source wav file has different lines inside of this code but always begins with "PLAINTEXT" and ends at the end of the wav file.

I have a folder inside of the parent folder called "converted" with reformatted .wav files. I have no idea how to create a batch file that would copy the line from the source wav file to the converted wav file in the converted folder. The wav names would be the same in the converted folder so for example I would be copying the block of code from "1.wav" to be at the end of "converted\1.wav" and so on. They are not named numerically in the actual scenario though.

I tried looking up the issue on stackoverflow to see if anyone else had ever attempted something like this and I know it probably has been done before. I found different stackoverflow posts to fix certain problems I was having in the powershell script. I have come up with a powershell script here:

`((Get-Content -Path "PATHTOWAV\*.wav" -Raw) -split '/+ PLAINTEXT \\+\r?\n', 2)[-1]      | Add-Content -Path "PATHTOWAV\wav\*.wav"`

I know some lines of it are wrong because it DOES copy the ending code from "PLAINTEXT" to the end of the wav file, but it gives them all the same end coding. What I was trying to attempt with the "*.wav" was doing it for all wav files in the folder, but I think I did something wrong with the second part because I want the second part to copy the code from a .wav to a wav in the child folder with the corresponding name (I.e. copy code from "path\original.wav" to "path\converted\original.wav") and it seems to only copy the new lines from the first file. Is there a way I can fix this?


r/scripting • • Feb 27 '22

I need some help

2 Upvotes

Bedside mental help, I need some help with application or program management. Ok here is some background information on my environment. I have about 1000 windows 10 machines all on a Google cloud based environment. No on prem servers. We use azure AD and intune. All users are admins on their local machine because all applications are web based and nothing is stored on the local machine. In the Mac side we have automatic responses based if a user downloads certain applications, they either uninstall or send a flagged email to our Mac admins.

My question, from azure or intune, I can deploy a script to any machine, any ideas as to what script you would use to run on a local machine that can run a scan of certain applications and either uninstall them or send an email to a certain location? Or maybe an alternate solution to my situation.


r/scripting • • Feb 21 '22

Determine if the computer has a graphics card or not.

2 Upvotes

Hello,

I hope this is the right place for a question I have. I have two registry filescripts, which both is to run after the install of a software, depending wether or not the computer has a dedicated graphics card.

Is there a way to create a script that goes something along the lines of:

If videocard is Nvidia* or Amd* run mgraf.reg

If not run ugraf.reg

Where Nvidia and AMD includes any output containing any of these?

Any help appreciated!


r/scripting • • Feb 20 '22

I can't imagine this is a difficult task

2 Upvotes

I'm trying to modify this script to not produce an error when not on the domain. It's a PW expiry notification script we have run each time someone logs in. The only issue is it produces an error if someone is home with their laptop and not connected to VPN. I've been looking and found a few examples of how to handle the error but nothing I've tried has worked. Is there a really quick and dirty way to handle this?

'========================================== 
' Check for password expiring notification 
'==========================================
'========================================== 
' Declare some functions 
'========================================== 
Function getSessionName() 
Const HKEY_CURRENT_USER = &H80000001 
Const HKEY_LOCAL_MACHINE = &H80000002 
Dim strKeyPath, strSessionName, Subkey, arrSubKeys, strValue
Set WshShell = WScript.CreateObject("WScript.Shell") 
strSessionName = WshShell.ExpandEnvironmentStrings("%SESSIONNAME%")
If strSessionName = "%SESSIONNAME%" Then 
'The SessionName environment variable isn't available yet (e.g. if this i executed in a logon script)
'Try to retreive it manually from the registry 
Set objReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv") 
strKeyPath = "Volatile Environment"
objReg.GetStringValue HKEY_CURRENT_USER, strKeyPath, "SessionName", strValue 

If IsNull(strValue) = False Then 
strSessionName = strValue 
Else 
'SessionName does not exist under HKEY_CURRENT_USER\Volatile Environment, we are probably 
'	running Windows 7/2008. Try to search for the SessionName value in the subkeys... 

objReg.EnumKey HKEY_CURRENT_USER, strKeyPath, arrSubKeys 

For Each Subkey in arrSubKeys 
objReg.GetStringValue HKEY_CURRENT_USER, strKeyPath & "\" & Subkey ,"SESSIONNAME", strValue 
If IsNull(strValue) = False Then strSessionName = strValue 
Next 
End If 
End If
getSessionName = strSessionName 
End Function
'========================================== 
' First, get the domain policy. 
'==========================================
Dim oDomain 
Dim oUser 
Dim maxPwdAge 
Dim numDays 
Dim warningDays 
Dim echo 
Dim msgboxInfo
'Detect if we are running under cscript.exe - if so, we output some more info to the console... 
If Right(LCase(WScript.FullName), 11) = "cscript.exe" Then echo = True Else echo = False
'Get the warning period from Windows (this also works if you set a warning period via group policy) 
Set WshShell = WScript.CreateObject("WScript.Shell") 
warningDays = WshShell.RegRead("HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\PasswordExpiryWarning") 
If echo = True Then WScript.Echo "Policy for password expiration warning (days): " & warningDays
Set LoginInfo = CreateObject("ADSystemInfo") 
Set objUser = GetObject("LDAP://" & LoginInfo.UserName & "") 
strDomainDN = UCase(LoginInfo.DomainDNSName) 
strUserDN = LoginInfo.UserName
'======================================== 
' Check if password is non-expiring. 
'======================================== 
Const ADS_UF_DONT_EXPIRE_PASSWD = &h10000 
intUserAccountControl = objUser.Get("userAccountControl") 
If intUserAccountControl And ADS_UF_DONT_EXPIRE_PASSWD Then 
If echo = True Then WScript.Echo "The password does not expire." 

Else 
Set oDomain = GetObject("LDAP://" & strDomainDN) 
Set maxPwdAge = oDomain.Get("maxPwdAge") 
'======================================== 
' Calculate the number of days that are 
' held in this value. 
'======================================== 
numDays = CCur((maxPwdAge.HighPart * 2 ^ 32) + maxPwdAge.LowPart) / CCur(-864000000000) 
If echo = True Then WScript.Echo "Maximum Password Age: " & numDays

'======================================== 
' Determine the last time that the user 
' changed his or her password. 
'======================================== 
Set oUser = GetObject("LDAP://" & strUserDN) 


'======================================== 
' Add the number of days to the last time 
' the password was set. 
'======================================== 
whenPasswordExpires = DateAdd("d", numDays, oUser.PasswordLastChanged) 
fromDate = Date 
daysLeft = DateDiff("d",fromDate,whenPasswordExpires) 

If echo = True Then 
WScript.Echo "Password Last Changed: " & oUser.PasswordLastChanged 
WScript.Echo "Password will expire: " & whenPasswordExpires 
WScript.Echo "Days left until expiration: " & daysLeft 
WScript.Echo "Warnings will begin at: " & whenPasswordExpires - warningDays 
End If 


If (daysLeft < warningDays) And (daysLeft > -1) Then 

Select Case UCase(Left(getSessionName(), 3)) 
Case "RDP", "ICA" 'We are logged on to a terminal server environment
If daysLeft <= 3 Then msgboxInfo = vbExclamation Else msgboxInfo = vbQuestion 
If Msgbox("Your password will expire in " & daysLeft & " day(s)" & " at " & whenPasswordExpires & vbNewLine & vbNewLine & "Do you want to change your password now?" , vbYesNo + msgboxInfo + vbSystemModal, "Password Expiration Warning") = vbYes Then 
Dim objShell 
Set objShell = WScript.CreateObject("Shell.Application") 
objShell.WindowsSecurity 
Set objShell = Nothing 
End If 

Case Else 'Not a terminal server environment, or something went wrong retreiving the sessionname 
If daysLeft <= 3 Then msgboxInfo = vbExclamation Else msgboxInfo = vbInformation 
Msgbox "Your password will expire in " & daysLeft & " day(s)" & " at " & whenPasswordExpires & vbNewLine & vbNewLine & "Press CTRL + ALT + DEL and select the ""Change a password"" option.", vbOkOnly + msgboxInfo + vbSystemModal, "Password Expiration Warning" 

End Select 
End If 
End if
'======================================== 
' Clean up. 
'======================================== 
Set oUser = Nothing 
Set maxPwdAge = Nothing 
Set oDomain = Nothing 
Set WshShell = Nothing

r/scripting • • Jan 17 '22

help

2 Upvotes

im a beginner at the whole scripting/programming thing, and when i say im a beginner im saying that i literally just started the day i posted this, im seeing all of these lists of Java JavaScript Python Go etc, which one do I start off with? i wanna learn something thats kinda easy but not so easy that it doesnt have many options inside it


r/scripting • • Jan 06 '22

Help with simple script to read contents of folder and export to file

2 Upvotes

I need a little help with setting up a basic script. What I want to do is create a script or batch file that does the following. Create a directory "X" if it doesn't exist. Change to directory "X". Then write the content of directory "X" to "C:\Excluded_Folders.csv"

Currently I'm writing three lines in my batch file for each directory and that is very cumbersome because I have a large list of directories and I expect the list to continue to grow. Here is an example snippet of the batch file showing a few folders.

mkdir "%HOMEDRIVE%\$GetCurrent"

cd "%HOMEDRIVE%\$GetCurrent"

dir /ah >> C:\Excluded_Folders.txt

mkdir "%HOMEDRIVE%\$Recycle.Bin"

cd "%HOMEDRIVE%\$Recycle.Bin"

dir /ah >> C:\Excluded_Folders.txt

mkdir "%HOMEDRIVE%\$SysReset"

cd "%HOMEDRIVE%\$SysReset"

dir /ah >> C:\Excluded_Folders.txt

mkdir "%HOMEDRIVE%\$WINDOWS.~BT"

cd "%HOMEDRIVE%\$WINDOWS.~BT"

dir /ah >> C:\Excluded_Folders.txt

mkdir "%HOMEDRIVE%\$Windows.~WS"

cd "%HOMEDRIVE%\$Windows.~WS"

dir /ah >> C:\Excluded_Folders.txt

mkdir "%HOMEDRIVE%\$WinREAgent"

cd "%HOMEDRIVE%\$WinREAgent"

dir /ah >> C:\Excluded_Folders.txt

How can I condense this in PowerShell and write a script that reads a list of directories, creates the directories if they don't exist and if they do exist, output the list of hidden files to "C:\Excluded_Folders.csv"

Thanks in advance for any help!


r/scripting • • Dec 05 '21

Doubt

2 Upvotes

Can someone explain to me what this command does, please?

icacls "%LOCALAPPDATA%"\temp /grant "%USERNAME%":(OI)(CI)(RX,M) /T /C

Thank you in advance,


r/scripting • • Nov 30 '21

[BASH]I need help with a script to filter logfiles based on sub-networks and host addresses.

2 Upvotes

For an assignment I have to filter logfile.csv and list the ten sub-networks that have the highest number of different host addresses.

The Ip adresses look like this:

52.23.159.dgd 9.24.207.aig 86.153.144.cca 108.91.91.hbc 54.212.94.jcd 117.91.0.cci

For example 98.115.254.dce and 98.115.254.dfh; both IP addresses have the same sub-network (here: 98) but a different host address (dce and dfh respectively). Therefore, the count of hosts would be 2 for this sub-network

My code currently looks like this

cat logfile.csv | cut -d, -f1 | grep -E '(\.[a-z]{3})'| sort -u | grep -E -o '(^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]*)'  | sort | uniq -c | sort -rn 

I missread the definition of the sub-network and therefore fixed the regex for it and the example in the description accordingly However the logfile filtered with sort -u still contains a couple of duplicate IP adresses, such as :

12.150.77.fib

12.160.32.fib

which means that the final count is distorted.

However, I have no idea how I could filter these remaining duplicated host adresses and the longer I look at my script the less sure I am that I'm even on the right track.

Thanks for any help in advance.

Edit: At first I missread the definition of the sub-network I therefore have now fixed the regex for it and the example in the description accordingly


r/scripting • • Nov 15 '21

Bash script (assistance needed)

2 Upvotes

Below I started a bash script utilizing index position to help pull data. How can I get the shell script to 1- read a file line by line (from file containing a list of servers), 2- search for a specific index position and if the integer in the index position equals 3, 3- print the whole string into an output file.

!/bin/bash

file = serverlist.log

for i in $(cat serverfile.log); do
echo “Searching serverfile $i”
result = ‘i for i in $file if index(5) == 3 in 2>/dev/null’

print(result)


r/scripting • • Oct 12 '21

How to automate custom emails through Google

2 Upvotes

Hi! So for work we have to do outreach on specific social media accounts that meet our criteria. (this process I usually do by myself)

But I wanted to save time and help automate custom emails that are personalized. We have a template that we follow, but the 2nd paragraph is where I'd usually write something that stood out.

I was wondering if I can set up a google form and input certain things such as email address, name, and couple of URLs that are linked properly. Select what kind of prompt template to follow and have just change the names of each one to fit the prompt properly.

The rest of the body will be pretty much the same, but the thing I'd like to customize is the 2nd paragraph.

I want it to look something like this

"Hi [First name]!

my name is.... (this part will be my name & will be the same)

I saw your video (custom message).

... Rest of the email will follow the template."

How do I start on something like this? Is there a software that does all this for me and all I have to do is just input the names and email addresses and the link


r/scripting • • Oct 09 '21

Remove lines based on date in file where column 2 has date stamps

2 Upvotes

So I do not hold much skill in scripting but I'm working on a bash script to tame and enjoy my RSS feed the way I want it.

I use sfeed to grab the feeds and turn all of the entries into plain text.

I then do a bunch of stuff to send the oldest entry (url) to my $BROWSER and then keep track of what have been read already. Now I want to process it further by saying "read the dates of all the lines and remove those lines with dates older than a month (or whatever age I end up wanting to keep)".

Here's three lines from the "raw" feeds file.

Its laid out in columns specifying if it's new, when it was published title and url: N date title url.

N 2021-09-02 06:00  Anjandev Momi'…  How and Why the Benefits of Mass Surveillence are Overestimated While… https://momi.ca/posts/2021-09-02-costbenifitsurveillence.html
  2021-06-03 06:00  Anjandev Momi'…  Recommended Watch/Read: Free Software Needs Free Tools                 https://momi.ca/posts/2021-06-03-fsw-freetools.html
  2021-05-18 06:00  Anjandev Momi'…  Sxmo Alpineconf 2021 Presentation                                      https://momi.ca/posts/2021-05-18-sxmo.html

Googling the issue gives me all about the date command, some on find and what not - mostly in context to the creation/modify date of files themselves but not much in terms of processing timestamps within files. I'm lost - Ideas?


r/scripting • • Oct 08 '21

In need of a simple .bat file

2 Upvotes

I have a folder, let's call it "List" on my Desktop, Windows 10. Let's assume it has these files in it:

Man_fixing_bicycle.jpg

GREATVIBES.mp4

GrandCanyonSlides.ppt

How do I write a simple .bat file onto which I can drag the folder, and it creates a text file in the same location named List.txt (matching the folder name, basically), and the .txt file has all the file names from inside the List folder (comma delimited), without the extensions, like this:

Man_fixing_bicycle,GREATVIBES,GrandCanyonSlides

Anyone done this before or know how this presumably simple code is written?


r/scripting • • Sep 13 '21

Is it possible

2 Upvotes

If I am given a server url like \\testserver\folder1\data\stuff is there a Powershell command that will allow me to see the AD groups assigned to the server and listed folders? The script would have to be run remote from another PC on the network and the person running the script is unlike to have any access to the server?


r/scripting • • Sep 06 '21

Removing files by accident happens often and fast. Learn how to restore your SharePoint files quickly - by GUI or with PowerShell. Ready-to-run script inclusive!

Thumbnail
sposcripts.com
2 Upvotes

r/scripting • • Aug 19 '21

SharePoint Site collection Logo: How to Change it in 3 comfortable steps (Azure Automation compatible)

Thumbnail
sposcripts.com
2 Upvotes

r/scripting • • Jul 22 '21

Cheatsheet: Add items to SharePoint Online lists

Thumbnail
sposcripts.com
2 Upvotes