Friday, May 26, 2017

Diskpart and PowerShell – part 6: Multiple partitions on a disk

Diskpart and PowerShell – part 6: Multiple partitions on a disk

http://ift.tt/2r3THyD

So far we’ve looked at creating a single partition on a disk. This time we’ll look at how you can create multiple partitions on a disk. The are good reasons not to do this but its something I’ve seen done on a frequent basis.

Lets create a 20GB disk as an example and mount it

New-VHD -Path C:\test\Test1.vhdx -Dynamic -SizeBytes 20GB
Get-VHD -Path C:\test\Test1.vhdx | Mount-VHD

Initialise the disk

Initialize-Disk -Number 1

Now we can create some partitions

New-Partition -DiskNumber 1 -DriveLetter F -Size 5GB
New-Partition -DiskNumber 1 -DriveLetter G -Size 5GB
New-Partition -DiskNumber 1 -DriveLetter H -Size 5GB
New-Partition -DiskNumber 1 -DriveLetter I -Size 4.87GB

The reason that the last partition is only 4.87 G is that 128MB of disk space is reserved

PS> Get-Partition -DiskNumber 1 | Format-Table -AutoSize


   DiskPath: \\?\scsi#disk&ven_msft&prod_virtual_disk#2&1f4adffe&0&000003#{53f56307-b6bf-11d0-94f2-00a0c91efb8b}

PartitionNumber DriveLetter Offset         Size Type
--------------- ----------- ------         ---- ----
1                           17408        128 MB Reserved
2               F           135266304      5 GB Basic
3               G           5503975424     5 GB Basic
4               H           10872684544    5 GB Basic
5               I           16241393664 4.87 GB Basic

You can format the 4 new volumes in one pass

Get-Partition -DiskNumber 1 | 
where Type -ne 'Reserved' | 
Format-Volume -FileSystem NTFS -Confirm:$false –Force

PS> Get-Partition -DiskNumber 1 | Get-Volume | select DriveLetter, FileSystem, Size

DriveLetter FileSystem       Size
----------- ----------       ----
          H NTFS       5368705024
          G NTFS       5368705024
          I NTFS       5229244416
          F NTFS       5368705024

The Storage module can be used to simply and easily create multiple volumes on a disk




Powershell

Powershell

via Richard Siddaway's Blog http://ift.tt/1JR1noE

May 26, 2017 at 12:54AM

Wednesday, April 26, 2017

DiskPart and PowerShell–part 1

DiskPart and PowerShell–part 1

http://ift.tt/2oxlxFy

An attendee at the Summit made the statement that the DiskPart utility didn’t have any equivalent in PowerShell. That’s not strictly true as the storage module provides a lot of functionality that maps to diskpart functionality.

The module contents include:

PS> Get-Command -Module Storage | select name

