Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

Register-PSsessionConfiguration -runas

$
0
0

 Hello, I have created and Registered a PSsessionConfiguration file to allow a Orchestrator Runbook to see if a user is logged into Citrix. The runbook account is from another team in my company and is not an admin in the Citrix space. This account is able to make the remote connection and is able to run the script successfully as long as I register the config with the -runas using an admin account in the Citrix Space. However if I dont use this the account isnt able to load the citrix modules and access the information needed.

My goal is to allow this account only access to the function I created to get-citrixsessions which just returns a true or fals if user is logged in. I don't want the possibllity of this account to be able to drop into a shell and see anything but this function. I also don't know where the -runas account information is stored and if its automatically updated if the account info changes, or if the config needs to be reregisterd, or if it authenticates everytime the script is run.  Can someone please help me understand this process better.

Thanks

ShaneM.


Array of Arrays of Tuples (Custom Objects), or Custom Object of Custom Objects of Custom Objects (Tuples)

$
0
0

I have a need to modify INI files, without changing the order of items in the INI, and I need to do it in PS 2.0.

The sort issue means I can't use a Dictionary, and the PS 2.0 requirement means I can't use an Ordered Dictionary.

My initial thoughts is an Array of Arrays of each section, with Tuples for each name/data pair. I know that tuples are implemented as a PS Custom Object, which has me wondering, is there an argument for or against using PS Objects instead of the Arrays? I'll need to be able to search for and delete individual Tuples, all Tuples in a Section and whole Sections, plus add Sections and Tuples in specific locations.

My concern is not performance, as the INI files I am dealing with are all less than a few hundred lines tops, and the other tasks the code enacts is measured in minutes and hours, so saving a few seconds with optimized INI manipulation is minor. But if one or the other makes for much quicker development, that would push me in a particular direction.

Thanks for any insights.
Gordon


Delete duplicate files using MD5 and group object

$
0
0

Hi,

i am about to clean my HDD from duplicated files (having sometimes 3 same files)

I have the md5 creator (found online, modified a little bit) but actually i dont have idea (lol, im newb), how to delete the files where $_.fullname -contains "*Backup*"

function get-hash
{
 $md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
 return $hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($_.fullname)))

}
get-childitem D:\TEmp\ -Recurse |?{!$_.Psiscontainer}| select fullname,@{n="Hash";e={$_ |get-hash}} |group hash | ?{$_.count -gt 1} 

example:

Name   : 7A-02-A8-C6-27-A1-FC-04-2A-B0-F2-7D-F7-D2-0F-6C
Count  : 2
Group  : {@{FullName=D:\TEmp\working.ps1; Hash=7A-02-A8-C6-27-A1-FC-04-2A-B0-F2-7D-F7-D2-0F-6C}, @{FullName=D:\TEmp\BACKUP\working.ps1; Hash=7A-02-A8-C6-27-A1-FC-04-2A-B0-F2-7D-F7-D2-0F-6C}}
Values : {7A-02-A8-C6-27-A1-FC-04-2A-B0-F2-7D-F7-D2-0F-6C}
i wanna delete the D:\TEMP\BACKUP\working.ps1 file ...

SMS_PowerConfigs

$
0
0

Hi everybody

Is there anybody who can tell me what im doing wrong?

Im trying to enable the default power management setting on a collection in sccm 2012 r2.

All im getting is:

Exception calling "Put" with "0" argument(s): "Generic failure "
At line:165 char:1+ $Collsetting.Put()+ ~~~~~~~~~~~~~~~~~~+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException+ FullyQualifiedErrorId : DotNetMethodException

My Code:

$SiteCode = 'P01'
$Server = 'sccmp01'
$CollectionID = 'P010000A'

cls
[wmi]$Collsetting = Get-WmiObject -Class SMS_CollectionSettings -Namespace root\sms\site_$SiteCode -Filter "CollectionID='$CollectionID'"
$Collsetting = $Collsetting.__PATH

