Friday, May 24, 2013

PowerShell : Validate if a folder exists


There are multiple ways to verify if a folder exists or not in PowerShell. 
1. Using the System.IO.Directory .NET namespace
[System.IO.Directory]::Exists($foldername)
The Exists() method returns True if the item specified is a directory and exists. I often use this method in the ValidateScript of PowerShell advanced functions inPowerShell 2.0 and above.
2. Using Test-Path cmdlet in PowerShell
Test-Path $foldername -PathType Container
The Test-Path cmdlet returns True if and only if the specified path is a directory and exists.

PowerShell : Get-Credential at the command line


PowerShell’s Get-Credential cmdlet lets us create a secure credential object for a specified user name and password using a UI dialog:


1
PS> Get-Credential shay

There’s a way of replacing the UI and collect the credentials via the command line. You need to be an administrator to do that and the console must be elevated (e.g “Run as Admin”).The change involves adding a registry value to the HKLM hive:

1
2
$key = "HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds"
Set-ItemProperty -Path $key -Name ConsolePrompting -Value $true

You add the ConsolePrompting value to the above path and set its data to $true. From now on, all Get-Credential calls will look like this:
1
2
3
4
5
PS> Get-Credential shay
Windows PowerShell Credential Request
Enter your credentials.
Password for user shay: ********

To bring back the UI dialog, set the value to $false or remove it all altogether. Note that this trick doesn’t have any effect in the ISE.

Get Windows Firewall rule status in Windows 8 and Server 2012



We can use the Get-NetFirewallRule cmdlet to achieve this. First, let us see how we can use this cmdlet on the local system.
1
Get-NetFirewallRule -All
The above command will list all available Firewall rules irrespective of their state (enabled or disabled) or action (allowed or denied). To filter this further to only enabled firewall rules, we can run:
1
Get-NetFirewallRule -Enabled True
We can filter this further and retrieve only the rules that are enabled and are set to allow.
1
Get-NetFirewallRule -Enabled True -Action Allow
So, how do we use this to retrieve the rules from a remote system? Simple, we need to use a computer name string or a CIM session object as an argument to the -CimSession parameter of Get-NetFirewallRule cmdlet.
1
2
$cimSession = New-CimSession -ComputerName Server-03
Get-NetFirewallRule -CimSession $cimSession -Enabled True -Action Allow
Or
1
Get-NetFirewallRule -CimSession Server-03 -Enabled True -Action Allow