Name
----
Disable-PhysicalDiskIndication
Disable-StorageDiagnosticLog
Enable-PhysicalDiskIndication
Enable-StorageDiagnosticLog
Flush-Volume
Get-DiskSNV
Get-PhysicalDiskSNV
Get-StorageEnclosureSNV
Initialize-Volume
Write-FileSystemCache
Add-InitiatorIdToMaskingSet
Add-PartitionAccessPath
Add-PhysicalDisk
Add-TargetPortToMaskingSet
Add-VirtualDiskToMaskingSet
Block-FileShareAccess
Clear-Disk
Clear-FileStorageTier
Clear-StorageDiagnosticInfo
Connect-VirtualDisk
Debug-FileShare
Debug-StorageSubSystem
Debug-Volume
Disable-PhysicalDiskIdentification
Disable-StorageEnclosureIdentification
Disable-StorageHighAvailability
Disable-StorageMaintenanceMode
Disconnect-VirtualDisk
Dismount-DiskImage
Enable-PhysicalDiskIdentification
Enable-StorageEnclosureIdentification
Enable-StorageHighAvailability
Enable-StorageMaintenanceMode
Format-Volume
Get-DedupProperties
Get-Disk
Get-DiskImage
Get-DiskStorageNodeView
Get-FileIntegrity
Get-FileShare
Get-FileShareAccessControlEntry
Get-FileStorageTier
Get-InitiatorId
Get-InitiatorPort
Get-MaskingSet
Get-OffloadDataTransferSetting
Get-Partition
Get-PartitionSupportedSize
Get-PhysicalDisk
Get-PhysicalDiskStorageNodeView
Get-PhysicalExtent
Get-PhysicalExtentAssociation
Get-ResiliencySetting
Get-StorageAdvancedProperty
Get-StorageDiagnosticInfo
Get-StorageEnclosure
Get-StorageEnclosureStorageNodeView
Get-StorageEnclosureVendorData
Get-StorageFaultDomain
Get-StorageFileServer
Get-StorageFirmwareInformation
Get-StorageHealthAction
Get-StorageHealthReport
Get-StorageHealthSetting
Get-StorageJob
Get-StorageNode
Get-StoragePool
Get-StorageProvider
Get-StorageReliabilityCounter
Get-StorageSetting
Get-StorageSubSystem
Get-StorageTier
Get-StorageTierSupportedSize
Get-SupportedClusterSizes
Get-SupportedFileSystems
Get-TargetPort
Get-TargetPortal
Get-VirtualDisk
Get-VirtualDiskSupportedSize
Get-Volume
Get-VolumeCorruptionCount
Get-VolumeScrubPolicy
Grant-FileShareAccess
Hide-VirtualDisk
Initialize-Disk
Mount-DiskImage
New-FileShare
New-MaskingSet
New-Partition
New-StorageFileServer
New-StoragePool
New-StorageSubsystemVirtualDisk
New-StorageTier
New-VirtualDisk
New-VirtualDiskClone
New-VirtualDiskSnapshot
New-Volume
Optimize-StoragePool
Optimize-Volume
Register-StorageSubsystem
Remove-FileShare
Remove-InitiatorId
Remove-InitiatorIdFromMaskingSet
Remove-MaskingSet
Remove-Partition
Remove-PartitionAccessPath
Remove-PhysicalDisk
Remove-StorageFileServer
Remove-StorageHealthSetting
Remove-StoragePool
Remove-StorageTier
Remove-TargetPortFromMaskingSet
Remove-VirtualDisk
Remove-VirtualDiskFromMaskingSet
Rename-MaskingSet
Repair-FileIntegrity
Repair-VirtualDisk
Repair-Volume
Reset-PhysicalDisk
Reset-StorageReliabilityCounter
Resize-Partition
Resize-StorageTier
Resize-VirtualDisk
Revoke-FileShareAccess
Set-Disk
Set-FileIntegrity
Set-FileShare
Set-FileStorageTier
Set-InitiatorPort
Set-Partition
Set-PhysicalDisk
Set-ResiliencySetting
Set-StorageFileServer
Set-StorageHealthSetting
Set-StoragePool
Set-StorageProvider
Set-StorageSetting
Set-StorageSubSystem
Set-StorageTier
Set-VirtualDisk
Set-Volume
Set-VolumeScrubPolicy
Show-VirtualDisk
Start-StorageDiagnosticLog
Stop-StorageDiagnosticLog
Stop-StorageJob
Unblock-FileShareAccess
Unregister-StorageSubsystem
Update-Disk
Update-HostStorageCache
Update-StorageFirmware
Update-StoragePool
Update-StorageProviderCache
Write-VolumeCache

In this mini series I’m going to go through a number of the diskpart options and show you how to do the same with the Storage module cmdlets.

I’m not sure if all diskpart options are available but it’ll be fun to find out.

The Storage module was introduced with Windows 8/Server 2012.

ls $pshome\modules\storage

or

Get-ChildItem $pshome\modules\storage

if you prefer shows a number of cdxml files. This means that the cmdlets are based on CIM classes which you can see at

Get-CimClass -Namespace ROOT/Microsoft/Windows/Storage

These classes aren’t available on versions of Windows prior to Windows 8/Server 2012.

I’ll also have a look at some of these classes to see if there’s anything we can do that isn’t covered directly by the storage module cmdlets.



Powershell

Powershell

via Richard Siddaway's Blog http://ift.tt/1nN0D9u

April 26, 2017 at 05:57AM

AD_bulk_new_OU

AD_bulk_new_OU

http://ift.tt/2q8jF35

Active Directory, bulk create OU's with defined sub OU's

Powershell

Powershell

via PowerShell Script Repository http://poshcode.org/

April 25, 2017 at 09:02PM

Monday, April 24, 2017

Always Ask for the API

