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

Add-Computer command is throwing Access is Denied

$
0
0

Hi All,

I have developed a script to change the domain of the remote computer using invoke-command and add-computer command. This is working fine in 2012 Machines.

But when I am trying to execute the same script in 2008 and 2008R2 machines, it is throwing error as Access is Denied.

Can anyone help me on this.

Regards,

Srikantan.


Need help simplifying get-date

$
0
0

I have a script that returns all users from AD who logged in from the last 30 days, but I need to adjust it to make it for the current calendar month. I've got the following code but I could do with some help simplifying it.

$month = (Get-Date -format "MM")
$year = (Get-Date -format "yyyy")

switch ($month)		#if month has less than 31 days
#start switch statement 
{

04 { $myvar = '30' }
06 { $myvar = '30' }
09 { $myvar = '30' }
11 { $myvar = '30' }
02 { if ([datetime]::IsLeapYear($year)){	#if current year is a leap year
	$myvar = '29'
}
	else {
	$myvar = '28'}
	}
}#end switch statement

So $myvar is the variable it uses to query AD users and say Where-Object {$_.LastLogon -le $myvar}. I haven't implemented this code yet but the script works fine at the moment with a variable set to 30 so let's put Active Directory to one side, because this is adapted from the first PS script I ever wrote and is very sloppy. Can anyone help in simplifying it at all?

Thanks in advance

Change the type of the X Axis in Excel 2010 with Powershell

$
0
0

Hi,

I am working on a project of daily reporting and the simplest way is to use powershell to export the datas and put it in an excel worksheet. In another worksheet, I use the datas to create a graph, everything is working fine except that even if the datas only use workdays, the graphs include weekend days, with blank bars.

After some searchs, I have found that in Excel, you have to change the horizontal (X) axis type to "Text Axis" in order to get rid of the weekends.

But, as I want to automate the process with powershell, I need to know how to change the type of the X axis with a command line.

Do you know how to tell Excel to use a Text X Axis type with a powershell command line ?

Thanks in advance for your help,

Best regards,

Thibaut

Bamboozled by the pipeline again

$
0
0

I have a set of keys in the registry, of which some have a specific value set for (Default). I need to build an array of just the names of those keys with (Default) equal to a certain value. I have been playing with this scratch code, and I get back the entire key object, and for the life of me I can't grok how to pipe just the key names as text into my array.

I assume this can be done in a one liner, rather than filling a temp array with objects and iterating through that to make a final array?

Thanks!
Gordon

Get-ChildItem "Registry::HKLM\SOFTWARE\PragmaticPraxis"    
| Get-ItemProperty -Name:'(default)' -ErrorAction SilentlyContinue    
| Where-Object -FilterScript {($_.'(default)' -eq 'Rollout') }

And, the secret sauce is 

Select -ExpandProperty PSChildName



Cant enable AD Recycle bin faeture through Power shell

$
0
0

Hi,

I have Server 2008 R2 running in our environement.

Domain functional level set to : 2008 R2

Forest functional level set to : 2008 R2

after checking awl these level i run following command over power shell

Enable-ADOptionalFeature 'Recycle Bin Feature' -Scope ForestOrConfigurationSet -target 'test.com'

and after the following error occured:

Enable-ADOptionalFeature : The FSMO role ownership could not be verified because its directory partition has not replic
ated successfully with at least one replication partner
At line:1 char:25
+ Enable-ADOptionalFeature <<<<  'Recycle Bin Feature' -Scope ForestOrConfigurationSet -target 'test.com'
    + CategoryInfo          : NotSpecified: (Recycle Bin Feature:ADOptionalFeature) [Enable-ADOptionalFeature], ADExce
   ption
    + FullyQualifiedErrorId : The FSMO role ownership could not be verified because its directory partition has not re
   plicated successfully with at least one replication partner,Microsoft.ActiveDirectory.Management.Commands.EnableAD
  OptionalFeature


Kindly help me out why i am facing this problem


electrifying

Get-RDUserSession in Powershell in pssession

$
0
0

I type command in Powershell Get-RDUserSession. I get all connecting user in terminal serwer.

When I type this command in pssession I get error:

Cannot index into a null array.
At C:\windows\system32\windowspowershell\v1.0\Modules\RemoteDesktop\Utility.psm1:54 char:9
+     if ($_script_resource[$Id])
+         ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray

Server is Windows 2012 R2. PSsession i established from Windows 8.1

 

Why does the help documentation for Test-Path restrict its use with files?

New AD User With Different Primary Group At Creation

$
0
0

Is there a way to script creating a new AD user and specify a group other than "Domain Users" as the Primary at creation time?  Right now I can create a new user account, add "AltGrp01", set "AltGrp01" as primary and then remove "Domain Users" membership for new user.

