Alma
Evans

A quick guide to executing custom Windows scripts via MDM

Alma Evans

Feb 25, 2021

21 min read

We all confront quite a few arduous daily tasks on our devices we wish we could perform with just one click of a button. It’s far more difficult if you’re an IT admin in charge of an entire fleet of work devices. Whether it is refreshing all the systems, converting file formats, pushing some new system configurations, creating backups, or permitting your users to access new functionalities, there will be a plethora of tedious activities that are driving you crazy, most of which are to be done iteratively, like almost every day.
You may literally be looking into anything that could automate these recurring tasks and speed up your work process. And scripting may be one of those convenient options that you might still haven’t got around to trying.

Try Hexnode for automated device administration

Scripting is a powerful tool with which you can do almost everything on the client device. You can reduce most administration tasks to a few lines of code. When it comes to the Windows platform, scripting has an increasingly significant role in doing remote configurations, certainly saving your time and effort. Scripting possibilities are almost endless and this makes it a fact of life for those who want to take shortcuts in Windows.

Mastering scripting technologies is pretty easy that even a non-techy IT guy with no prior programming experience can have the basic technical know-how with little to no pain. And when you finally get to grips with Windows scripting, you have that extra option for remotely executing these custom Windows scripts via MDM, further automating the process. Today in this blog, we will be looking into the surprising benefits you can come up with by executing custom Windows scripts via MDM.

Making life with Windows a bit easier

Making life with Windows a bit easier using Windows scripts
Working with a Windows laptop
 

There is no systematic literature to explain how challenging it can be to tackle the administrative burden imposed on a company’s IT team. If you’re an IT admin who has ever spent time renaming a whole set of files on your employee devices, you can understand how exhausting it is to deal with such tasks manually over and over again. But, wouldn’t it be great if you could set up your systems to do all this grunt work by themself? This is exactly what you can achieve with scripts in Windows. All you have to do is write up scripts for the tasks you would like to automate and configure your devices to handle them for you. You can just sit back and enjoy the triumph of seeing your machine doing something productive.

What are Windows scripts?

Automate Windows management using scripts
Automate Windows management using scripts
 

Let’s start from scratch.
Windows scripts or scripts generally are small, interpreted programs that collect a series of commands into a file intended to push target devices to accomplish various operations. Scripts are usually written in a text editor and saved into a text file. A script file may contain thousands of individual statements (carried out in sequence), each of which details a specific operation and makes decisions based on the information they find, altogether executing the expected process without any manual intervention.
You just need to figure out the steps involved in performing the task and the conditions under which the task is to be performed; the task is ready to be turned into a script. As scripts are written in ASCII text, a code editor or text editor like Windows Notepad might be the only thing needed.

The scripting benefits

Benefits of Windows scripting
Benefits of Windows scripting
 

For an IT admin, the ability to do things quickly will make a huge difference for a task that takes a lot of clicks or one that takes a week to complete, and anything saving time is worth trying!
If you’re still not convinced and doubt whether scripting is well worth the effort, here are a good few comforts that scripts can bring to an IT admin’s life:

  • Scripts automate a variety of mind-numbing tasks performed every day or several times a day, deliver custom commands to the devices in bulk and extract information from a set of data.
  • Scripts work well enough to save time, effort and money. It saves a lot of back and forth without incurring any extra costs, and the IT team would be freed up to do more critical things.
  • Scripts are accurate and help prevent human errors, inconsistency and confusion. They function correctly and consistently and to be sure they can be tested before execution.
  • Scripts accomplish routine computer activities at an incredible speed.
  • Scripts have thousands of possibilities. They need to be written only once and can be invoked many times. Even the code can be reused with a small degree of modifications for different use cases if needed.
  • Scripts can integrate new features into the devices.
  • Scripts create shortcuts for really convoluted commands, help put multiple commands together and combine features from multiple applications. A really complicated workflow can be broken down into a series of simple scripts, which makes the nuanced task easy.
  • As scripts delegate complex tasks, they can be assigned to smaller teams who can accomplish the task simply by running the script.
  • Scripts are really flexible and can make logical decisions according to the working conditions. So, they can function dynamically rather than statically approaching the use case.