Always Ask for the API

http://ift.tt/2oFnAmd

Take this hypothetical, totally-didn’t-recently-come-up-at-work, scenario: your business uses two disparate cloud services and needs them to share data, but they don’t integrate natively.

You, the scripting magician that you are, can take an export from the first service, manipulate it however it needs to be manipulated and then import it to the other service. You could do this in reverse. You could do this all day, every day; it’s a task right up your alley.

But you really don’t need to make this harder than it needs to be.

Hard? This sounds like a piece of cake!

Yeah sure. At first look it really is a simple task.

You read in a CSV, make some changes to the resulting objects, maybe pull in some auxiliary info from an internal system and finally spit out a new CSV that can be uploaded to the second service.

But take a step back and consider: how are you getting that initial CSV?

Chances are that you may not have your own access to the service in question, or you may have limited access. This is especially true if it’s “owned” by another business unit outside of IT, like Human Resources. This means that you likely won’t be able to export a report as a CSV and you’ll need someone else to do it for you and probably email it to you.

Now you’ve got to figure out how to:

  • Check for to see if the email is in your inbox.

  • Save the attachment somewhere.

  • Read the file in and do all the processing mentioned above.

  • Clean up the file.

You’ve also got to worry about the staff member you’ve roped into this scheme remembering to do it. It’ll also never be sent at the same time, so you’re script/process will need to run in a loop until the email arrives.

Also, the whole point of automation is to rule out (or limit/mitigate) human error. Are you 100% sure that there is no chance that the person running the report won’t accidentally generate the wrong one. The report you get could end up with missing columns, extra columns. Maybe it has the right info, but in the “wrong” order.

Well, that escalated quickly

It sure did! But fear not, there is (usually) and easier way.

Firstly, if this is a bigger cloud provider, chances are they already have an accessible and well documented API. In which case, just use that… and why were you even considering doing any of the above?!

However, if this is more of a bespoke service, then instead of roping someone from the business unit into running a report all the time for you, ask them if they have a technical contact or account manager with the company providing the cloud service.

With contact details in hand, flick them an email. Include the person you’ve been talking to within your own company so they are aware of what you’re asking for and can authorize it if need be.

Keep the email short and simple, explain that you’re attempting to get data out of system x using an API (maybe mention a preference for JSON if you’re on that PowerShell train). Ask if it’s possible and what the authorization and development process is.

You’ll likely get a “sure, no problem!” type response and details on the specific info the company needs. This will likely include the specific info you want exposed and how often you’ll be polling it.

When I’ve done this in the past, after specifying the info I’m after they will generate an example of the result as a CSV so you can eye ball that the result is what you’re looking for and then they’ll hand it off to their developers to set it all up.

When the developers have done their thing, you should get some instructions, a URL and an authorization key. Time to start Invoke-RestMethoding!

So I can have my cake and eat it too?

Getting access to the API will make your job dramatically easier and the end product more robust and reliable.

But it isn’t free (unless you have a generous provider, a great support contract or negotiate it when procuring the service.)

In every case when I have been through this process we’ve been changed an hourly fee for two hours of development time. It’s also possible that your provider may do the setup for free but then charge per request against the API.

It’s pretty easy to justify this cost, assuming your provider doesn’t absolutely gouge you, when you consider the amount of time that it’ll take you to develop the process that an API eliminates. Also consider the time you’ll have to give up when something goes wrong; an extra column causing the script to fail? That’s more of your time that would have been freed up with the API being in place.

As an aside if you’re having trouble working your hours into a cost/benefit analysis keep in mind your time does have a cost to the business. Chances are it’s actually higher than the hourly rate that you’re paid. Some managers would happily give you a number you can use in a business case, others may have never thought about it before.

In any case, it can’t hurt to at least ask for the API, that much costs nothing.



Powershell

Powershell

via Planet PowerShell http://ift.tt/2ozzxeJ

April 24, 2017 at 12:52PM

PowerShell Hash Tables and Calculated Properties Basics

PowerShell Hash Tables and Calculated Properties Basics

http://ift.tt/2pc2JZv

This video is a basic overview of how to use hash tables and calculated properties to make PowerShell data more usable.

<#
.SYNOPSIS
    How to use Hash Table and Calculated Properties

.DESCRIPTION
    A basic walk through of how to use Hash Tables and Calculated properties