I would like to create the new user as being a member of "AltGrp01" only and with that group set as Primary (without having to remove membership in "Domain Users".  Membership in "Domain Users" is not required at all for this project and I'd like to eliminate the extra step if possible.  Thanks.



Server 2012 R2 powershell install of RemoteAccess (Including DirectAccess)

$
0
0

I am building a test lab with Server 2012 R2 for Remote Access. The GUI install went smooth but I am trying to figure out how to install the role and role services with PowerShell.

From what I read I should be able to use "Install-WindowsFeature RemoteAccess -IncludeManagementTools". Although it has reported to have installed successfully, even after a reboot I don't have the Remote Access management console available to configure it. If I look at Roles "Remote Access" is checked but "DirectAccess and VPN (RAS)" is not selected.

How can I use Powershell to install the DirectAccess option in RemoteAccess?

When to use Microsoft.Win32.RegistryView.Registry64

$
0
0

I'm writing a PowerShell script that modifies the registry and I'm wondering if I need to specify the bittness of the keys I'm trying to modify.  I'm hoping someone can clear this up for me.

As I understand it, in 64-bit versions of Windows, portions of the registry are divided into 32-bit keys and 64-bit keys.  This is a result of some 32-bit keys being virtualized (or reflected) into 64-bit keys for the sake of interoperability.  The virtualized keys have different paths/names/values and cause problems when accessing the registry with 32-bit applications (on 64-bit machines).

But what about PowerShell? 

I know there are 32 and 64-bit versions of PowerShell:

%systemroot%\SysWOW64\WindowsPowerShell\v1.0\powershell.exe (32)
%systemroot%\System32\WindowsPowerShell\v1.0\powershell.exe (64)

And also Regedit:

%systemroot%\syswow64\regedit.exe (32)
%systemroot%\regedit.exe (64)

The 64-bit versions are the default.  Is there any reason to use the 32-bit version?

As for scripting, is it simply a matter of knowing the bittness of the registry key in question and usingMicrosoft.Win32.RegistryView.Registry64 when needed?  What if I need to modify registry entries for 32-bit applications that are installed on 64-bit machines?


Finding files 10k and greater

$
0
0

I am using the Get-ChildItem cmdlet and need to pull out a list of 10k or larger files and copy them to a list. How do I express the

10k property in a powershell script to accomplish it though? Thanks for an y help, summer_gregg (below I put in write-host instead of copy)

$ara_prog=@(Get-ChildItem"C:\Program Files\*"-Include.txt-recurse|Sort-Objectlength)


$txt_file

=Get-ChildItem-name



foreach

($txt_filein$ara_prog)

{

if($txt_file-gt10)

{

  

Write-Host$txt_file


}

}

get objectsid property

$
0
0

is it possible to get the objectsid property based on a txt file populated with username or samaccounts from one domain.

and then using the same file populate the msRTCSIP-OriginatorSID using a separate PS?

thanks

Function cannot evaluate percentage

$
0
0

Hi All,

Does anyone know how i might be able to get this function to evaluate table cells containing (%) percentage values? It can currently only evaluate cells containing numbers without the (%) sign displayed in the cell.

Any assistance would be much appreciated.

Function Set-CellColor
{
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true, Position = 0)][string]$Property,
[Parameter(Mandatory = $true, Position = 1)][string]$Color,
[Parameter(Mandatory = $true, ValueFromPipeline = $true)][Object[]]$InputObject,
[Parameter(Mandatory = $true)][string]$Filter
)
Begin
{
Write-Verbose "$(Get-Date): Function Set-CellColor begins"
If ($Filter)
{
If ($Filter.ToUpper().IndexOf($Property.ToUpper()) -ge 0)
{
$Filter = $Filter.ToUpper().Replace($Property.ToUpper(), "`$Value")
Try
{
[scriptblock]$Filter = [scriptblock]::Create($Filter)
}
Catch
{
Write-Warning "$(Get-Date): ""$Filter"" caused an error, stopping script!"
Write-Warning $Error[0]
Exit
}
}
Else
{
Write-Warning "Could not locate $Property in the Filter, which is required.  Filter: $Filter"
Exit
}
}
}
Process
{
ForEach ($Line in $InputObject)
{
If ($Line.IndexOf("<tr><th") -ge 0)
{
Write-Verbose "$(Get-Date): Processing headers..."
$Search = $Line | Select-String -Pattern '<th ?[a-z\-:;"=]*>(.*?)<\/th>' -AllMatches
$Index = 0
ForEach ($Match in $Search.Matches)
{
If ($Match.Groups[1].Value -eq $Property)
{
Break
}
$Index++
}
If ($Index -eq $Search.Matches.Count)
{
Write-Warning "$(Get-Date): Unable to locate property: $Property in table header"
Exit
}
Write-Verbose "$(Get-Date): $Property column found at index: $Index"
}
If ($Line.IndexOf("<tr><td") -ge 0)
{
$Search = $Line | Select-String -Pattern '<td ?[a-z\-:;"=]*>(.*?)<\/td>' -AllMatches
$Value = $Search.Matches[$Index].Groups[1].Value -as [double]
If (-not $Value)
{
$Value = $Search.Matches[$Index].Groups[1].Value
}
If (Invoke-Command $Filter)
{
Write-Verbose "$(Get-Date): Criteria met!  Changing cell to $Color..."
$Line = $Line.Replace($Search.Matches[$Index].Value, "<td style=""background-color:$Color"">$Value</td>")
}
}
Write-Output $Line
}
}
End
{
Write-Verbose "$(Get-Date): Function Set-CellColor completed"
}
}