Now, it’s clear that scripts are indeed a boon for IT admins who are looking for a faster and more manageable way to address too time-constraining, too irritating and too error-prone device operations. Though writing scripts may require an additional time investment initially, the time scripts save you when ran repeatedly would make up for this time you spend. That is, in the long run, scripts can make powerful workflows to enhance productivity, raise your quality and bring more value to the organization, effortlessly performing useful and impressive feats of automation.

Some Windows scripting basics

More than a few IT admins do not have an understanding of even the scripting basics as it was not considered a powerful tool a while back. But knowing the basics is really important that without a strong base, a seemingly simple script can startle even a long-tenured programmer.

The history of Windows automation

Automate Windows management by executing custom scripts via MDM
The history of Windows automation
 

It’s a long time since automation and scripting have been around the Windows platform. The first Windows-oriented automation tool introduced was the Command Prompt (Command line), which can be considered a successor of MS-DOS (Microsoft Disk Operating System) prompt and is often called as MS-DOS Command Prompt. It was designed to be compatible with the MS-DOS batch scripts for easy scripting. Since then, Command Prompt has been a pivotal component of the Windows ecosystem. Later, another tool called Windows Script Host (WSH) provided a language-independent environment to host more sophisticated command line based scripts via different object models and multiple scripting engines.
By the time Microsoft realized that the users desire a better command line experience, an object-oriented Command Shell called PowerShell was launched. PowerShell came with PowerShell ISE and worked both as a Command line interpreter program and a scripting language to unify Windows scripting and automation into a single console. As PowerShell provided a great extension of Command Prompt’s possibilities, it reinvented the way users interact with Windows. PowerShell is now a key component of any Windows management strategy, though Command Prompt is still in use to date. There is also a Windows feature called Windows Subsystem for Linux (WSL), which enable running Linux command-line tools on Windows. Windows Terminal is the latest Microsoft-approved terminal application to use all these Command line tools and shells within the same tool.

Command Prompt vs. PowerShell

Command Prompt  PowerShell 
Legacy command line interpreter of Windows  A task-based command line interpreter and a scripting language 
Runs only Windows commands (i.e., can interpret only batch commands)  Runs both Windows commands and PowerShell cmdlets (i.e., can interpret both batch commands and PowerShell commands) 
Much easier to learn and use  Much complex but has more features 
The output is a stream of texts  The output is a collection of objects 
Available only for Windows OS  Available on macOS and Linux, though primarily intended for Windows. 
Command line commands are usually one word. 

Eg:- cd to change the directory. 

PowerShell commands consist of two words usually structured in a verb-noun format. 

Eg:- Set-Location to change the directory 

Some common commands

  1. Listing files in a directory
    • Command Prompt: dir
    • PowerShell: Get-ChildItem
  2. Rename a file
    • Command Prompt: rename
    • PowerShell: Rename-Item "path/to/file.ext" -NewName "newfilename.ext"
  3. Shutdown a remote computer or a server section
    • Command Prompt: shutdown -s
    • PowerShell: Stop-Computer -ComputerName "HostName1","HostName2","Gateway or Address"
  4. Restart a local or remote computer
    • Command Prompt: shutdown -r
    • PowerShell: Restart-Computer -ComputerName "Hostname3", "localhost"
  5. Get help with a command
    • Command Prompt: /?
    • PowerShell: Get-Help "CMDLET Name"
  6. Force Group Policy refresh
    • Command Prompt: gpupdate /force
    • PowerShell: Invoke-GPUpdate -Computer "Name of the Host" -Force
  7. Set variables
    • Command Prompt: SET VariableName = "Value of the Variable"
    • PowerShell: $VariableName="Value of the Variable"
  8. Join a computer to a domain
    • Command Prompt: netdom /domain:domainname /user:username /password:passwordforthedomain member hostname /add
    • PowerShell: Add-Computer -DomainName "Domain" -Credential "Domain\Username" -Restart
  9. Stop a process
    • Command Prompt: taskkill
    • PowerShell: Stop-Process -Name "ApplicationName.exe"
  10. Find the location of an executable command
    • Command Prompt: where CommandName
    • PowerShell: Get-Command CommandName