.PARAMETER 


Powershell

Powershell

via Planet PowerShell http://ift.tt/2ozzxeJ

April 24, 2017 at 10:57AM

Powershell Tip: Escaping special Characters in a String using [RegEx] type accelerator

Powershell Tip: Escaping special Characters in a String using [RegEx] type accelerator

http://ift.tt/2pd2nnf

Often when using the -Replace (Operator) or .replace() (Method) in Powershell, I forget that the former parses the string in regex and in case you’re passing Special characters in the string, you’ll get the error all over your console.

That is because some special characters are part of regular expression language and are considered are Meta Characters in RegEx, so it’s always a best practice to escape special characters.

To your rescue,  here is a quick tip to escape all special characters in a string using the .Net Type accelerator for Regular expression [RegEx] , something like in the following image –

regex

and an animation with a use case.

tip

Hope you’ll find this useful, until next time, Cheers!

signature


Filed under: Powershell, PSTip, Today I Learned ! Tagged: .Net, dotnet, Powershell, PSTip, Regex, Regular expression, String, TypeAccelerator

Powershell

Powershell

via Planet PowerShell http://ift.tt/2ozzxeJ

April 23, 2017 at 10:51PM

PowerShell Server Inventory, Part 2: Collecting and Sending Data

PowerShell Server Inventory, Part 2: Collecting and Sending Data

http://ift.tt/2nMjgT8

This will be at least a 3 part series in which I will go over each aspect of my build which will cover the following topics:

Picking up where I left at, we have created our database and tables that will be used to store all of our data on our servers. Next up is to begin querying each server in the domain and pull as much information as we can and then send that data up to SQL so we can view it later on.

For this part of querying and sending data to the SQL server, I felt that it would be best to do some multithreading to speed up the time that it would take to hit all of the systems rather than perform the work sequentially. My multithreading approach of choice is to use my module, PoshRSJob to handle this. You can grab this module from my GitHub repo and place it on whichever server that you will be using to schedule the task from to perform the scans and uploads to SQL.

I say that you can scheduled a job to run the next script, but this is something that could be performed manually as well if need be and in fact, I would recommend this to ensure that no errors are thrown during the script execution.

The script that I wrote which will be used is called Invoke-ServerInventoryDataGathering.ps1 which only has a single parameter that accepts what SQL server will be used to send the data to. The script itself is over 1000 lines of which most of it consists of various regions which are used to group each type of data pull ranging from user account information to drive data to system configurations. In fact, about half of the code consists of helper functions which are used for data gathering or, in the case of Get-Server, is used to perform a domain wide lookup of all of the servers for a more dynamic approach of ensuring that all servers are being checked rather than using a file to host all of the systems.

image

There is a variable called $ServerGroup which is keeping a value of ‘MemberServer’. You can disregard this (keep it uncommented though) as I have my lab set up differently where Domain Admins do not have access to anything other than domain controllers which require a second script to be used to query the domain controllers and then write the data to the SQL server (which does allow domain admins to access for the purpose of writing the data to SQL).

Continuing to step through the code,  I have several regions which I use to group together each type of query. If more queries need to be added to grab more information, I can simply create a new region and add the necessary code to gather and send the data.

image

Each region follows the same type of process:

  1. Query the remote system for the particular information that I need
  2. If the query was successful, then proceed to perform a check against the database for data on the same system on the table that matches the type of data being queried for
  3. If data already exists, then remove the existing data
  4. Send the new data up to the appropriate table based on the current data being collected

Kicking off the script manually is just a matter of running it. In my case, VSQL is hard coded as the parameter value for the SQL server. In other cases, you would want to supply your own value.

image

I use Wait-RSJob with the –ShowProgress switch so I can track the status of each job. Each job represents a computer that is being scanned and the data gathered sent to a SQL database for later viewing.

image

Of course,  the preferred use of this script is by putting it into a scheduled task so it can be run on a daily schedule to handle all of the updates or new systems that come into the environment.

image

With all of this done, we can quickly verify that data actually exists. We can either look in SQL Server Management Studio for the data, or run a simple PowerShell command using the Invoke-SQL function against one of the tables.

image

PowerShell Example

