Using Diskpart

To use the command line to bring a disk online, create a partition, and format it, run the following commands:

C:\> Diskpart

DISKPART> list disk
DISKPART> select disk (id)
DISKPART> online disk (if the disk is not online)
DISKPART> attributes disk clear readonly
DISKPART> clean
DISKPART> convert mbr (or gpt)
DISKPART> create partition primary
DISKPART> select part 1
DISKPART> active (if this is the boot partition)
DISKPART> format fs=ntfs label=(name) quick
DISKPART> assign letter (letter)
DISKPART> list volume

 

The following are common errors displayed if you miss a step:

DISKPART> clean

DiskPart has encountered an error: The media is write protected. See the System Event Log for more information.

Resolution: run “attributes disk clear readonly” before trying to clean the volume and create the partition.

 

DISKPART> convert mbr

Virtual Disk Service error: The specified disk is not convertible. CDROMs and DVDs are examples of disks that are not convertable.

Resolution: clear all data off the disk before converting by running the clean command.

 

DISKPART> create partition primary

Virtual Disk Service error: There is not enough usable space for this operation.

Resolution: run “clean” before trying to create the partition.

 

DISKPART> format fs=ntfs quick

Virtual Disk Service error: The volume is not online.

Resolution: online the disk, create the partition, and convert to mbr before formatting.

 

The following are common errors displayed if there is a hardware problem:

DISKPART> clean

DiskPart has encountered an error: The device is not ready. See the System Event Log for more information.

Resolution: If the event log entry states “The driver detected a controller error on \Device”, the problem is likely your storage controller on your mainboard. Check your hard drive connections and reload your storage conroller driver. If the event log entry states “VDS fails to write boot code on a disk during clean operation. Error code: 80070015@02070008”, the hard drive itself has failed.

 

The following are common errors you may see if there is a hardware problem:

DISKPART> clean

DiskPart has encountered an error: The media is write protected. See the System Event Log for more information.

Resolution: Running “attributes disk clear readonly”, as mentioned above, is the first step. Next, the disk is may be locked by an active process, in which case a reboot generally clears the error.

If the disk is a USB flash drive, check that it does not have a write protect switch. The Imation Clip and the Kanguru Flash Blu II, for example, both have this feature and will cause the above error if protected. USB devices may also need a low-level format to reset the drive. In these cases, please see the manufacturer for such tools. (Patroit has such a tool here.)

If the disk is SAN attached storage, check that the LUN is not presented in a read-only state. Windows Server 2008 also has a condition were SAN storage is erroneously reported as read-only. See the Microsoft article 971436 for details and a hotfix.

email me

Countdown Clock

This will create a countdown clock based upon a specified date.  You could use this as an expiration date, or to logically run a task at that time.

olympics=CDate(“27/07/2012 00:00:00”)
wscript.echo(“It is ” & DateDiff(“d”, Now(), olympics) & ” days to the olmypics!”)

email me

Launching Commands on Behalf of Someone Else

The following script provides a function called Start-ProcessInteractive. You can specify a target computer, a path to an executable on that computer and also some arguments. If you do not specify a path and arguments, then the defaults will run a powershell command and write a file into the target windows folder. That’s a proof-of-concept, because if that command works it illustrates that the PowerShell command was launched with full privileges.

The function schedules the task for the currently logged on user. If no currently logged on user could be identified, then either no user was physically logged on, or the target machine is running virtual machines in which case you can manually submit the user account you want to schedule the command for.

function Start-ProcessInteractive {
param(
$filepath = ‘powershell.exe’,
$arguments = ‘-noprofile -command Get-Date | Out-File $env:windir\testfile.txt’,
[Parameter(Mandatory=$true)]
$computername
)

function Execute-Tool($path) {
$r = (Invoke-Expression $path) 2>&1
if ($LASTEXITCODE -ne 0) { Throw $r[0].Exception.Message }
}

$computername | ForEach-Object {
try {
$username = Get-WmiObject Win32_ComputerSystem -ComputerName $_ |
Select-Object -ExpandProperty UserName
} catch {}
$computer = $_

if ($username -eq $null) {
Write-Warning “On $computername no user is currently physically logged on.”
$username = Read-Host “Enter username of logged on user at the remote system”
}
if ($username -ne ”) {

$xml = @”

IgnoreNew
false
false
true
false
false

true
true
false
false
false
PT72H
7

$filepath
$arguments

$username
InteractiveToken
HighestAvailable

“@

$jobname = ‘remotejob{0}’ -f (Get-Random)

try {
$xml | Out-File “$env:temp\tj1.xml”
Execute-Tool “schtasks /CREATE /TN $jobname /XML $env:temp\tj1.xml /S $computer”
Start-Sleep -Seconds 1
Execute-Tool “schtasks /RUN /TN $jobname /S $computer”
Execute-Tool “schtasks /DELETE /TN $jobname /s $computer /F”
}
catch {
Write-Warning “$_ (trying to access user ‘$username’ on system ‘$computer’)”
}
}
}
}

email me

VBScript Count Files

This script will count the numbers of files in a folder and output to file.

Dim fso, folder, files, OutputFile
Dim strPath, filecnt

‘ Create a FileSystemObject
Set fso = CreateObject(“Scripting.FileSystemObject”)

‘ Create text file to output test data
Set OutputFile = fso.CreateTextFile(“c:\Script\ScriptOutput.txt”, True)

‘ Define folder we want to list files from
strPath = “c:\Script\”

set objFSO = createobject(“Scripting.FileSystemObject”)

GetFolders strPath

sub GetFolders(byval strDirectory)
set objFolder = objFSO.GetFolder(strDirectory)
for each objFolder in objFolder.SubFolders
Set folder = fso.GetFolder(objFolder.Path)
Set files = folder.Files
‘ Loop through each file
filecnt = 0
For each item In files
filecnt = filecnt + 1
‘ Output file properties to a text file