$NonPeakPowerPlan = '<?xml version="1.0" encoding="utf-16"?><PowerScheme xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" GUID="22B698A7-B734-4107-B5E0-
4BD16375F5C2" Name="Balanced (ConfigMgr)" Description="Automatically balances performance with energy consumption on capable hardware (ConfigM
gr)"><PowerSettings><PowerSetting><GUID>3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e</GUID><CurrentACPowerSettingIndex>1200</CurrentACPowerSettingIndex><CurrentDCPowerSettingIndex>600</CurrentDCPowerSettingIndex></PowerSetting><PowerSetting><GUID>29f6c1db-86da-48c5-9fdb-f2b67b1f44da</GUID><CurrentACPowerSettingIndex>3600</CurrentACPowerSettingIndex><CurrentDCPowerSettingIndex>900</CurrentDCPowerSettingIndex></PowerSetting><PowerSetting><GUID>0e796bdb-100d-47d6-a2d5-f7d2daa51f51</GUID><CurrentACPowerSettingIndex>1</CurrentACPowerSettingIndex><CurrentDCPowerSettingIndex>1</CurrentDCPowerSettingIndex></PowerSetting><PowerSetting><GUID>7648efa3-dd9c-4e3e-b566-50f929386280</GUID><CurrentACPowerSettingIndex>1</CurrentACPowerSettingIndex><CurrentDCPowerSettingIndex>1</CurrentDCPowerSettingIndex></PowerSetting><PowerSetting><GUID>a7066653-8d6c-40a8-910e-a1f54b84c7e5</GUID><CurrentACPowerSettingIndex>0</CurrentACPowerSettingIndex><CurrentDCPowerSettingIndex>0</CurrentDCPowerSettingIndex></PowerSetting><PowerSetting><GUID>96996bc0-ad50-47ec-923b-6f41874dd9eb</GUID><CurrentACPowerSettingIndex>1</CurrentACPowerSettingIndex><CurrentDCPowerSettingIndex>1</CurrentDCPowerSettingIndex></PowerSetting><PowerSetting><GUID>5ca83367-6e45-459f-a27b-476b1d01c936</GUID><CurrentACPowerSettingIndex>1</CurrentACPowerSettingIndex><CurrentDCPowerSettingIndex>1</CurrentDCPowerSettingIndex></PowerSetting><PowerSetting><GUID>6738e2c4-e8a5-4a42-b16a-e040e769756e</GUID><CurrentACPowerSettingIndex>1200</CurrentACPowerSettingIndex><CurrentDCPowerSettingIndex>300</CurrentDCPowerSettingIndex></PowerSetting><PowerSetting><GUID>9d7815a6-7ee4-497e-8888-515a05f02364</GUID><CurrentACPowerSettingIndex>0</CurrentACPowerSettingIndex><CurrentDCPowerSettingIndex>0</CurrentDCPowerSettingIndex></PowerSetting><PowerSetting><GUID>d8742dcb-3e6a-4b3c-b3fe-374623cdcf06</GUID><CurrentACPowerSettingIndex>0</CurrentACPowerSettingIndex><CurrentDCPowerSettingIndex>0</CurrentDCPowerSettingIndex></PowerSetting><PowerSetting><GUID>637ea02f-bbcb-4015-8e2c-a1c7b9c0b546</GUID><CurrentACPowerSettingIndex>0</CurrentACPowerSettingIndex><CurrentDCPowerSettingIndex>2</CurrentDCPowerSettingIndex></PowerSetting><PowerSetting><GUID>81cd32e0-7833-44f3-8737-7081f38d1f70</GUID><CurrentACPowerSettingIndex>0</CurrentACPowerSettingIndex><CurrentDCPowerSettingIndex>0</CurrentDCPowerSettingIndex></PowerSetting><PowerSetting><GUID>bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d</GUID><CurrentACPowerSettingIndex>1</CurrentACPowerSettingIndex><CurrentDCPowerSettingIndex>1</CurrentDCPowerSettingIndex></PowerSetting></PowerSettings></PowerScheme>'

