Is there a way to get a special folder from a remote machine?
I'm getting the local folder using this code:
$path = [environment]::getfolderpath("CommonApplicationData")
But I'd like to get it from other machine using a function like this:
$specialFolder = Get-RemoteSpecialFolder "MyRemoteMachine" "CommonApplicationData"
function Get-RemoteSpecialFolder
{
param(
[string]$ComputerName,
[string]$SpecialFolderName
)
Get-WMIObject ...
...
}
You can get this info by reading the remote computers registry (you need permissions of course) like with the function below:
function Get-RemoteSpecialFolder {
[CmdletBinding()]
param(
[string]$ComputerName = $env:COMPUTERNAME,
[string]$SpecialFolderName = 'Common AppData'
)
if (Test-Connection -ComputerName $ComputerName -Count 1 -Quiet) {
$regPath = "SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
try {
$baseKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $ComputerName)
$regKey = $baseKey.OpenSubKey($regPath)
return $regkey.GetValue($SpecialFolderName)
}
catch {
throw
}
finally {
if ($regKey) { $regKey.Close() }
if ($baseKey) { $baseKey.Close() }
}
}
else {
Write-Warning "Computer '$ComputerName' is off-line or does not exist."
}
}
You should be able to find these common environment variables with this:
"Common Desktop"
"Common Start Menu"
"CommonVideo"
"CommonPictures"
"Common Programs"
"CommonMusic"
"Common Administrative Tools"
"Common Startup"
"Common Documents"
"OEM Links"
"Common Templates"
"Common AppData"
P.S. Put the function in first, then call on it
$specialFolder = Get-RemoteSpecialFolder "MyRemoteMachine" "Common AppData"
Related
First off I would like to thank everyone for helping me work thru my issue.
Scope:
I am looking to write a script that will dynamically build the full set of permissions for each printer. As each printer has it's own Dynamic Group and is not allowed to have the everyone group applied to the printer.
Example:
Printer Name: PrinterA
AdGroup for Printer: gprt_PrinterA
Other groups assigned full (Print/Manage Doc/Manage Printer) permissions to the printer : Local Admin/Local Power User/Local Print Operator/Network Admins (Domain Group)
Other groups with Manage Documents and Print permissions to the printer: Endpoint (Domain Group)/Service Desk (Domain Group)/gprt_PrinterA (Domain Group)\
First what works and I see many examples about this across the web but does not meet my requirements:
$DefaultPrinterInfo = Get-Printer -Name PrinterA -Full
Set-Printer -Name PrinterB -PermissionSDDL ($DefaultPrinterInfo.PermissionSDDL)
IMPORTANT:
This however does not work to meet the required specifications. The reason is the gprt_PrinterA group can not exist on PrinterB. PrinterB must have the gprt_PrinterB Group.
In one example I have attempted to:
Set-Printer -Name PrinterB -PermissionSDDL "G:SYD:(A;;LCSWSDRCWDWO;;;BA)(A;OIIO;RPWPSDRCWDWO;;;BA)"
I have attempted to even dynamically create the default permission groups required and if this worked then it would be easy for me to just add 1 more group that is dynamically assigned:
(A;;LCSWSDRCWDWO;;;BA)(A;OIIO;RPWPSDRCWDWO;;;BA)
(A;;LCSWSDRCWDWO;;;PU)(A;OIIO;RPWPSDRCWDWO;;;PU)
(A;;LCSWSDRCWDWO;;;PO)(A;OIIO;RPWPSDRCWDWO;;;PO)
(A;;LCSWSDRCWDWO;;;S-1-5-21-51083937-621610274-1850952788-69794)(A;OIIO;RPWPSDRCWDWO;;;S-1-5-21-51083937-621610274-1850952788-69794)
(A;CIIO;RC;;;S-1-5-21-51083937-621610274-1850952788-69792)(A;OIIO;RPWPSDRCWDWO;;;S-1-5-21-51083937-621610274-1850952788-69792)(A;;SWRC;;;S-1-5-21-51083937-621610274-1850952788-69792)
(A;CIIO;RC;;;S-1-5-21-51083937-621610274-1850952788-69791)(A;OIIO;RPWPSDRCWDWO;;;S-1-5-21-51083937-621610274-1850952788-69791)(A;;SWRC;;;S-1-5-21-51083937-621610274-1850952788-69791)
I kept the groups clean for easy reading but essentially just make it a continuous line with "G:SYD:" in the beginning. Then replace the PermissionSDDL in the above powershell statement. Either way though, I keep getting the error: "[Set-Printer : Access was denied to the specific resource]"
I have even attempted to do the following:
SetSecurityDescriptor method of the Win32_Printer class
Set-PrinterPermission.ps1
The Security Descriptor Definition Language of Love (Part 2)
Adding Multiple Permissions to a Share
These did put me on the correct path! It lets me replace the permission on the printer. But it strips all existing permission, putting on only the single permission specified for the printer. I need to apply a whole set of permissions to the printer as you see above. I am a little out of my realm but learning how to build a Multi-ACL Package to apply to the printer.
I am ok with replacing all permissions, if I can assign a whole set of permissions, or simply add and remove to the existing permissions if they do or not exist.
What I have learned in my research the permission sets need to be:
Print/Manage this Printer
# G:SYD:(A;;LCSWSDRCWDWO;;;$SID)
Print
# G:SYD:(A;;SWRC;;;$SID)
Print/Manage this Printer/Manage Documents/Special Permissions
# G:SYD:(A;;LCSWSDRCWDWO;;;$SID)(A;OIIO;RPWPSDRCWDWO;;;$SID)
I hope someone the help me figure out a solution please.
Ok so after extensively researching I am getting closer.
The "Set-PrinterPermission" script is on the correct path. What I have had to do, is stripped out the ACE function from the script to place it into it's own function.
function New-PrinterACE
{
##[CmdletBinding(SupportsShouldProcess)]
Param (
[Parameter(
Mandatory = $true,
HelpMessage = "User/group to grant permissions"
)]
[String]$UserName,
[Parameter(
Mandatory = $true,
HelpMessage = "Permissions to apply"
)]
[ValidateSet('Takeownership', 'ReadPermissions', 'ChangePermissions', 'ManageDocuments', 'ManagePrinters', 'Print + ReadPermissions')]
[String]$Permission,
[Parameter(
Mandatory = $true,
HelpMessage = "Permissions to apply"
)]
[ValidateSet('Allow', 'Deny', 'System Audit')]
[String]$AccessType
)
$Ace = ([WMIClass] "Win32_Ace").CreateInstance()
$Trustee = ([WMIClass] "Win32_Trustee").CreateInstance()
Write-Verbose "Translating UserName (user or group) to SID"
$SID = (New-Object security.principal.ntaccount $UserName).translate([security.principal.securityidentifier])
Write-Verbose "Get binary form from SID and byte Array"
[byte[]]$SIDArray = , 0 * $SID.BinaryLength
$SID.GetBinaryForm($SIDArray, 0)
Write-Verbose "Fill Trustee object parameters"
$Trustee.Name = $UserName
$Trustee.SID = $SIDArray
Write-Verbose "Translating $Permission to the corresponding Access Mask"
Write-Verbose "Based on https://learn.microsoft.com/en-US/windows/win32/cimwin32prov/setsecuritydescriptor-method-in-class-win32-printer?redirectedfrom=MSDN"
Write-Verbose "https://social.technet.microsoft.com/Forums/Windows/en-US/a67e3ffd-5e41-4e2f-b1b9-c7c2f29a3a12/adding-permissions-to-an-existing-share"
switch ($Permission)
{
'Takeownership'
{
$Ace.AccessMask = "524288"
}
'ReadPermissions'
{
$Ace.AccessMask = "131072"
}
'ChangePermissions'
{
$Ace.AccessMask = "262144"
}
'ManageDocuments'
{
$Ace.AccessMask = "983088"
}
'ManagePrinters'
{
$Ace.AccessMask = "983052"
}
'Print + ReadPermissions'
{
$Ace.AccessMask = "131080"
}
}
Write-Verbose "Translating $AccessType to the corresponding numeric value"
Write-Verbose "Based on https://learn.microsoft.com/en-US/windows/win32/cimwin32prov/setsecuritydescriptor-method-in-class-win32-printer?redirectedfrom=MSDN"
switch ($AccessType)
{
"Allow"
{
$Ace.AceType = 0
$Ace.AceFlags = 0
}
"Deny"
{
$Ace.AceType = 1
$Ace.AceFlags = 1
}
"System Audit"
{
$Ace.AceType = 2
$Ace.AceFlags = 2
}
}
Write-Verbose "Write Win32_Trustee object to Win32_Ace Trustee property"
$Ace.Trustee = $Trustee
Return $ACE
}
$MyPrinterAces = #()
$MyPrinterAces += New-PrinterACE -UserName <DomainUserA> -Permission ManagePrinters -AccessType Allow
$MyPrinterAces += New-PrinterACE -UserName <DomainUserA> -Permission ManageDocuments -AccessType Allow
$MyPrinterAces += New-PrinterACE -UserName "DomainGroupA" -Permission ManageDocuments -AccessType Allow
$MyPrinterAces += New-PrinterACE -UserName "DomainGroupA" -Permission 'Print + ReadPermissions' -AccessType Allow
#https://learn.microsoft.com/en-us/windows/win32/wmisdk/wmi-security-descriptor-objects#example-checking-who-has-access-to-printers
#https://stackoverflow.com/questions/60261292/explicit-access-array-from-acl-win32-api
This, with a few other cosmetic modifications to the "Set-PrinterPermission" script to accommodate; So that it now references this function to build the ACE's it uses and to add the ability for it to accommodate an array of multiple users/groups with permissions types.
function Set-PrinterPermission
{
[CmdletBinding(SupportsShouldProcess)]
Param (
[Parameter(
Mandatory = $true,
HelpMessage = "Server or array of servers",
ParameterSetName = 'OnePrinter'
)]
[Parameter(
Mandatory = $true,
HelpMessage = "Server or array of servers",
ParameterSetName = 'AllPrinters'
)]
[string[]]$Servers,
[Parameter(
HelpMessage = "Name of the Printer",
ParameterSetName = 'OnePrinter'
)]
[String]$PrinterName,
$PrinterPermissions =
#(
#('Administrators', 'ManagePrinters','Allow'),
#('Power Users', 'ManagePrinters','Allow'),
#('Print Operators', 'ManagePrinters','Allow'),
#('OHD – Network Support Team', 'ManagePrinters','Allow'),
#("OHD – PC Support Team", 'Print + ReadPermissions','Allow'),
#("OHD - Service Desk Users", 'Print + ReadPermissions','Allow')
)
)
Begin
{
$greenCheck =
#{
Object = [Char]8730
ForegroundColor = 'Green'
NoNewLine = $true
}
ConvertFrom-SddlString -Sddl $printer.PermissionSDDL
#Write-Host "Status check... " -NoNewline
#Start-Sleep -Seconds 1
#Write-Host #greenCheck
#Write-Host " (Done)"
Write-Output "Beginning Treatment ..."
Write-Verbose "creating instances of necessary classes ..."
$SD = ([WMIClass] "Win32_SecurityDescriptor").CreateInstance()
$Aces = #()
Foreach ($PrinterPermission in $PrinterPermissions)
{
$Aces += New-PrinterACE -UserName $PrinterPermission[0] -Permission $PrinterPermission[1] -AccessType $PrinterPermission[2]
}
Write-Verbose "Write Win32_Ace and Win32_Trustee objects to SecurityDescriptor object"
$SD.DACL = $Aces
Write-Verbose "Set SE_DACL_PRESENT control flag"
$SD.ControlFlags = 0x0004
}
process
{
try
{
If ($PSCmdlet.ParameterSetName -eq "OnePrinter")
{
ForEach ($Server in $Servers)
{
$Printer = Get-Printer -ComputerName $Server -Name $PrinterName -ErrorAction Stop
$PrinterName = $Printer.name
Write-Output "Beginning treatment of: $PrinterName On: $Server"
Write-Verbose "Get printer object"
<#
It seems that i can't use the Filter parameter using a var
$PrinterWMI = Get-WMIObject -Class WIN32_Printer -Filter "name = $PrinterName"
I've also noticed that I've haven't the same result using Get-CimInstance in particular with
$PrinterCIM.psbase.scope
However I'm sure that using Get-CiMInstance will be better, but i don't know how to proceed
then I'm using the following "Legacy" approach
https://techcommunity.microsoft.com/t5/ask-the-directory-services-team/the-security-descriptor-definition-language-of-love-part-1/ba-p/395202
https://techcommunity.microsoft.com/t5/ask-the-directory-services-team/the-security-descriptor-definition-language-of-love-part-2/ba-p/395258
http://docs.directechservices.com/index.php/category-blog-menu/319-the-security-descriptor-definition-language-of-love
https://learn.microsoft.com/en-us/windows/win32/secauthz/ace-strings?redirectedfrom=MSDN
https://learn.microsoft.com/en-us/windows/win32/secauthz/access-tokens
#>
#$PrinterWMI = (Get-WmiObject -Class WIN32_Printer | Where-Object -FilterScript { $_.Name -like "wilpa0p11" }).GetSecurityDescriptor().Descriptor.dacl
$PrinterWMI = Get-WmiObject -Class WIN32_Printer | Where-Object -FilterScript { $_.Name -like $PrinterName }
Write-Verbose "Enable SeSecurityPrivilege privilegies"
$PrinterWMI.psbase.Scope.Options.EnablePrivileges = $true
Write-Verbose "Invoke SetSecurityDescriptor method and write new ACE to specified"
$PrinterWMI.SetSecurityDescriptor($SD)
Write-Verbose "Treatment of $PrinterName : Completed"
}
} # end if OnePrinter Parameter Set
If ($PSCmdlet.ParameterSetName -eq "AllPrinters")
{
ForEach ($Server in $Servers)
{
$Printers = Get-Printer -ComputerName $Server | Where-Object { $_.Shared -eq $true } -ErrorAction Stop
ForEach ($Printer in $Printers)
{
$PrinterName = $Printer.name
Write-Output "Beginning treatment of : $PrinterName"
Write-Verbose "Get printer object"
<#
It seems that i can't use the Filter parameter using a var
$PrinterWMI = Get-WMIObject -Class WIN32_Printer -Filter "name = $PrinterName"
I've also noticed that I've haven't the same result using Get-CimInstance in particular with
$Printer.psbase.scope
then I'm using the following approach
However I'm sure that using Get-CiMInstance will be better
#>
$PrinterWMI = Get-WmiObject -Class WIN32_Printer | Where-Object -FilterScript { $_.Name -like $PrinterName }
Write-Verbose "Enable SeSecurityPrivilege privilegies"
$PrinterWMI.psbase.Scope.Options.EnablePrivileges = $true
Write-Verbose "Invoke SetSecurityDescriptor method and write new ACE to specified"
$PrinterWMI.SetSecurityDescriptor($SD)
Write-Output "Treatment of $PrinterName : Completed"
}
}
} # end if All Printers Parameter Set
} # End Try
catch
{
Write-Error "Hoops an error occured"
Write-Error $_.Exception.Message
}
}
end
{
Write-Output "All treatments : completed"
}
} # end function
Now this is working great I can easily add the dynamic group as a parameter and a ACE will get assigned to the security descriptor of the printer.
Now my problem is I am unable to add the "Manage Documents" permission to the printer. if anyone can help me with this I will have my project complete.
The permission is assigned correctly for Printing only, and Manage Printer.
Primary Issue needing help resolving:
I am so very close now... what am I doing wrong to apply the "Manage Documents" permission to the printer ACL?
The Image below is the results of the script trying to apply the "Manage Documents" Permissions.
Very Minor Cosmetic help:
is there a way to validate the $PrinterPermissions in the Parameters section of the code? My thinking is to validate the parameter in the begin section of the code and exit out if one of my validations fail. not sure if there is a better way.
I run this script in a user context that has privileges to add members to my AD group. I verified permissions already and I can add members manually via ADUC.
I'd like to add my machine to a specific group on a specific domain controller. I'm very unfamiliar with ADSI usage and I pieced together the below script based on other examples. I'm unable to use PS AD module at the time this script will be ran.
Param(
[Parameter(Mandatory)]
[string]$GroupName
)
#Find domain controllers
$searcher = New-Object System.DirectoryServices.DirectorySearcher([adsi] "LDAP://OU=Domain Controllers,DC=corp,DC=thing,DC=com")
$searcher.Filter = "(objectclass=computer)"
$DomainControllers = $searcher.FindAll()
Write-Verbose "Found DCs:"
foreach ($dc in $DomainControllers.Properties.cn)
{
Write-Verbose "$dc"
}
$TargetController = $null
$ComputerDn = $null
foreach ($dc in $DomainControllers.Properties.cn)
{
$searcher = New-Object System.DirectoryServices.DirectorySearcher([adsi] "LDAP://$dc/DC=corp,DC=thing,DC=com")
$searcher.Filter = "(&(objectclass=computer)(cn=$env:COMPUTERNAME))"
$result = $searcher.FindOne()
try {
if ($result)
{
$TargetController = $dc
Write-Verbose "Target controller set: $TargetController"
$ComputerDn = $result.Properties.distinguishedname
Write-Verbose "Computer DN: $ComputerDn"
break
}
else
{
Write-Verbose "Did not find $env:COMPUTERNAME on $dc"
}
}
catch
{
Write-Verbose "$dc ERROR"
}
}
if ($TargetController)
{
$GroupSearcher = New-Object System.DirectoryServices.DirectorySearcher([adsi] "LDAP://$TargetController/DC=corp,DC=thing,DC=com")
$GroupSearcher.Filter = "(&(objectclass=group)(cn=$GroupName))"
$GroupDn = $GroupSearcher.FindOne().Properties.distinguishedname
$Group = [ADSI] "LDAP://$TargetController/$GroupDn"
$ComputerSearcher = New-Object System.DirectoryServices.DirectorySearcher([adsi] "LDAP://$TargetController/DC=corp,DC=thing,DC=com")
$ComputerSearcher.Filter = "(&(objectclass=computer)(cn=$env:COMPUTERNAME))"
$result = $ComputerSearcher.FindOne().Properties.memberof -match "cn=$GroupName,"
if (!$result)
{
try
{
$Computer = [adsi] "LDAP://$TargetController/$ComputerDn"
$Group.Add("$Computer")
}
catch
{
$_.Exception.Message ; Exit 1
}
}
else
{
Write-Verbose "$env:COMPUTERNAME already a member of $GroupName"
}
}
Running this I get the error "Exception calling "Add" with "1" argument(s): "Exception from HRESULT: 0x80005000". I'm open to any alternatives!
As Bill Stewart commented you should either remove the [adsi] accelerator
$Computer = "LDAP://$TargetController/$ComputerDn"
$Group.Add($Computer)
or specify the path
$Computer = [adsi] "LDAP://$TargetController/$ComputerDn"
$Group.Add($Computer.path)
The method expects the path which you've already constructed with "LDAP://$TargetController/$ComputerDn" which makes the cast to an adsi object unnecessary.
I am currently trying to import a .psm1 file dynamically into a script block to execute it.
I am using parallelisation along with jobs as I need to trigger several modules simultaneously as different users.
This is the code:
$tasksToRun | ForEach-Object -Parallel {
$ScriptBlock = {
param ($scriptName, $Logger, $GlobalConfig, $scriptsRootFolder )
Write-Output ("hello $($scriptsRootFolder)\tasks\$($scriptName)")
Import-Module ("$($scriptsRootFolder)\tasks\$($scriptName)")
& $scriptName -Logger $Logger -GlobalConfig $GlobalConfig
}
$job = Start-Job -scriptblock $ScriptBlock `
-credential $Cred -Name $_ `
-ArgumentList ($_, $using:Logger, $using:globalConfig, $using:scriptsRootFolder) `
Write-Host ("Running task $_")
$job | Wait-job -Timeout $using:timeout
if ($job.State -eq 'Running') {
# Job is still running, stop it
$job.StopJob()
Write-Host "Stopped $($job.Name) task as it took too long"
}
else {
# Job completed normally, get the results
$job | Receive-Job
Write-Host "Finished task $($job.Name)"
}
}
The logger variable is a hashtable as defined here:
$Logger = #{
generalLog = $function:Logger
certificateLog = $function:LoggerCertificate
alertLog = $function:LoggerAlert
endpointServiceLog = $function:LoggerEndpointService
}
Currently, it is erroring with the following:
ObjectNotFound: The term
' blah blah blah, this is the code straight from the logger function '
is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
The logger function servers the purpose of logging to a file in a specific way, it is generalised to that it can be used across many tasks.
A cut down example of a logger (probably won't compile, just deleted a bunch of lines to give you the general idea):
function LoggerEndpointService {
param (
# The full service name.
[string]$ServiceFullName,
# The unique identifier of the service assigned by the operating system.
[string]$ServiceId,
# The description of the service.
[string]$Description,
# The friendly service name.
[string]$ServiceFriendlyName,
# The start mode for the service. (disabled, manual, auto)
[string]$StartMode,
# The status of the service. (critical, started, stopped, warning)
[string]$Status,
# The user account associated with the service.
[string]$User,
# The vendor and product name of the Endpoint solution that reported the event, such as Carbon Black Cb Response.
[string]$VendorProduct
)
$ServiceFullName = If ([string]::IsNullOrEmpty($ServiceFullName)) { "" } Else { $ServiceFullName }
$ServiceId = If ([string]::IsNullOrEmpty($ServiceId)) { "" } Else { $ServiceId }
$ServiceFriendlyName = If ([string]::IsNullOrEmpty($ServiceFriendlyName)) { "" } Else { $ServServiceFriendlyNameiceName }
$StartMode = If ([string]::IsNullOrEmpty($StartMode)) { "" } Else { $StartMode }
$Status = If ([string]::IsNullOrEmpty($Status)) { "" } Else { $Status }
$User = If ([string]::IsNullOrEmpty($User)) { "" } Else { $User }
$Description = If ([string]::IsNullOrEmpty($Description)) { "" } Else { $Description }
$VendorProduct = If ([string]::IsNullOrEmpty($VendorProduct)) { "" } Else { $VendorProduct }
$EventTimeStamp = Get-Date -Format "yyyy-MM-ddTHH:mm:ssK"
$Delay = 100
For ($i = 0; $i -lt 30; $i++) {
try {
$logLine = "{{timestamp=""{0}"" dest=""{1}"" description=""{2}"" service=""{3}"" service_id=""{4}""" `
+ "service_name=""{5}"" start_mode=""{6}"" vendor_product=""{7}"" user=""{8}"" status=""{9}""}}"
$logLine -f $EventTimeStamp, $env:ComputerName, $Description, $ServiceFullName, $ServiceId, $ServiceFriendlyName, $StartMode, $VendorProduct, $User, $Status | Add-Content $LogFile -ErrorAction Stop
break;
}
catch {
Start-Sleep -Milliseconds $Delay
}
if ($i -eq 29) {
Write-Error "Alert logger failed to log, likely due to Splunk holding the file, check eventlog for details." -ErrorAction Continue
if ([System.Diagnostics.EventLog]::SourceExists("SDOLiveScripts") -eq $False) {
Write-Host "Doesn't exist"
New-EventLog -LogName Application -Source "SDOLiveScripts"
}
Write-EventLog -LogName "Application" -Source "SDOLiveScripts" `
-EventID 1337 `
-EntryType Error `
-Message "Failed to log to file $_.Exception.InnerException.Message" `
-ErrorAction Continue
}
}
}
Export-ModuleMember -Function LoggerEndpointService
If anyone could help that'd be great, thank you!
As mentioned in the comments, PowerShell Jobs execute in separate processes and you can't share live objects across process boundaries.
By the time the job executes, $Logger.generalLog is no longer a reference to the scriptblock registered as the Logger function in the calling process - it's just a string, containing the definition of the source function.
You can re-create it from the source code:
$actualLogger = [scriptblock]::Create($Logger.generalLog)
or, in your case, to recreate all of them:
#($Logger.Keys) |ForEach-Object { $Logger[$_] = [scriptblock]::Create($Logger[$_]) }
This will only work if the logging functions are completely independent of their environment - any references to variables in the calling scope or belonging to the source module will fail to resolve!
The Vester project creates pester tests that follow a specific pattern of Describe, It, Try, Catch, Remdiate to test and then fix issues with a VMWare environment, Ex. Update-DNS.Tests.ps1.
In semi-pseudo code, the core of the algorithm is the following:
Param(
[switch]$Remediate = $false
)
Process {
Describe -Name "Test Group Name" -Tag #("Tag") -Fixture {
#Some code to load up state for the test group
foreach ($Thing in $Things) {
It -name "Name of first test" -test {
#Some code to load up state for the test
try {
#Conditional tests using Pester syntax
} catch {
if ($Remediate) {
Write-Warning -Message $_
Write-Warning -Message "Remediation Message"
#Code to remediate issues
} else {
throw $_
}
}
}
}
}
}
I would like to be able to write the code that would allow for the following Pester like DSL syntax:
Param(
[switch]$Remediate = $false
)
CheckGroup "AD User Checks" {
ForEach($Aduser in (Get-aduser -Filter * -Properties HomeDirectory)) {
Check "Home directory path exists" {
Condition {
if ($Aduser.HomeDirectory) {
Test-path $Aduser.HomeDirectory | Should be $true
}
}
Remdiation "Create home directory that doesn't exist" {
New-Item -ItemType Directory -Path $Aduser.HomeDirectory
}
}
}
}
Running this would result in something like the following actually being run:
Describe -Name "AD User Checks" -Fixture {
ForEach($Aduser in (Get-aduser -Filter * -Properties HomeDirectory)) {
It -name "Home directory path exists" -test {
try {
if ($Aduser.HomeDirectory) {
Test-path $Aduser.HomeDirectory | Should be $true
}
} catch {
if ($Remediate) {
Write-Warning -Message $_
Write-Warning -Message "Create home directory that doesn't exist"
New-Item -ItemType Directory -Path $Aduser.HomeDirectory
} else {
throw $_
}
}
}
}
}
How can I go about implementing this DSL designed specifically for performing checks and remediations?
Here is some of the code that I have written to try to accomplish this:
Function CheckGroup {
param (
[Parameter(Mandatory, Position = 0)][String]$Name,
[Parameter(Position = 1)]$CheckGroupScriptBlock
)
Describe $CheckGroupName -Fixture $CheckGroupScriptBlock
}
Function Check {
param (
[Parameter(Mandatory, Position = 0)][String]$Name,
$ConditionScriptBlock,
$RemediationScriptBlock
)
It -name $Name -test {
try {
& $ConditionScriptBlock
} catch {
& $RemediationScriptBlock
}
}
}
Function Condition {
[CmdletBinding()]
param (
[Parameter(Position = 1)]$ScriptBlock
)
& $ScriptBlock
}
Function Remediation {
[CmdletBinding()]
param (
$Name,
[Parameter(Position = 1)]$ScriptBlock,
[bool]$Remediate = $false
)
if ($Remediate) {
Write-Verbose $_
Write-Verbose $Name
& $ScriptBlock
} else {
throw $_
}
}
For the function Check I really need to be able to take in a single script block as a parameter but somehow find the Condition and Remediation function calls inside the script block passed and split them out of the script block and blend them into the appropriate spot in the Try {} Catch {} inside the It in the Check function.
I want to be able to replicate this adsutil.vbs behaviour in PowerShell:
cscript adsutil.vbs set W3SVC/$(ProjectWebSiteIdentifier)/MimeMap
".pdf,application/pdf"
and I've gotten as far as getting the website object:
$website = gwmi -namespace "root\MicrosoftIISv2" -class "IISWebServerSetting"
-filter "ServerComment like '%$name%'"
if (!($website -eq $NULL)) {
#add some mimetype
}
and listing out the MimeMap collection:
([adsi]"IIS://localhost/MimeMap").MimeMap
Anyone know how to fill in the blanks so that I can add mimetypes to an exiting IIS6 website?
Ok well after much frustration and research, this is the solution I've come up with...
a) Grab the COM DLL "Interop.IISOle.dll" and put it somewhere easily referenced
(eg. reference the COM component "Active DS IIS Namespace Provider" in a dummy project, build and grab the DLL from the bin folder)
b)
function AddMimeType ([string] $websiteId, [string] $extension,
[string] $application)
{
[Reflection.Assembly]::LoadFile("yourpath\Interop.IISOle.dll") | Out-Null;
$directoryEntry = New-Object System
.DirectoryServices
.DirectoryEntry("IIS://localhost/W3SVC/$websiteId/root");
try {
$mimeMap = $directoryEntry.Properties["MimeMap"]
$mimeType = New-Object "IISOle.MimeMapClass";
$mimeType.Extension = $extension
$mimeType.MimeType = $application
$mimeMap.Add($mimeType)
$directoryEntry.CommitChanges()
}
finally {
if ($directoryEntry -ne $null) {
if ($directoryEntry.psbase -eq $null) {
$directoryEntry.Dispose()
} else {
$directoryEntry.psbase.Dispose()
}
}
}
}
c) Sample usage:
AddMimeType "123456" ".pdf" "application/pdf"
References: Can I setup an IIS MIME type in .NET?
I had this same problem. An alternative to the Interop.IISOle.dll is to use InvokeMember to set the COM bindings.
$adsiPrefix = "IIS://$serverName"
$iisPath = "W3SVC"
$iisADSI = [ADSI]"$adsiPrefix/$iisPath"
$site = $iisADSI.Create("IISWebServer", $script:webSiteNumber)
$xapMimeType = New-Object -comObject MimeMap
SetCOMProperty $xapMimeType "Extension" ".xap"
SetCOMProperty $xapMimeType "MimeType" "application/x-silverlight-app"
$site.Properties["MimeMap"].Add($xapMimeType)
$site.SetInfo()
$site.CommitChanges()
function SetCOMProperty($target, $member, $value) {
$target.psbase.GetType().InvokeMember($member, [System.Reflection.BindingFlags]::SetProperty, $null, $target, $value)
}