Next
OutputFile.WriteLine(“This Folder –> ‘” & folder & “‘ has ” & filecnt & ” Files”)
OutputFile.WriteLine
GetFolders objFolder.Path
next

end sub
wscript.echo “Script has finished running”
‘ Close text file
OutputFile.Close

email me

PowerShell Bulk Create Users from CSV

This script uses the ‘Active Directory module for Windows Powershell’ but the key point (that took me ages to work out, and seems mad) is you should not run it from a domain controller! instead I ran it from a member server while logged in as a Domain Admin.

The Script

Import-Csv .\2012Users.csv | foreach-object {
$userprinicpalname = $_.SamAccountName + “@yourdomain.com”

New-ADUser -SamAccountName $_.SamAccountName -UserPrincipalName $userprinicpalname -Name $_.name -DisplayName $_.name -GivenName $_.FirstName -SurName $_.LastName -Path “OU=year7,OU=Pupils,DC=yourdomain,DC=com” -AccountPassword (ConvertTo-SecureString “Passwordgoeshere” -AsPlainText -force) -Enabled $True -ChangePasswordAtLogon $True -PassThru }

The CSV should have the following columns

FirstName
LastName
name
SamAccountName

When you run the script, it will create the users, using their login name as the Display name.

email me

Create Users in AD

email me

Using this PowerShell, and a CSV file, you can create Users is specified OU’s in AD.

 

Code

Import-Csv "NewUsers.csv" | ForEach-Object {
$userPrinc = $_."Logon Username" + "@domain.com"
New-QADUser -Name $_.Name `
-ParentContainer $_."Container" `
-SamAccountName $_."Logon Username" `
-UserPassword "MyPassword99$" `
-FirstName $_."First Name" `
-LastName $_."Last Name" `
-LogonScript "TheLogonScript.bat" `
-Description $_."Graduating Year" `
-UserPrincipalName $userPrinc `
-DisplayName $_."Name" ;`
Add-QADGroupMember -identity $_."Graduating Year" -Member $_."Logon Username" ;`
Set-QADUser -identity $_."Logon Username" `
-UserMustChangePassword $true `

 

What is in your CSV:

Ed,Jackson,2016,ejackson,Ed Jackson,domain.com/Main OU/Domain Users/Students/Class 2016
Sam,Larson,2017,slarson,Sam Larson,domain.com/Main OU/Domain Users/Students/Class 2017
Jack,Johnson,2018,jjohnson,Jack Johnson,domain.com/Main OU/Domain Users/Students/Class 2018

Create Outlook Signature

Creates a signature for Outlook based upon AD Information.

On Error Resume Next

Set objSysInfo = CreateObject(“ADSystemInfo”)

Set WshShell = CreateObject(“WScript.Shell”)

strUser = objSysInfo.UserName
Set objUser = GetObject(“LDAP://” & strUser)

strName = objUser.FullName
strTitle = objUser.Description
strCred = objUser.info
strStreet = objUser.StreetAddress
strLocation = objUser.l
strPostCode = objUser.PostalCode
strPhone = objUser.TelephoneNumber
strMobile = objUser.Mobile
strFax = objUser.FacsimileTelephoneNumber
strEmail = objUser.mail

Set objWord = CreateObject(“Word.Application”)

Set objDoc = objWord.Documents.Add()
Set objSelection = objWord.Selection

Set objEmailOptions = objWord.EmailOptions
Set objSignatureObject = objEmailOptions.EmailSignature

Set objSignatureEntries = objSignatureObject.EmailSignatureEntries

objSelection.Font.Name = “Arial”
objSelection.Font.Size = 10
if (strCred) Then objSelection.TypeText strName & “, ” & strCred Else objSelection.TypeText strName
objSelection.TypeParagraph()
objSelection.TypeText strTitle
objSelection.TypeText Chr(11)
objselection.TypeText Chr(11)
objSelection.TypeText “Company Name”
objSelection.TypeText Chr(11)
objSelection.TypeText strStreet
objSelection.TypeText Chr(11)
objSelection.TypeText “PHONE: ” & strPhone
objSelection.TypeText Chr(11)
if (strFax) Then objSelection.TypeText “FAX: ” & strFax & Chr(11)
if (strMobile) Then objSelection.TypeText “CELL: ” & strMobile & Chr(11)
objSelection.TypeText “EMAIL: ” & strEmail
objSelection.TypeText Chr(11)
objSelection.TypeText “________________________________”
objSelection.TypeText Chr(11)
objSelection.TypeText “CONFIDENTIALITY NOTICE”

Set objSelection = objDoc.Range()

objSignatureEntries.Add “Full Signature”, objSelection
objSignatureObject.NewMessageSignature = “Full Signature”

objDoc.Saved = True
objWord.Quit

Set objWord = CreateObject(“Word.Application”)

Set objDoc = objWord.Documents.Add()
Set objSelection = objWord.Selection

Set objEmailOptions = objWord.EmailOptions
Set objSignatureObject = objEmailOptions.EmailSignature

Set objSignatureEntries = objSignatureObject.EmailSignatureEntries

objSelection.Font.Name = “Arial”
objSelection.Font.Size = 10
if (strCred) Then objSelection.TypeText strName & “, ” & strCred Else objSelection.TypeText strName
objSelection.TypeParagraph()
objSelection.TypeText strTitle
objSelection.TypeText Chr(11)

Set objSelection = objDoc.Range()

objSignatureEntries.Add “Reply Signature”, objSelection

objSignatureObject.ReplyMessageSignature = “Reply Signature”

objDoc.Saved = True
objWord.Quit

email me