$TSQL = @"
SELECT TOP 1000 [ComputerName]
      ,[Manufacturer]
      ,[Model]
      ,[SystemType]
      ,[SerialNumber]
      ,[ChassisType]
      ,[Description]
      ,[BIOSManufacturer]
      ,[BIOSName]
      ,[BIOSSerialNumber]
      ,[BIOSVersion]
      ,[InventoryDate]
  FROM [ServerInventory].[dbo].[tbGeneral]
"@

Invoke-SQLCmd -Computername VSQL -TSQL $TSQL -Database ServerInventory -CommandType Query

image

All of this code as well as the rest of the Server Inventory code is available at my GitHub repo here: http://ift.tt/2l6O03a

The last part in this series will take us through building a tool that will pull the data from SQL and provide users with a graphical way to view and generate reports.


Filed under: powershell Tagged: inventory, Powershell, server, SQL, tsql

Powershell

Powershell

via Planet PowerShell http://ift.tt/2ozzxeJ

April 24, 2017 at 12:59PM

Saturday, April 22, 2017

Determine the Default Password Policy for an Active Directory Domain with PowerShell

Determine the Default Password Policy for an Active Directory Domain with PowerShell

http://ift.tt/2pLEMIa

I’ve been working with PowerShell since the version 1.0 days and I’m still amazed that I find cmdlets that I didn’t know existed. Back in 2003, I had written some PowerShell code to query group policy for the lockout policy of an Active Directory domain. It used code similar to what’s shown in the following example which requires the GroupPolicy PowerShell module that installs as part of the RSAT (Remote Server Administration Tools).

I recently discovered that there’s a Get-ADDefaultDomainPasswordPolicy cmdlet that’s part of the ActiveDirectory PowerShell module that also installs as part of the RSAT.

You could select only the LockoutThreshold property to return the same results as shown in the first example:

The default lockout threshold for active directory accounts is 0 which means they’re never locked out. That’s not good so it’s something you might want to consider adding to your operational readiness testing for your infrastructure. The following example is a Pester test that checks this setting and verifies that it’s not set to zero.

Once you correct the problem by changing the account lockout threshold to a value greater than zero, the test should pass.

I like that Pester shows how long it took to execute the test. This tells me that using the Get-ADDefaultDomainPasswordPolicy is not only easier to use, but it’s also more efficient.

µ



Powershell

Powershell

via Planet PowerShell http://ift.tt/2ozzxeJ

April 21, 2017 at 02:42AM

Powershell: Remote install software

Powershell: Remote install software

http://ift.tt/2ogjGoc

I previously covered how to silently installing a MSI. The next thing an administrator wants to do is install it on a remote system. That is the logical next step. This isn’t always the easiest task for someone new to Powershell. Index Index Introduction Running installers remotely Installing from a...

Powershell

Powershell

via Planet PowerShell http://ift.tt/2ozzxeJ

April 22, 2017 at 06:47AM

Determine the Default Password Policy for an Active Directory Domain with PowerShell

Determine the Default Password Policy for an Active Directory Domain with PowerShell

http://ift.tt/2pLEMIa

I’ve been working with PowerShell since the version 1.0 days and I’m still amazed that I find cmdlets that I didn’t know existed. Back in 2003, I had written some PowerShell code to query group policy for the lockout policy of an Active Directory domain. It used code similar what’s shown in the following example which requires the GroupPolicy PowerShell module that installs as part of the RSAT (Remote Server Administration Tools).

I recently discovered that there’s a Get-ADDefaultDomainPasswordPolicy cmdlet that’s part of the ActiveDirectory PowerShell module that also installs as part of the RSAT.

You could select only the LockoutThreshold property to return the same results as shown in the first example:

The default lockout threshold for active directory accounts is 0 which means they’re never locked out. That’s not good so it’s something you might want to consider adding to your operational readiness testing for your infrastructure. The following example is a Pester test that checks this setting and verifies that it’s not set to zero.

Once you correct the problem by changing the account lockout threshold to a value greater than zero, the test should pass.

I like that Pester shows how long it took to execute the test. This tells me that using the Get-ADDefaultDomainPasswordPolicy is not only easier to use, but it’s also more efficient.

µ



Powershell

Powershell

via Mike F Robbins http://mikefrobbins.com

April 21, 2017 at 02:14AM

Friday, April 21, 2017

Check Backups

Check Backups

http://ift.tt/2p2zKco

Check for successful backups in NetWorker