$PeakPowerPlan = '<?xml version="1.0" encoding="utf-16"?><PowerScheme xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" GUID="db310065-829b-4671-9647-
2261c00e86ef" Name="Customized Peak (ConfigMgr)" Description="Description for Customized Peak (ConfigMgr)"><PowerSettings><PowerSetting><GUID>3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e</GUID><CurrentACPowerSettingIndex>1200</CurrentACPowerSettingIndex><CurrentDCPowerSettingIndex>660</CurrentDCPowerSettingIndex></PowerSetting><PowerSetting><GUID>29f6c1db-86da-48c5-9fdb-f2b67b1f44da</GUID><CurrentACPowerSettingIndex>3600</CurrentACPowerSettingIndex><CurrentDCPowerSettingIndex>900</CurrentDCPowerSettingIndex></PowerSetting><PowerSetting><GUID>0e796bdb-100d-47d6-a2d5-f7d2daa51f51</GUID><CurrentACPowerSettingIndex>1</CurrentACPowerSettingIndex><CurrentDCPowerSettingIndex>1</CurrentDCPowerSettingIndex></PowerSetting><PowerSetting><GUID>7648efa3-dd9c-4e3e-b566-50f929386280</GUID><CurrentACPowerSettingIndex>1</CurrentACPowerSettingIndex><CurrentDCPowerSettingIndex>1</CurrentDCPowerSettingIndex></PowerSetting><PowerSetting><GUID>a7066653-8d6c-40a8-910e-a1f54b84c7e5</GUID><CurrentACPowerSettingIndex>0</CurrentACPowerSettingIndex><CurrentDCPowerSettingIndex>0</CurrentDCPowerSettingIndex></PowerSetting><PowerSetting><GUID>96996bc0-ad50-47ec-923b-6f41874dd9eb</GUID><CurrentACPowerSettingIndex>1</CurrentACPowerSettingIndex><CurrentDCPowerSettingIndex>1</CurrentDCPowerSettingIndex></PowerSetting><PowerSetting><GUID>5ca83367-6e45-459f-a27b-476b1d01c936</GUID><CurrentACPowerSettingIndex>1</CurrentACPowerSettingIndex><CurrentDCPowerSettingIndex>1</CurrentDCPowerSettingIndex></PowerSetting><PowerSetting><GUID>6738e2c4-e8a5-4a42-b16a-e040e769756e</GUID><CurrentACPowerSettingIndex>1200</CurrentACPowerSettingIndex><CurrentDCPowerSettingIndex>300</CurrentDCPowerSettingIndex></PowerSetting><PowerSetting><GUID>9d7815a6-7ee4-497e-8888-515a05f02364</GUID><CurrentACPowerSettingIndex>0</CurrentACPowerSettingIndex><CurrentDCPowerSettingIndex>0</CurrentDCPowerSettingIndex></PowerSetting><PowerSetting><GUID>d8742dcb-3e6a-4b3c-b3fe-374623cdcf06</GUID><CurrentACPowerSettingIndex>0</CurrentACPowerSettingIndex><CurrentDCPowerSettingIndex>0</CurrentDCPowerSettingIndex></PowerSetting><PowerSetting><GUID>637ea02f-bbcb-4015-8e2c-a1c7b9c0b546</GUID><CurrentACPowerSettingIndex>0</CurrentACPowerSettingIndex><CurrentDCPowerSettingIndex>2</CurrentDCPowerSettingIndex></PowerSetting><PowerSetting><GUID>81cd32e0-7833-44f3-8737-7081f38d1f70</GUID><CurrentACPowerSettingIndex>0</CurrentACPowerSettingIndex><CurrentDCPowerSettingIndex>0</CurrentDCPowerSettingIndex></PowerSetting><PowerSetting><GUID>bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d</GUID><CurrentACPowerSettingIndex>1</CurrentACPowerSettingIndex><CurrentDCPowerSettingIndex>1</CurrentDCPowerSettingIndex></PowerSetting></PowerSettings></PowerScheme>'

$Collsetting.Get()

$PowerConfig = ([WMIClass] "\\$Server\root\SMS\site_$($SiteCode):SMS_PowerConfig").CreateInstance()
$PowerConfig.ConfigID = $CollectionID
$PowerConfig.DurationInSec = 28800
$PowerConfig.NonPeakPowerPlan = $NonPeakPowerPlan
$PowerConfig.PeakPowerPlan = $PeakPowerPlan
$PowerConfig.PeakStartTimeHoursMin = "09:00"
$PowerConfig.WakeUpTimeHoursMin = ""

$Collsetting.PowerConfigs += $PowerConfig.psobject.BaseObject
$Collsetting.Put()


wmmayms

Internet Explorer COM Automation Not Working

$
0
0

I've been searching for a solution to this for a while and I'm stunned and embarrassed I haven't found more helpful pages with information how to solve this problem for myself.

I have a few different scripts that spawn an instance of IE, navigate to the page, then update and click elements.  They work fine with IE 8, but nothing newer.  

$ie = New-Object -comobject InternetExplorer.Application
$ie.Visible = $true
$ie.Navigate($URL)


This works fine.  I can type $ie.document | gm at the console and see getElementById, getElementsByClassName, etc in the list of methods and properties, but if I try to access them I get an error:

Cannot find an overload for "getElementsByClassName" and the argument count: "1".
At line:1 char:36
+ $ie.document.getElementsByClassName <<<< ("input")
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

I found this link:

http://stackoverflow.com/questions/17924770/how-can-i-translate-or-run-a-vbscript-function-inside-a-ps1-file

That gets me a little bit further:

$EmailField = [System.__ComObject].InvokeMember("getElementsByClassName",[System.Reflection.BindingFlags]::InvokeMethod, $null, $ie.document,"email")


If I output $EmailField I get a long list of properties that includes:

type                         : email
value                        :
name                         : email

But when I try to edit $EmailField, I get another error:

PS C:\Users\user> $EmailField.value
PS C:\Users\user> $EmailField.type
PS C:\Users\user> $EmailField.name
PS C:\Users\user> $EmailField.value = "email@email.com"
Property 'value' cannot be found on this object; make sure it exists and is settable.
At line:1 char:13
+ $EmailField. <<<< value = "email@email.com"
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyAssignmentException

Also from the previous site I tried using the similar method as above:

[System.__ComObject].InvokeMember("value",[System.Reflection.BindingFlags]::SetProperty,$null,$EmailField,"email@email.com")


But that caused another error:

Exception calling "InvokeMember" with "5" argument(s): "Unknown name. (Exception from HRESULT: 0x80020006 (DISP_E_UNKNO
WNNAME))"
At line:1 char:34
+ [System.__ComObject].InvokeMember <<<< ("value",[System.Reflection.BindingFlags]::SetProperty,$null,$EmailField,"emai
l@email.com")
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

I found another link that mentioned a missing microsoft.mshtml.dll and related it to this problem with IE without Office installed, which I can't find now, but copying that file and loading it didn't make any difference in the behavior.

I can't believe I'm the only one having this problem...anyone have an idea how I can access the IE Com object on newer versions? 


I hope this post has helped!

List sql backups in a folder then restore the selected backup to the selected database

$
0
0

Hi

I'm created a script that lists the backups in a folder then allows user input to select a backup.

It then needs to list the sql database on a specific server and accepts user input.

I can list the backups as follows

    $Dir = get-childitem $CurDir -recurse
    $List = $Dir | where {$_.extension -eq ".bak"}
    $List | format-table name

but what I want to know is how to format the list to have a number for the selection next to it?

How can I get a list of the sql databases on the server.

Thanks

Wayne

True history of all powershell commands run on a system

$
0
0
Is it possible to somehow log all commands run on a server via powershell? Not something that is limited by session/user but something that logs everything from all users and all programs that call powershell.

Get NTFS Permissions for remote machine

$
0
0

Hello,

I'm working on a Powershell UI to assist our support team members with our Windows servers. One of the functions of the UI is to obtain all shares including all Share Permissions and NTFS permissions for those shares on a remote server and export it to a CSV file. I have been successful in exporting the Share Permissions, however the code I have written so far to obtain the NTFS permissions is failing. It is gathering the NTFS permissions of the path where I export the data vs. the NTFS permission of the shared path on the remote server. Below is the entire section of code....and a screen print of the UI. Any assistance in resolving the issue is greatly appreciated.

I believe there is an issue with this section of code....

            if($XML.Options.Shares.IncludeSubFolderNTFS.Enabled -eq $True){
                Get-Childitem $Path -Recurse | Where-Object {$_.PSIsContainer} | Get-ACL | Select-Object @{Name="Path";Expression={$_.PSPath.Substring($_.PSPath.IndexOf(":")+2) }} -ExpandProperty Access | Export-CSV $OutputFileShareNTFSPermissions -NoTypeInformation}
            else{
                Get-Childitem $Path | Where-Object {$_.PSIsContainer} | Get-ACL | Select-Object @{Name="Path";Expression={$_.PSPath.Substring($_.PSPath.IndexOf(":")+2) }} -ExpandProperty Access | Export-CSV $OutputFileShareNTFSPermissions -NoTypeInformation
            }

$cmsSharePermissions_Click={
        $lblSearchTip.Visible = $False
        Get-ServerName
		$SelectedServer = $ServerName.Substring(0,15)
        Get-ColumnIndex 'Path'
        ForEach ($Sel in $lvMain.SelectedItems){
            $stbarWSAUStatusDesc.Text = "Generating Share Permissions report for " + $ServerName + "...please be patient."
            Start-Sleep -m 4000
            $Share = $Sel.SubItems[$ColumnIndex].Text
            $ShareProperty = @{n="Share";e={$ShareName}}
            $AccessMask = @{n="AccessMask";e={Translate-AccessMask $_.AccessMask}}
            $AceType = @{n="AceType";e={Translate-AceType $_.AceType}}
            $Trustee = @{n="Trustee";e={$_.Trustee.Name}}
            $filter="name='$Share'"
            $WMIQuery = Get-WmiObject -Class Win32_LogicalShareSecuritySetting -ComputerName $SelectedServer | ForEach-Object {
            $ShareName = $_.name
            $_.GetSecurityDescriptor().Descriptor.DACL | Select-Object $Shareproperty,$AccessMask,$AceType,$Trustee}
            $OutputFileSharePermissions = $XML.Options.Shares.ExportFilePath + $SelectedServer + "-" + $XML.Options.Shares.SharePermissionsExportFileName
            $WMIQuery | Export-Csv $OutputFileSharePermissions -NoTypeInformation
        }
        Get-ColumnIndex 'Name'
        ForEach ($Sel in $lvMain.SelectedItems){
            $stbarWSAUStatusDesc.Text = "Generating Share NTFS Permissions report for " + $ServerName + "...please be patient."
            Start-Sleep -m 15000
            $Path = Split-Path $Sel.SubItems[$ColumnIndex].Text -Parent
            $OutputFileShareNTFSPermissions = $XML.Options.Shares.ExportFilePath + $SelectedServer + "-" + $XML.Options.Shares.ShareNTFSPermissionsExportFileName
            if($XML.Options.Shares.IncludeSubFolderNTFS.Enabled -eq $True){
                Get-Childitem $Path -Recurse | Where-Object {$_.PSIsContainer} | Get-ACL | Select-Object @{Name="Path";Expression={$_.PSPath.Substring($_.PSPath.IndexOf(":")+2) }} -ExpandProperty Access | Export-CSV $OutputFileShareNTFSPermissions -NoTypeInformation}
            else{
                Get-Childitem $Path | Where-Object {$_.PSIsContainer} | Get-ACL | Select-Object @{Name="Path";Expression={$_.PSPath.Substring($_.PSPath.IndexOf(":")+2) }} -ExpandProperty Access | Export-CSV $OutputFileShareNTFSPermissions -NoTypeInformation
            }
        }
        $lblSearchTip.Visible = $True
        $lblSearchTip.Text = "Tips: 1) Right-click on a share from the above list to perform an action. 2) Go to the File menu to reset search criteria..."
        $stbarWSAUStatusDesc.Text = "Ready"  
    }


Same command works with enter-pssession but not invoke-command

$
0
0

I'm trying to run an executable remotely with powershell. Right now I'm trying to install Office 2013 SP1, but in the past I've had the same issue with other executables.

The command I'm running is as follows:

Invoke-Command -computername computer01 -scriptBlock {C:\windows\Temp\proplussp2013-kb2817430-fullfile-x86-en-us.exe /quiet}

It finishes almost immediately, returning no result, having not installed anything.

However, if I do the following, it works just fine:

Enter-PSSession computer01
C:\windows\Temp\proplussp2013-kb2817430-fullfile-x86-en-us.exe /quiet
Any idea what my problem with Invoke-Command is?


Eric Hodges

Powershell Script Returning Duplicates

$
0
0

Hi All,

I am running the following powershell script however it is returning duplicate results. Any idea why this might be (assuming it is the nested foreach loop).

function Check-IsGroupMember{

$users = Import-csv .\users.csv

$GroupsHash = @{ 

Archive = "GroupName";
MDMUser = “GroupName”;
OutlookClient = "GroupName";
Access = "GroupName";

}



Foreach ($hash in $groupshash.GetEnumerator()) {

ForEach ($user in $users) {

IF ($hash.Value -ne "AccessADGroup") { $root = [ADSI]"LDAP://ForestDN"} ELSE {$root = [ADSI]"LDAP://AlternateForestDN"}

    $Username = $user.PrimaryEmail

    $strFilter = "(&(objectClass=User)(mail="+ $username +"))"
    $objSearcher = New-Object System.DirectoryServices.DirectorySearcher
    $objSearcher.SearchRoot = $root
    $objSearcher.PageSize = 10000000
    $objSearcher.Filter = $strFilter
    $objSearcher.SearchScope = "Subtree"
    $colResults = $objSearcher.FindOne()
    $objItem = $colResults.Properties


IF (([string]$objItem.memberof).contains($hash.Value) -and $hash.name -eq "Archive") { $ArchiveGroup = "Yes"} ELSE {$ArchiveGroup = "No"}
IF (([string]$objItem.memberof).contains($hash.Value) -and $hash.name -eq "MDMUser") { $MDMUserGroup = "Yes"} ELSE {$MDMUserGroup = "No"}
IF (([string]$objItem.memberof).contains($hash.Value) -and $hash.name -eq "OutlookClient") { $OutlookClientGroup = "Yes"} ELSE {$OutlookClientGroup = "No"}
IF (([string]$objItem.memberof).contains($hash.Value) -and $hash.name -eq "Access") { $AccessGroup = "Yes"} ELSE {$AccessGroup = "No"}


New-Object PSObject -Property @{

'Archive Group' = $ArchiveGroup
'Mobility User' = $MDMUserGroup
'Outlook Client' = $OutlookClientGroup
'Access Group' = $AccessGroup
'Name' = $Username }	


}
}
}
}