Getting down to the nitty-gritty of Windows scripting

Knowing the essential concepts of Windows scripting
The essential concepts of Windows scripting
 

We’ve already taken the just-enough approach to know the basics of Windows scripting, and you’re now comfortable with what scripts are. It’s time to take the next step; let’s fathom out how the basic building blocks of Windows scripts together do the complex stuff.
Scripts are basically built of a sequence of statements, each of which states what action is to do further. The scripts might also contain some conditions under which the action is to be executed. Each of these statements will be interpreted by the host, and the necessary actions will be taken. Sometimes, larger scripts will be broken into components or modules to make them understandable.
The format, structure and flow of scripts may vary according to the language being used. So, instead of digging too deeper into the scripting concepts and terminology, capturing some first impressions of the common scripting languages would go a long way in an attempt to scripting the boring stuff.

Getting a sense of Windows scripting languages

Get an idea of different Windows scripting languages
Get an idea of different Windows scripting languages
 

Scripting languages are computer languages that are interpreted rather than compiled, where instructions are processed while in motion. Scripting languages are uncomplicated (as they don’t require a steep learning curve) yet perfect (as they can fulfill any piece of work). Most scripting languages are so simple that the code can be edited and re-executed with ease.
Windows come with in-built support for multiple scripting languages though some are widely used than others. Learning even a single scripting language is worth the effort. Anyhow, here, we’ll be focusing only on two, namely the Batch and PowerShell that look like the top contenders. Surely, there are some others like VBscript along the way, but for the most part, Batch and PowerShell were the mainstays. Pardon me if you have an entirely different set of scripting languages to consider!

Batch

Batch is a very old scripting language whose birth dates back to the days of MS-DOS. It is not commonly used as a programming language but has great importance in the Windows environment. The series of commands are stored in a plain text file called a batch file and are executed by the Command Prompt that assumes both the role of an interpreter and a run time environment. Batch files are stored either using a .bat or .cmd extension.

.bat  .cmd 
The first extension used by Microsoft for batch files  The new extension described by Windows NT based systems 
Used by both DOS and Windows  Used by only Windows NT 
Works in all environments  Won’t work in a 16-bit environment 
Error level variable changes only if there is error  Error level variable changes when the command gets affected by successful command extensions 
Can be read or interpreted by both command.com and cmd.exe  Can be read or interpreted only by cmd.exe 

There are two ways by which batch scripts can be executed, either by typing the batch scripts in the Command Prompt or by writing the script in a file and executing it through the Command Prompt. The latter is the recommended method where the script file is created in any script editor with a .txt extension, later renamed using a .bat or .cmd extension and the file is opened later to run the script.