Software triggered IRQ in PS

$
0
0

Is there  a way in powershell to initiate software triggered IRQ. I am trying to use the Measure-command to find the execution time of a script block. But due to the high CPU queue length, I see delays in milliseconds. Since the expected result is within milliseconds, even a slight delay in seconds makes much difference in the final result.

Regards

Ranjith A Paul

System::Management::Automation not recognized in cpp code

$
0
0

I need to call powershell cmdlets from cpp code. The cmdlets which will operate the vm's from the hyper-v.

I found that to run the powershell cmdlets, will have to create powershell object and then could invoke the scripts I need to.

But code fails at the line..

using namespace System::Management::Automation;

I am using a makefile to build my project.

What libs, and dll's I need to add so the project will be able to recognize this namespace.



Copy files over network

$
0
0

I have to copy files from one share network to another share network. But both the share network on different domains. Is it possible to do such via powershell?

$Share 1= //k0z0s1/D$ -- domain -- Busz.com

$Share 2=//Z0k0z1/D$ -- domain -- kozo.com

I want to copy the files from share 1 to Share 2.

Creating a loop through importing a text file

$
0
0

I am currently using this script:

Param(           
    [parameter(Mandatory=$true)]           
    $ManagementServer,           
    [parameter(Mandatory=$true)]           
    $ManagementPackID,           
    [parameter(Mandatory=$true)]           
    $GroupID,
    [parameter(Mandatory=$true)]
    $GroupName
    )

Write-Host "ManagementServer:"$ManagementServer
Write-Host "ManagementPackID: "$ManagementPackID
Write-Host "GroupID: "$GroupID
Write-Host "GroupName: "$GroupName

function CreateManagementPack
{
  param([object]$MG, [string]$ManagementPackID)
  $MPStore = New-Object Microsoft.EnterpriseManagement.Configuration.IO.ManagementPackFileStore
  $MP = New-Object Microsoft.EnterpriseManagement.Configuration.ManagementPack($ManagementPackID, $ManagementPackID, (New-Object Version(1, 0, 0)), $MPStore)
  $MG.ImportManagementPack($MP)
}

function XMLEncode
{
  param([string]$s)
  $s = $s.Replace("&", "&amp;")
  $s = $s.Replace("<", "&lt;")
  $s = $s.Replace(">", "&gt;")
  $s = $s.Replace('"', "&quot;")
  $s = $s.Replace("'", "&apos;")
  return $s.ToString()
}

Write-Host "Adding SCOM Snap-in"
Add-PSSnapin Microsoft.EnterpriseManagement.OperationsManager.Client

Write-Host "Connecting to SCOM Management Group"
$ManagementServer = New-Object Microsoft.EnterpriseManagement.ManagementGroup($ManagementServer)

Write-Host "Getting MP Information and Incrementing Version"
try
{
  $MP = $ManagementServer.GetManagementPacks($ManagementPackID)[0]
  $VIncrement = $MP.Version.ToString().Split('.')
  $VIncrement[$VIncrement.Length - 1] = ([system.int32]::Parse($VIncrement[$VIncrement.Length - 1]) + 1).ToString()
  $MP.Version = ([string]::Join(".", $VIncrement))
}
catch
{
  Write-Host "MP Not Found, Creating New MP"
  CreateManagementPack $ManagementServer $ManagementPackID
  $MP = $ManagementServer.GetManagementPacks($ManagementPackID)[0]
}

$Formula =  '<MembershipRule Comment="Empty Membership Rule">' + `
            '<MonitoringClass>$MPElement[Name="SCIG!Microsoft.SystemCenter.InstanceGroup"]$</MonitoringClass>' + `
            '<RelationshipClass>$MPElement[Name="SCIG!Microsoft.SystemCenter.InstanceGroupContainsEntities"]$</RelationshipClass>' + `
            '<Expression>' + `
            '<SimpleExpression>' + `
            '<ValueExpression>' + `
            '<Value>True</Value>' + `
            '</ValueExpression>' + `
            '<Operator>Equal</Operator>' + `
            '<ValueExpression>' + `
            '<Value>False</Value>' + `
            '</ValueExpression>' + `
            '</SimpleExpression>' + `
            '</Expression>' + `
            '</MembershipRule>'