Check-IsGroupMember | FT Name,'Archive Group', 'Mobility User', 'Outlook Client', 'Access'

Regards,

Michael.

get-aduser based on sidhistory

$
0
0

Hello, so here's what i'm trying to do, we have our current domain and we have a domain that belongs to a company that we've acquired. I have exported their objectsid attribute among with other ones, and now i'm trying to query our AD by using the exported objectsid attribute (obviously in our domain it will be sidhistory attribute). Here's what i've tried so far (the file contains objectsid and samaccount values - i need to query based on their legacy sid):

import-csv .\amtexp.csv | foreach {Get-ADUser -Filter 'sidhistory -like $_.objectsid'}

This is the error that i'm getting:

Get-ADUser : Property: 'objectsid' not found in object of type: 'System.Management.Automation.PSCustomObject'.
At line:1 char:36
+ import-csv .\amtexp.csv | foreach {Get-ADUser -SearchBase 'ou=amsterdam-amt,ou=c ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-ADUser], ArgumentException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Comm
   ands.GetADUser

I've also tried this:

import-csv .\amtexp.csv | foreach {Get-ADUser -Filter * -Properties sidhistory | Where-Object {$_.sidhistory -like $_.obje
ctsid}}

that returns no errors and no results

Lastly, i've tried:

import-csv .\amtexp.csv | foreach {Get-ADUser -Filter "(sidhistory=$_.objectsid)"}

That returns:

Get-ADUser : Error parsing query: '(sidhistory=@{samaccountname=jvandijk;
objectsid=S-1-5-21-2965642621-1226631172-1998228529-18668}.objectsid)' Error Message: 'Operator Not supported: =' at
position: '12'.
At line:1 char:36
+ import-csv .\amtexp.csv | foreach {Get-ADUser -server americas.swk.pri -Filter " ...
+                                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ParserError: (:) [Get-ADUser], ADFilterParsingException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADFilterParsingException,Micr
   osoft.ActiveDirectory.Management.Commands.GetADUser

please note that samaccountname in '(sidhistory=@{samaccountname=jvandijk; is the actual samaccountname from the legacy domain - not the current domain.

Any suggestions/help will be greatly appreciated.

Thanks!

Export AD users with orgranizationUnit

$
0
0

Hi 

I am using this Poweshell script to export users with last login time. Can any one help with, how I can include organizationUnit in the export file.

$NumDays = 0
$LogDir = ".\Users-Last-Logon.csv"


$currentDate = [System.DateTime]::Now
$currentDateUtc = $currentDate.ToUniversalTime()
$lltstamplimit = $currentDateUtc.AddDays(- $NumDays)
$lltIntLimit = $lltstampLimit.ToFileTime()
$adobjroot = [adsi]''
$objstalesearcher = New-Object System.DirectoryServices.DirectorySearcher($adobjroot)
$objstalesearcher.filter = "(&(objectCategory=person)(objectClass=user)(lastLogonTimeStamp<=" + $lltIntLimit + "))"

$objstalesearcher.PageSize=4000
$users = $objstalesearcher.findall() | select `
@{e={$_.properties.cn};n='Display Name'},`
@{e={$_.properties.cn};f='Organization'},`

@{e={$_.properties.samaccountname};n='Username'},`

@{e={[datetime]::FromFileTimeUtc([int64]$_.properties.lastlogontimestamp[0])};n='Last Logon'},`
@{e={[string]$adspath=$_.properties.adspath;$account=[ADSI]$adspath;$account.psbase.invokeget('AccountDisabled')};n='Account Is Disabled'}

$users | Export-CSV -NoType $LogDir


Not enough quota is available to process this command.

$
0
0


Hi, I'm trying to run a script in a remote Powershell session and I get a 'Not enough quota is available to process this command.' error. The symptoms are identical with the one reported in this bug:

https://connect.microsoft.com/PowerShell/feedback/details/775399/quotas-ignored-after-wmf-3-0-update

but I'm using Powershell 4.0 and the hot fix is not being installing against my Powershell:

http://support.microsoft.com/hotfix/KBHotfix.aspx?kbnum=2842230&kbln=en-us

This is how I'm calling the remote script:

$cred = Get-Credential
Enter-PSSession remote1 -Authentication CredSSP -cred $cred
cd d:\dev
.\Build.ps1


Instead of calling the .\Build.ps1 the error can be simple reproduced with this line:

cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd /C cmd

cmd : Not enough quota is available to process this command.
    + CategoryInfo          : NotSpecified: (Not enough quot...s this command.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

Deleting a few cmds from the above line will make the rest of them to run.

I tried changing the MaxMemoryPerShellMB and MaxProcessesPerShell limits but nothing works:

winrm set winrm/config/winrs '@{MaxProcessesPerShell="10000"}'
winrm set winrm/config/winrs '@{MaxMemoryPerShellMB="2048"}'


Running function with "Write-Host" and redirect output to file does nothing.

$
0
0

Hello,

I created this function:

function TicketSolutionInformation {
Write-Host "User has been created." -ForegroundColor Green
}
TicketSolutionInformation | Out-File -filepath ("123" + ".txt") -append

but the file 123.txt is always empty. Why ?

How to invoke the shutdown event tracker when running restart-computer

$
0
0

In Windows command shell, it is possible to run shutdown /d to specify a reason code and /c to enter a comment into the shutdown event tracker to log why a shutdown was being performed.

I'm not seeing an equivalent parameter for the restart-computer cmdlet in PowerShell.  Is it possible to invoke the shutdown event tracker when running restart-computer?


Contains Method with Case Insensitive Test

$
0
0

Is there a way to make the following test case-insensitive (In Bold)?

## Go get the site to promote the DC in
    $correctEntry = $false
    While ($correctEntry -eq $false)
      {$siteIn = read-host "What site should the new DC be placed within?"
       $correctEntry = $ADSites.Name.Contains($siteIn)
      }


Paul Bergson
MVP - Directory Services
MCITP: Enterprise Administrator
MCTS, MCT, MCSE, MCSA, Security, BS CSci
2012, 2008, Vista, 2003, 2000 (Early Achiever), NT4
Twitter @pbbergs http://blogs.dirteam.com/blogs/paulbergson
Please no e-mails, any questions should be posted in the NewsGroup.
This posting is provided AS IS with no warranties, and confers no rights.


Exception calling “UploadFile” with “2” argument(s): “The Content-Type header cannot be set to a multipart type for this request.”

$
0
0

I'm working on a PowerShell script and am getting the above error, I am not understanding. Any help would be appreciated!

$down = "C:\Script\log\down-hosts.log"
$computers = Get-Content "C:\Script\list\Computers.txt"

$sourcefileName = "source_file.csv"

#ftp server 
$ftp = "sftp://servername" 
$user = "user" 
$pass = "pass"

$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)

# Create empty log file for down hosts (overwrite if exists)
New-Item $down -type file -force

foreach ($computer in $computers) {
if ( Test-Connection -ComputerName $computer -Count 1 -ErrorAction SilentlyContinue ) {
  Write-Host "$computer is up"
  Write-Host "Uploading \\$computer\c$\UPS CSV Exports\$sourcefile..."
  $sourcefilePath = "\\$computer\c$\UPS CSV Exports"
  $uri = New-Object System.Uri($ftp+$computer+"_"+$sourcefileName)
  $webclient.UploadFile($uri,$sourcefilePath+"/"+$sourcefileName)
  if($? -eq $True) {
  write-host "$ftp$sourcefileName ok"
  Remove-Item $sourcefilePath"\"$sourcefileName
 }
} else {
  Write-Host "$computer is down""$computer is down" | Out-File $down -append 
  }
}

In the script, I am using FTP to move a file to an FTP directory and I think this is partly the problem. Instead of using FTP, I could use copy/paste/move for the file due to the FTP server directory being on the same network/domain as the computer running the script. So if you have anyone has a modification to my script, that would be of great help as well as I am newbie when it comes to PowerShell. 

Thanks!


Russ, MCSE

Script to include error checking

$
0
0

Hi All,

Hopefully someone can help me with this.  I'm quite new to powershell and dont really know much about it.  A bit of background on what i want to achieve.  

At the end of each server build (vm or physical), I would like to run a script which does a full inventory of our windows servers and checks for anything which is not configured / installed.  So for example once the server is build, I would like to check what windows features are installed / GPO's are applied / windows activation status etc and then i want the script to create a HTML report and highlight anything it finds which could be missing or not configured.  I understand this is quite vague but for the time being i would just like a generic check and then can fine tune it later.  I have managed to get the following script from another site and added a few modifications myself but need to now get it doing what i want:

Set-ExecutionPolicy RemoteSigned -ErrorAction SilentlyContinue 

$UserName = (Get-Item  env:\username).Value
$ComputerName = (Get-Item env:\Computername).Value 
#$filepath = (Get-ChildItem env:\userprofile).value
$share = "\\files\general$\Operations\Build Reports"

#ReportDate 
$ReportDate = Get-Date | Select -Property DateTime |ConvertTo-Html -Fragment 

#General Information 
$ComputerSystem = Get-WmiObject -Class Win32_ComputerSystem |  
Select -Property Model , Manufacturer , Description , PrimaryOwnerName , SystemType |ConvertTo-Html -Fragment 

#Operating System Information 
$OS = Get-WmiObject -Class Win32_OperatingSystem | Select -Property Caption , CSDVersion , OSArchitecture , OSLanguage | ConvertTo-Html -Fragment 

#Windows Activation Status
$Activation = Get-CimInstance -ClassName SoftwareLicensingProduct | where PartialProductKey | Select Name, @{Label="Grace period (days)"; Expression={ $_.graceperiodremaining / 1440}}, @{Label= "License Status"; Expression={switch (foreach {$_.LicenseStatus}) { 0 {"Unlicensed"} 1 {"Licensed"} 2 {"Out-Of-Box Grace Period"} 3 {"Out-Of-Tolerance Grace Period"} 4 {"Non-Genuine Grace Period"} 5 {"Notification Period"} 6 {"Extended Grace"} } } } | ConvertTo-Html -Fragment 

#Logical Disk Information 
$Disk = Get-WmiObject -Class Win32_LogicalDisk -Filter DriveType=3 | 
Select SystemName , DeviceID , @{Name=”size(GB)”;Expression={“{0:N1}” -f($_.size/1gb)}}, @{Name=”freespace(GB)”;Expression={“{0:N1}” -f($_.freespace/1gb)}} | 
ConvertTo-Html -Fragment 

#Time Zone Information 
$TimeZone = Get-WmiObject -Class Win32_TimeZone | Select Caption , StandardName | ConvertTo-Html -Fragment 

#CPU Information 
$SystemProcessor = Get-WmiObject -Class Win32_Processor  |  Select SystemName , Name , MaxClockSpeed , Manufacturer , status |ConvertTo-Html -Fragment

#Memory Information 
$PhysicalMemory = Get-WmiObject -Class Win32_PhysicalMemory | Select -Property Tag , SerialNumber , PartNumber , Manufacturer , DeviceLocator , @{Name="Capacity(GB)";Expression={"{0:N1}" -f ($_.Capacity/1GB)}} | ConvertTo-Html -Fragment 

#Software Inventory 
$Software = Get-WmiObject -Class Win32_Product | Select Name , Vendor , Version , Caption | ConvertTo-Html -Fragment  

#Windows Features Inventory
$Features = Get-WmiObject -query "select * from win32_optionalfeature where installstate=1" | select Name, Caption | ConvertTo-Html -Fragment

ConvertTo-Html -Body "<font color = blue><H4><B>Report Executed On</B></H4></font>$ReportDate 
<font color = blue><H4><B>Report Generated By</B></H4></font>$username
<font color = blue><H4><B>General Information</B></H4></font>$ComputerSystem 
<font color = blue><H4><B>Operating System Information</B></H4></font>$OS 
<font color = blue><H4><B>Activation Status</B></H4></font>$Activation
<font color = blue><H4><B>Time Zone Information</B></H4></font>$TimeZone 
<font color = blue><H4><B>Disk Information</B></H4></font>$Disk 
<font color = blue><H4><B>Processor Information</B></H4></font>$SystemProcessor 
<font color = blue><H4><B>Memory Information</B></H4></font>$PhysicalMemory 
<font color = blue><H4><B>Windows Features Iventory</B></H4></font>$Features
<font color = blue><H4><B>Software Inventory</B></H4></font>$Software" -CssUri  "$share\style.CSS" -Title "Server Inventory" | Out-File "$share\$ComputerName.html" 

Write-Host "Script Execution Completed" -ForegroundColor Yellow 
Invoke-Item -Path "$share\$ComputerName.html"

So what I would like is in the HTML report, anything that is not done right is highlighted in Red with a quick sentence at the end stating the issue.  So for example where this script checks the Windows Activation status, I would like that any status which is reported that is not "Licensed" is highlighted red in the HTML report and a sentence at the end of the report which reads out something like "Windows is not activated.  Please activate".  All our base build have a certain set of windows features installed, so the  script could reference a set of features installed on a current system (possibly output the windows features from a correctly built system which is output to a file and then compared on the newly built server) and check what is missing and again highlight in red (for example "Failover clustering is not Installed" etc.  

I would appreciate any help that could be provided

Thanks



Export Event Log

$
0
0

Hello,

I want to export event logs from the actuall day, only the error und criticals evnts, to an evtx or evt file.

My script is:

cls
$date = get-date -Format d
$Path = "c:\temp\horst\Application_EventIDs_$date.csv"
$current = get-date
$oldDate = $current.adddays(-1)
get-eventlog 	-logname Application -EntryType Error `
				| Select Index,EventID,MachineName,Category,CategoryNumber,EntryType,@{Name="MyMSG"; Expression = {$_.Message -replace "`r`n", ""}},Source `
				| export-csv $Path

I don't know, how can I export them to an evtx file and also the to event type's, error and critial!

I hope somebody can help me,


Thanks Horst MOSS 2007 Farm; MOSS 2010 Farm; TFS 2010; TFS 2013; IIS 7.5

How to Create Windows Firewall Predefined rules using Powershell

$
0
0

Windows Firewall Predefined rules using Powershell

Following commands are working some time however sometimes it's giving errors. Any help would be appreciated

WORKING ==> Set-NetFirewallRule -DisplayGroup "File and Printer Sharing" -Enabled True 

 

Set-NetFirewallRule -DisplayGroup "File and Printer Sharing" -Enabled True -Direction Inbound

NOT WORKING

PS C:\Windows\system32> Set-NetFirewallRule -DisplayGroup "File and Printer Sharing" -Enabled True -Direction Outbound

Set-NetFirewallRule : One of the port keywords is invalid.
At line:1 char:1
+ Set-NetFirewallRule -DisplayGroup "File and Printer Sharing" -Enabled True -Dire ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (MSFT_NetFirewal...ystemName = ""):root/standardcimv2/MSFT_NetFirewallRule) [Se 
   t-NetFirewallRule], CimException
    + FullyQualifiedErrorId : HRESULT 0x80070057,Set-NetFirewallRule


PS C:\Windows\system32> Set-NetFirewallRule -DisplayGroup "File and Printer Sharing" -Enabled True -Direction Outbound
Set-NetFirewallRule : One of the port keywords is invalid.
At line:1 char:1
+ Set-NetFirewallRule -DisplayGroup "File and Printer Sharing" -Enabled True -Dire ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (MSFT_NetFirewal...ystemName = ""):root/standardcimv2/MSFT_NetFirewallRule) [Se 
   t-NetFirewallRule], CimException
    + FullyQualifiedErrorId : HRESULT 0x80070057,Set-NetFirewallRule


Anoop C Nair (My Blog www.AnoopCNair.com)- Twitter @anoopmannur -FaceBook Forum For SCCM

Viewing all 21975 articles
Browse latest View live