Sample Batch scripts for some common use cases

  1. Open folders and files
    @echo off
    :: Open folders
    start %USERPROFILE%\Documents\
    start %USERPROFILE%\Desktop\MusicFolder\
    :: Open files
    start chrome.exe
    start "" "%USERPROFILE%\Documents\Blogs\Scripting.docx"
    start "" "%USERPROFILE%\Documents\Content Ideas.xlsx"
    exit
  2. Delete old files
    @echo off
    forfiles /p "%USERPROFILE%\Documents\My Blogs" /s /m *.docx /d -20 /c "cmd /c del @path"
    echo Document files older than 20 days deleted
    pause
    exit
  3. Turn off the system (after showing an alert message at a particular time)
    @echo off
    :a
    If %time%==23:00:00.00 goto :b
    goto a:
    :b
    shutdown.exe /s /f /t 120 /c "Time To Say Good Night!"
    exit
  4. Backup files or folders (here backs up the user directory and system registry)
    @echo off
    :: Set the folder to backup below
    set sourcedir=C:\Users\USER
    :: Set your portable drive's folder below
    set targetdir=D:\Backup
    if not exist "%targetdir%" mkdir "%targetdir%"
    echo ### Backing up your profile…
    robocopy %sourcedir% %targetdir% * /e /j /r:10 /v
    echo ### Backing up the registry…
    if exist "%targetdir%\regbackup.reg" del "%targetdir%\regbackup.reg"
    regedit.exe /e "%targetdir%\regbackup.reg"
    echo ### Backup is all complete…
    pause
    exit
  5. Checking the ping of two different URLs
    @echo off
    Title CHECKING PING
    ping www.google.com && ping www.appuals.com
    pause
    exit
  6. Determine the absolute path to the Batch file being run
    @echo off
    rem Echo illustrating how to get batch file folder and its parent folder.
    rem Determine the folder that this batch file exists in:
    rem - used to provide path relative to the batch file location
    set scriptFolder=%~dp0
    rem Remove trailing \ from scriptFolder.
    set scriptFolder=%scriptFolder:~0,-1%
    rem Also get the script name without leading path.
    set scriptName=%~nx0
    rem Get the parent folder, which is the folder for the full software install.
    rem Have to get parent folder using Windows for loop approach.
    for %%i in (%scriptFolder%) do set installFolder=%%~dpi
    rem Remove trailing \ from installFolder
    set installFolder=%installFolder:~0,-1%
    echo scriptFolder=%scriptFolder%
    echo installFolder=%installFolder%
    exit /b 0
  7. Set Command Prompt window title
    @echo off
    rem Example of how to set command prompt window title
    rem Configure the environment for software tool
    set ENV_VAR1=some value
    set ENV_VAR2=some value
    rem Set the title to indicate that the command prompt window is configured for ABC software.
    title Command shell window for ABC software
    exit /b 0
  8. Copy file from one folder to another
    @echo off
    rem Change console screen
    color F0
    rem Source folder location
    set Source_Folder=D:\hexnode\docs
    rem Destination folder location
    set Dest_Folder=D:\hexnode\data
    rem Ask file name from user
    set /p FileName= Enter File Name
    rem If destination folder not available, create
    mkdir %Dest_Folder%
    rem Copy the files
    copy %Source_Folder%\*%FileName%* %Dest_Folder%\.
    pause
  9. Stop and restart audio service
    @echo off
    net stop audiosrv
    pause
    net start audiosrv
    pause
  10. Create local user account
    @echo off
    net user USERNAME PASSWORD /add /comment:"COMMENT" /passwordchg:NO
    wmic useraccount where "name='USERNAME'" set passwordexpires=FALSE
    net localgroup "GROUP" USERNAME/add
    exit

PowerShell

No matter what all scripting languages are out there for Windows, there won’t be anything better than PowerShell which is the de facto choice for scripting in Windows. PowerShell is a high level full-fledged scripting language. It is extremely useful in cases where more programming logic is needed than Batch can provide.
PowerShell is the ideal language to code for the majority of Windows scripting tasks and is the Microsoft recommended way of scripting. PowerShell is based on object-oriented standards. PowerShell scripts are also written in a plain text file that uses a .ps1 extension. Using PowerShell ISE is the preferred way to use PowerShell language as it provides syntax highlighting and auto-filling of commands. To execute an already saved script file, right-click and click on Run with PowerShell.