Write-Host "Getting Alias for the Microsoft.SystemCenter.InstanceGroup.Library Management Pack Reference"
$Alias = ($MP.References | where {$_.Value -like '*Microsoft.SystemCenter.InstanceGroup.Library*'}).key
If (!($Alias))
{
  Write-Host "Management Pack Reference Not Found, Exiting"
  exit
}
ElseIf ($Alias -ne 'SCIG')
{
  Write-Host "Management Pack Reference Found but Alias Not Equal to SCIG. Modifying Formula"
  $Formula = $Formula.Replace("SCIG", $Alias)
}

Write-Host "Creating Group"
$Group = New-Object Microsoft.EnterpriseManagement.Monitoring.CustomMonitoringObjectGroup($ManagementPackID, $GroupID, (XMLEncode -s $GroupName), $Formula)

Write-Host "Adding Group"
$MP.InsertCustomMonitoringObjectGroup($Group)

Write-Host "Script Complete"

and have a text file: (sample.txt)

ManagementServer=Test
ManagementPackID=example.test
GroupID=group1
GroupName=ThisIsFun
======================
ManagementServer=Test2
ManagementPackID=example.test2
GroupID=group2
GroupName=ThisIsFun2

I need to loop through the code and add in the text in the correct spots.

Converting "whencreated" (System.DirectoryServices.ResultPropertyValueCollection) to string

$
0
0

Hi All,

I'm writing a simple script to get few inactive accounts, for better comparison in excel i'm chopping off the time from: whencreted, LastLogonTimeStamp & PwdLastSet like this:

#get the date

$LastLogontimeStamp = $Obj.Properties.Item("LastLogonTimeStamp")

#convert the date in readble format

$LastLoginDate = [datetime]::fromfiletime($LastLogonTimeStamp[0])

#save in a different variable as string

$LogLastLogon = $LastLoginDate.ToString()

#eliminate last 10 chars which is time leaving DD/MM/YYYY format

$LogLastLogon = $LogLastLogon.Substring(0,10)

above works fine for last logn & last pwd change, but i'm getting error while using same logic for whencreated

Cannot convert argument 0 with value "<same date here - DD/MM/YYYY hr:mm:ss>" for "FromFileTime" to type "System.Int64" : Cannot convert value <same date as above> to type"System.Int64". Error: Invalid cast from 'DateTime' to Int64'

when i observed further i can see the item whencreted is already returned in readable date format (DD/MM/YYYY hr:mm:ss) so if i skip 2nd step in above script logic then the value returned is "System.Dir" for all whencreated

I'm totally confused wht am i doing wrong, if any1 can give me some pointers that'd be gr8

Thx! :)



-Match and $Matches[0] in a single if?

$
0
0

This bit of code seems to be working intermittently for me, and I can't nail down what the problem is.

if (($Places[-1] -match "([0-9])") -and ([bool]($Matches[0] -as [int]))) {
some stuff
}

If I make it two different if's it always works, but for the life of me I don't know why this -and version isn't working all the time. I may also be testing excessive conditions, as there really should never be a decimal number there to find, but it seems like this should still work all the time, given a single one or two digit number to be found in the string.

Thoughts?

Gordon

Set an Active Directory ExtendedRight

$
0
0

Hi Everyone I would like to set the DS-Install-Replica (Add/Remove Replica In Domain) on the domain using Powershell.

http://msdn.microsoft.com/en-us/library/ms684351%28VS.85%29.aspx

 

This is the script

$objLDAP = [ADSI]"LDAP://DC=Devenvx,DC=infra,dc=ss,dc=gov,dc=au"
    $objSecurity = $objLDAP.psbase.ObjectSecurity

    ## set the rights and control type
    $objControlType = [System.Security.AccessControl.AccessControlType]::Allow
    $objRights = "ExtendedRight"
    $strGUID = "9923a32a-3607-11d2-b9be-0000f87a36b2"
    #$objInherit = [System.DirecotryServices.ActiveDirectorySecurityInheritance]::All
    $objInherit = [System.DirectoryServices.ActiveDirectorySecurityInheritance]"All"
   
    ## who does this apply to
    $objwho = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList "", "AA-L-AdditionalDC"

    # apply
    $ObjnewACE= New-Object -TypeName System.DirectoryServices.ActiveDirectoryAccessRule -ArgumentList $objwho, $objRights, $objControlType, $objInherit, $strGUID
    $objSecurity.AddAccessRule($ObjnewACE)
    $objLDAP.psbase.CommitChanges()

 

Works fine, except when I go into ADSIEdit, the permission hasn't been set, instead it just seems to add the group and sets nothing.

 

Any ideas?

Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>