Powershell

Powershell

via PowerShell Script Repository http://poshcode.org/

April 20, 2017 at 02:53PM

Thursday, April 20, 2017

PowerShell Studio 2017: Service Release v5.4.139

PowerShell Studio 2017: Service Release v5.4.139

http://ift.tt/2o8pFeL

Today we released a new build of PowerShell Studio 2017 (v5.4.139). In this build we added a number of new features, such as multi-language syntax coloring.

 

New Features

Multi-Language Syntax Coloring Support

Yes, you read that correctly, we added support for syntax coloring to a total of 19 languages / file types.

 

Does this mean PowerShell Studio is replacing PrimalScript?

No. The multi-language syntax coloring feature was only added for your convenience. The purpose of the feature is to allow viewing and basic editing of these files only. We realize often times users are required to work with a variety of file types; this is especially true when working with module projects.  Adding support for multi-language syntax coloring does not mean PowerShell Studio will allow you to compile or build projects using non-PowerShell languages. If you require that functionality, we recommend using PrimalScript instead.

 

Supported Languages:

Language Extensions
PowerShell *.ps1, *.psm1, *.psd1
Batch *.bat
C# *.cs
C++ *.cpp, *.h
C *.c
CSS *.css
HTML *.html, *.htm
INI *.ini, *.inf
Java *.java
JScript *.js
JSON *.json
PHP *.php
Python *.py
SQL *.sql
VB.NET *.vb
VB Script *.vbs
XAML *.xaml
XML *.xml, *.xsl, *.xslt, *.xsd
Text *.txt

 

The following are sample screenshots of different languages.

C#

CSharp

XML

XML

VB Script

VBScript

 

Editing Theme Coloring for Languages

You can edit the language specific coloring via Options->Editor->Font and Color:

Edit Language Coloring

When you save a color preset, it will include the settings for all the languages supported in PowerShell Studio.

 

Module Projects – Support for multiple psd1 and psm1 files

You can now add multiple psd1 and psm1 files to a module project as long as they are located in a sub-directory and not in the root of the project folder.

 

New Control Set

We added a new control set, TextBox – Browse for Folder (Modern) control set. This control uses the FolderBrowserModernDialog control instead of the traditional FolderBrowserDialog.

TextBox - Browse for Folder (Modern)

 

Console – Cancel Execution

We added a Cancel Execution command to the embedded console context menu, which tells the console to stop the execution of the running command.

Console - Cancel Execution

 

 

Please continue providing your feedback. Many of the new features included in the service builds are suggestions from users like you. Therefore, if you have any suggestions or feature requests, please share them with us on our Wish List and Feature Requests forum.



Powershell

Powershell

via SAPIEN Blog http://ift.tt/1oXyxzS

April 20, 2017 at 01:21AM

Saturday, April 15, 2017

Video: PowerShell Non-Monolithic Script Module Design

Video: PowerShell Non-Monolithic Script Module Design

http://ift.tt/2o13nZ2


This past Tuesday night, I presented a session on “PowerShell Non-Monolithic Script Module Design” for the Arizona PowerShell Users Group. The video from that presentation is now available.

The presentation begins at 10 minutes and 30 seconds seconds into the video.

The presentation materials to include the slide deck and code can be found in my presentations repository on GitHub.

µ



Powershell

Powershell

via Planet PowerShell http://ift.tt/2ozzxeJ

April 5, 2017 at 11:17PM

group policy powershell

group policy powershell

http://ift.tt/2oM2KVM

 

First install RSAT or run command on Windows Server 2008 R2 or later Domain Controller

http://ift.tt/1BvUr01

 

10982 Examples

image

image

 imageimage



Powershell

Powershell

via PowerShell 101 http://ift.tt/2pkXmJR

April 11, 2017 at 11:50PM

Add and remove lines in text based config files with PowerShell

Add and remove lines in text based config files with PowerShell

http://ift.tt/2oHSpee

Add and remove lines in text based config files with PowerShell

7. April 2017

blog.feldmann.io

PowerShell Version: >4 
Modules: none

I want to take some text file and look for a specific line, then delete that line and add some other line at the end of the file. Here’s how I made it work:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

# define file for input/output

$outfile = "C:\test.properties"

# set line to be removed

$old_content = 'install=1'

# set line to be added

$new_content = 'install=0'

 