Sample PowerShell scripts for some common use cases

  1. Rename multiple files
    $files = Get-ChildItem -Path C:\Temp #create list of files
    foreach ($file in $files)
    {
    $newFileName=$file.Name.Replace("A","B") #replace "A" with "B"
    Rename-Item $file $newFileName
    }
  2. Monitor folder for new files
    Get-ChildItem -Path \\pdc\Shared\Accounting\*.* -Filter * | ?
    {
    $_.LastWriteTime -gt (Get-Date).AddDays(-1)
    }
  3. Add users present in a CSV to the AD
    try
    {
    Import-Csv “C:\test\test.csv” | ForEach-Object
    {
    $Name = $_.Name + “test.com”
    New-ADUser `
    -DisplayName $_.”Dname” `
    -Name $_.”Name” `
    -GivenName $_.”GName” `
    -Surname $_.”Sname” `
    -SamAccountName $_.”Name” `
    -UserPrincipalName $UPName `
    -Office $_.”off” `
    -EmailAddress $_.”EAddress” `
    -Description $_.”Desc” `
    -AccountPassword (ConvertTo-SecureString “abc@123”
    -AsPlainText -force) ` -ChangePasswordAtLogon $true `
    -Enabled $true `
    Add-ADGroupMember “OrgUsers” $_.”Name”;
    Write-Host "User created and added in the AD group"
    }
    }
    catch
    {
    $msge=$_.Exception.Message
    Write-Host "Exception is" $msge
    }
  4. Delete old files (path to be checked for files are mentioned in a CSV)
    Write-Host "Welcome to the archive example"
    $csv = Import-Csv "C:\Scripting\test.csv"
    foreach($row in $csv)
    {
    $Path=$row.Path
    write-host "The path to be archived is"
    $row.Path
    $DaysTOBeArchived = "-30"
    $CurrentDate = Get-Date
    $DatetoBeDeleted = $CurrentDate.AddDays($DaysTOBeArchived) Get-ChildItem $Path -Recurse | Where-Object { $_.CreationTime -lt $DatetoBeDeleted } | Remove-Item Write-Host "Cleared the files is the path "$row.path
    }
  5. Delete an app from multiple computers
    $computerNames = @("SomeComputerName1", "SomeComputerName2", "SomeComputerName3")
    $appName = "AppName"
    $yourAccount = Get-Credential
    ForEach ($computerName in $computerNames) {
    Invoke-Command -ComputerName $computerName -Credential $yourAccount -ScriptBlock {
    Get-WmiObject Win32_product | Where {$_.name -eq $appName} | ForEach {
    $_.Uninstall()
    }
    }
    }
  6. Retreiving computer information from computers belonging to an AD
    $ou = [ADSI] "LDAP://ou=test,dc=testlab,dc=local"
    $computers = $ou.PSBase.Get_Children()
    $arrInfo = @()
    foreach($node in $computers)
    {
    $arrInfo += Get-WmiObject –query "Select `
    Name, Manufacturer, Model, `
    NumberOfProcessors, `
    TotalPhysicalMemory ` From Win32_ComputerSystem" ` -computername $node.Name
    }
    $arrInfo | format-table Name, Manufacturer, `
    Model, NumberOfProcessors, TotalPhysicalMemory
  7. List out the content of a folder
    if ($args.count –ne 1)
    {
    Write-Host "Missing Parameter!" –foregroundcolor "Red"
    Exit
    }
    $folderPath = $args[0]
    Write-Host ("Directory listing of " + $folderpath)
    # Process each item in the directory
    foreach ($i in get-childitem $folderpath)
    {
    if ($i.mode.substring(0,1) –eq "d")
    {
    Write-Host $i.name –foregroundcolor "Blue"
    }
    else
    {
    Write-Host $i.name –foregroundcolor "Green"
    }
    }
  8. Create a new folder and add shortcut on desktop
    $path = "C:\" New-Item .\EpicFolder -ItemType Directory -Force
    $wshshell = New-Object -ComObject WScript.Shell
    $desktop = [System.Environment]::GetFolderPath('Desktop')
    $lnk =
    $wshshell.CreateShortcut($desktop+"\ShortcutName.lnk")
    $lnk.TargetPath = "c:\EpicFolder"
    $lnk.Save() Write-Host "Folders and Shortcut created!"
  9. Create a file after checking whether it already exists
    #create array of text files
    $files=Get-ChildItem C:\data\*.txt | select -expand fullname
    #check if file exists inside the array
    $files -match "pc.txt"
    #if matching return “True” key then exit, if “False” then create a report
    if($files -eq 'False')
    {
    Get-ADComputer -Filter * | Export-Csv -Path C:\data\pc.txt
    }
    else
    {
    exit
    }
  10. Delete files from multiple computers
    $filelist = @(" \c$\Temp", "\c$\Backups") #variable to delete files and folder
    $computerlist = Get-Content C:\data\pc.txt #get list of remote pc's
    foreach ($computer in $computerlist)
    {
    foreach ($file in $filelist)
    {
    $filepath= Join-Path "\\$computer\" "$filelist" #generate unc paths to files or folders
    if (Test-Path $filepath)
    {
    Remove-Item $filepath -force -recurse -ErrorAction Continue
    }
    }
    }

Up and running with Windows scripts: some major concerns

Windows scripting difficulties
Windows scripting difficulties
 

We are simply amazed at the power that comes out of the synergy of various technologies underlying Windows scripting. Still, many frustrating difficulties surround their execution. Though working with scripts is pretty easy, running your scripts on an entire fleet of devices is not at all an easy task to tackle. You can ignore this fact if you don't feel script execution a difficult chore; you put your head in the sand at your own risk.
Deploying scripts to a large fleet of devices can be a mammoth task for the IT admin. All the scripts need to be tested before distributing them to make sure that the systems never get damaged with the scripts. You also need to keep the scripts well organized with proper naming in a way that you won’t get confused.
All these concerns might make you a little lost in the world of scripting, but there are some ways to take the edge off these worries and make all the difference.

Automating Windows script execution using the Task Scheduler

Automating Windows script execution using Windows Task Scheduler
Automating Windows script execution using Windows Task Scheduler
 

Task Scheduler is an administrative tool in Windows that often doesn’t get much attention from IT admins. To make Windows scripts run automatically, the Task Scheduler allows scheduling scripts to run on a regular basis. Scripts can be executed on-demand, on schedule, on startup or when any conditions are met.
Task Scheduler promises full automation of script execution, but this is not a much viable solution for IT admins due to lack of scalability.

Executing custom Windows scripts via MDM

Executing custom Windows scripts via Hexnode MDM
Executing custom Windows scripts via Hexnode MDM
 

If the IT is heavily reliant on a large scale of scripts that run often enough, it would be burdensome to execute the scripts manually all the time in all the devices. On top of that, the need for standardization and organization is rapidly apparent as IT admins have a lot of scripts to handle. Hexnode provides the option to get on with these, and no matter how many devices you are managing, Hexnode can handle all of them with ease. The exemplary management features and the centralized management console of Hexnode surely reduce the desperate number of tools that the IT has to rely on for task automation.
The Execute custom scripts action allows admins to push Windows scripts remotely to a bulk of devices, vastly simplifying their execution process. By executing custom Windows scripts via MDM, all your scripts can be kept organized, run either at the device level or the user level, and the execution status can be monitored right from the management portal. And it’s important to note that custom scripts are a great way to add to your endpoint management capabilities and flexibility as many features not included in the MDM protocol stack could be scripted and run on the machines to accomplish advanced configurations.

Things to remember while executing custom Windows scripts via MDM:

  • Supported only on Windows 10 v1709 or later PCs and tablets.
  • Supported only on devices enrolled via Hexnode Installer app with Hexnode Agent 4.2.2 or later.
  • The file name of a script file should not contain values like / : ? \ * | “ [ ] @ ! % ^ and #.
  • Only PowerShell scripts (.ps1) and batch files (.bat or .cmd) are supported.
  • Scripts requiring user interactions or device UI interactions aren’t supported. The device UI interactions may include opening an application, playing a video, and so forth.
  • Wildcards can be used to pass arguments to the script.

Though we initially considered script execution a hard knock, it’s now clear that it can definitely be done with the right approach. And executing custom Windows scripts via MDM might be the right approach. When combined with an MDM, scripts can have a lot more possibilities. So, no matter how limited your management requirement is, automation and scripting should be your top priority to take care of.
We have just scratched the surface of Windows scripting concepts to get a taste of it still hope that these fundamental measures will take you significantly further in the direction of scripting in Windows. And if you haven’t yet started working on your scripting skills, you’re already behind the curve, and it is high time to catch up with your peers. Take the first step now to unleash the power of Windows scripting and accompany Hexnode to put your scripting skills work right away!

Share
  • 3
  •  
  •  
  •  
  •  
    3
    Shares

Alma Evans

Product Evangelist @ Hexnode. Already lost up in the whole crazy world of tech... Looking to codify my thoughts for now...

Share your thoughts