#check if new line is already in place and then skip

$check = get-content $outfile | select-string -pattern $new_content

if (!$check)

    {

    #use temporary variable for enabling overwrite

    $tmp = get-content $outfile | select-string -pattern $old_content -notmatch

    $tmp | Set-Content $outfile

    # add new content at the end of the file

    $new_content | Out-File $outfile -Append ascii

    }



Powershell

Powershell

via Planet PowerShell http://ift.tt/2ozzxeJ

April 6, 2017 at 05:56PM

Test Active Directory User Accounts for a Default Password with PowerShell

Test Active Directory User Accounts for a Default Password with PowerShell

http://ift.tt/2px7Ban


#Requires -Version 3.0 -Modules ActiveDirectory

function Test-MrADUserPassword {

 

<#

.SYNOPSIS

    Test-MrADUserPassword is a function for testing an Active Directory user account for a specific password.

.DESCRIPTION

    Test-MrADUserPassword is an advanced function for testing one or more Active Directory user accounts for a

    specific password.

.PARAMETER UserName

    The username for the Active Directory user account.

 

.PARAMETER Password

    The password to test for.

 

.PARAMETER ComputerName

    A server or computer name that has PowerShell remoting enabled.

 

.PARAMETER InputObject

    Accepts the output of Get-ADUser.

 

.EXAMPLE

     Test-MrADUserPassword -UserName alan0 -Password Password1 -ComputerName Server01

 

.EXAMPLE

     'alan0'. 'andrew1', 'frank2' | Test-MrADUserPassword -Password Password1 -ComputerName Server01

 

.EXAMPLE

     Get-ADUser -Filter * -SearchBase 'OU=AdventureWorks Users,OU=Users,OU=Test,DC=mikefrobbins,DC=com' |

     Test-MrPassword -Password Password1 -ComputerName Server01

 

.INPUTS

    String, Microsoft.ActiveDirectory.Management.ADUser

.OUTPUTS

    PSCustomObject

.NOTES

    Author:  Mike F Robbins

    Website: http://mikefrobbins.com

    Twitter: @mikefrobbins

#>

 

    [CmdletBinding(DefaultParameterSetName='Parameter Set UserName')]

    param (

        [Parameter(Mandatory,

                   ValueFromPipeline,

                   ValueFromPipelineByPropertyName,

                   ParameterSetName='Parameter Set UserName')]

        [Alias('SamAccountName')]

        [string[]]$UserName,

 

        [Parameter(Mandatory)]

        [string]$Password,

 

        [Parameter(Mandatory)]

        [string]$ComputerName,

 

        [Parameter(ValueFromPipeline,

                   ParameterSetName='Parameter Set InputObject')]

        [Microsoft.ActiveDirectory.Management.ADUser]$InputObject

 

    )

    

    BEGIN {

        $Pass = ConvertTo-SecureString $Password -AsPlainText -Force

 

        $Params = @{

            ComputerName = $ComputerName

            ScriptBlock = {Get-Random | Out-Null}

            ErrorAction = 'SilentlyContinue'

            ErrorVariable  = 'Results'

        }

    }

 

    PROCESS {

        if ($PSBoundParameters.UserName) {

            Write-Verbose -Message 'Input received via the "UserName" parameter set.'

            $Users = $UserName

        }

        elseif ($PSBoundParameters.InputObject) {

            Write-Verbose -Message 'Input received via the "InputObject" parameter set.'

            $Users = $InputObject

        }

 

        foreach ($User in $Users) {    

            

            if (-not($Users.SamAccountName)) {

                Write-Verbose -Message "Querying Active Directory for UserName $($User)"

                $User = Get-ADUser -Identity $User

            }

    

            $Params.Credential = (New-Object System.Management.Automation.PSCredential ($($User.UserPrincipalName), $Pass))

 

            Invoke-Command @Params

 

            [pscustomobject]@{

                UserName = $User.SamAccountName

                PasswordCorrect =

                    switch ($Results.FullyQualifiedErrorId -replace ',.*$') {

                        LogonFailure {$false; break}

                        AccessDenied {$true; break}

                        default {$true}

                    }

            }    

    

        }

    

    }      

 

}



Powershell

Powershell

via Planet PowerShell http://ift.tt/2ozzxeJ

April 12, 2017 at 11:27PM