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

LDAP Query to exclude expired accounts

$
0
0

I have a script that has been running fine for a while, but some issues have come up with recent changes in our organization.

The main LDAP query I was using is:

$searcher.Filter = '(&(objectCategory=person)(objectClass=user)(mail=*)(!samaccountname=ITS-*)(!userAccountControl:1.2.840.113556.1.4.803:=2))

I have modified that to now be:

$searcher.Filter = '(&(objectCategory=person)(objectClass=user)(mail=*)(!samaccountname=ITS-*)(!userAccountControl:1.2.840.113556.1.4.803:=2)(|(accountExpires=9223372036854775807)(accountExpires=0)))'

Which I got the (|(accountExpires=9223372036854775807)(accountExpires=0)) from the following article:

http://webactivedirectory.com/microsoft-active-directory/ldap-filter-to-find-accounts-not-set-to-expire-in-microsoft-active-directory/

Now my main question is, if I use that filter then I am assuming that if a user in AD has the Account Expires selected and the date is in the future, then will they still be filtered out, or only if the account is actually now expired?


If you find that my post has answered your question, please mark it as the answer. If you find my post to be helpful in anyway, please click vote as helpful.


Powershell script Add-computer "" -OUPath "" failing when executed.

$
0
0

Good afternoon,

I have the following script that is ran manually with elevated rights to join a windows 7 workstation to a domain and to the right OU.

Add-Computer -domainname "org domain" -OUPath "OU=folder1,DC=part1,DC=part2,DC=part3" -cred domain\ -passthru -verbose

This was working up to a month ago.  If I remove, the -OUPath part of the script, it works as its meant to.  Please if anyone has any ideas that can help, it would be great.

Warm Regards,

New-Item using csv file

$
0
0

I am trying to use a csv file with the new-item and then the copy.

This works well on its own

$UserName = Read-host "Enter User Name"
New-Item E:\PST\WHD\$username -type directory
$PST = Get-ChildItem \\10.36.11.225\whdusers$\$username -Filter *.pst -Recurse | % {$_.FullName}
$PST | Copy-Item -Destination E:\PST\WHD\$username -verbose.

How I can use a csv file with a list of usernames with this sscript?

Sharepoint batch delete from cvs file Powershell script not working

$
0
0

Hi,

I'm trying to use a Powershell script to check if a SharePoint list contains items from a cvs file. If there is a match the script should delete the item from the SharePoint list and move on to the next row.

The code was something I found here: http://sharepointcherie.blogspot.nl/2014/01/use-powershell-to-edit-delete-and-add.html

I used the first part of the code and changed the "exists = 0" to "exists =1" and "if ($exists -eq 0)" to "if ($exists -eq 1)". This because the original code was to remove items when the item was not in the csv list. Also I changed the "if ($item.Title -eq $row.PID)" to "if ($item.<columnname> -eq $row.<columnname>)" because I have a different column I needed to compare than the Title or PID.

Unfortunately it didnt work. Can someone help me to make this work?

#specify file and check to see if it exists.  If it does, continue operations
$csvVariable= Import-CSV "\\networkpath\MyFile.csv"
if ($csvVariable) {"File exists"} else {exit}

# Check if the Sharepoint Snapin is loaded already, and load if not
if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
{Add-PSSnapin Microsoft.SharePoint.PowerShell}
$WebURL = "http://mySharePoint/sites/mysharepointsite"#site name
$listName = "MyListName" # list name
$web = Get-SPWeb -identity $WebURL #Get the SPWeb object and save it to a variable
$list = $web.Lists[$listName] #Get the SPList object to retrieve the list
$items = $list.items #Get all items in this list and save them to a variable

#loop through SharePoint list and delete items that don't appear in csv file
    foreach($item in $items)
    {
      $exists = 0
      #loop through csv and compare item to each row
      foreach ($row in $csvVariable)
      {
        if ($item.Title -eq $row.PID)
        {$exists++}
      }
      #if the item hasn't been found, delete from SharePoint list
      if ($exists -eq 0)
      {$list.GetItemById($item.ID).Delete()}
    }

secure password input while handling special characters

$
0
0

Hello,

I am trying to create a bat file to allow password input at the command prompt.  I use powershell with the following command:

:: =============================================================================================
:: Get Password - hide from the screen
:: =============================================================================================
SETLOCAL DISABLEDELAYEDEXPANSION
SET "psCommand=powershell -Command "$pword = read-host 'password' -AsSecureString ; ^
    $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
        -join("0",[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR))""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set D_PASSWORD=%%p
SETLOCAL ENABLEDELAYEDEXPANSION
SET D_PASSWORD=!D_PASSWORD:~1!

:: =============================================================================================

This works great for all but the exclamation mark (!) character

How can I fix my script to take this character?

Thanks!

Debug Prompt not coming when Powershel breakpoint hit

$
0
0

Hi,

I have created a breakpoint as follows

Set-PSBreakpoint -Command get-process -Script C:\Temp\SP\AutoSPInstaller\AutoSPInstallerFunctions.ps1

or

Set-PSBreakpoint -Script C:\Temp\SP\AutoSPInstaller\AutoSPInstallerFunctions.ps1 -line 2132

Then I launch a batch file which internally calls PowerShell script  AutoSPInstallerFunctions.ps1

C:\Temp\SP\AutoSPInstaller\AutoSPInstallerLaunch.bat

When the breakpoint hits DBG prompt does not show up it only shows me breakpoint hit it never provides me an option of step into, list ,step-over etc...

Any clue!! 


Powershell script to change DNS

$
0
0
$computer = get-content "C:\dns\dns.txt"
 $NICs = Get-WMIObject Win32_NetworkAdapterConfiguration -computername $computer |where{$_.IPEnabled -eq “TRUE”} | select PScomputerName,DNSServersearchOrder | where DNS=1.1.1.1
   Foreach($NIC in $NICs) {

$DNSServers = “2.2.2.2",”3.3.3.3"
  $NIC.SetDNSServerSearchOrder($DNSServers)
  $NIC.SetDynamicDNSRegistration(“TRUE”)
 }

I have the need to change the DNS settings on several servers. I am trying to do this using PowerShell and a txt file. Problem being I need to make sure I am only changing the DNS settings on the NICS that currently have a certain IP. I am not able to make this work. Any suggestions on how I could do this? Please see code above

Thanks for your help

powershell to retrieve certificate expiration date from list computers.

$
0
0

Hi, 

we need to retrieve certificate expiration date from a list of computers on personal certificates of certificates(local computer).  when I ran the script below, it always sopped after two results.  Can anyone help on retrieving certificate expiration date from a list of computers on personal certificates of certificates(local computer)?

$computers=get-content c:\temp\pc.txt
foreach($computer in $computers){Invoke-Command -ComputerName $computer  -ScriptBlock {Get-ChildItem cert:\localmachine\my | Format-Table Subject,Thumbprint,notafter -AutoSize}}


[Powershell] lastlogondate exactly 90 days ago

$
0
0

Dear All,

I beg for help as I'm in a need to build a "GET-ADUSER" command which will find :

1. enabled
2. not used exactly 90 days (not 89 & not 91+)
3. with specific value of "EmployeeID" attribute starting with K* and L0*

I have tried

$90Days = (get-date).adddays(-90)
$colection =$null
$colection = Get-ADUser -resultpagesize 0 -properties * -filter {(lastlogondate -eq $90days) -AND (enabled -eq $True) -and (employeeid -like "K*" -or employeeid -like "L0*")}

and then I tried:

Search-ADAccount -AccountInactive -TimeSpan 90.00:00:00 | ?{$_.enabled -eq $true} 
But I need 90 days old, and not older than 90 days, not even 91 day old. but Exactly 90 days old.

Please help.

Set pscustomobject to return only a specific property

$
0
0

Hi

I don't know if it possible or make sense but is it possible to make an object return only one of its properties when called?

What I mean is, I want to create a "tree" of objects (for example a tree of "DateTime" objects)

I can do it like this:

$Level3 = [pscustomobject]@{
  'Value' = Get-Date
}

$Level2v1 = [pscustomobject]@{
  'Value' = Get-Date
}

$Level2v2 = [pscustomobject]@{
  'Value' = Get-Date
  'Level3' = $Level3
}

$Level1 = [pscustomobject]@{
  'Value' = Get-Date
  'Level2v1' = $Level2v1
  'Level2v2' = $Level2v2
}

Then later I can get the specific data (the DateTime objects) I need like this:

$Level1.Value
$Level1.Level2v2.Level3.Value
$Level1.Level2v2.Level3.Value.GetType().Name

Output:

Tuesday, June 7, 2016 11:03:11 PM
Tuesday, June 7, 2016 11:03:12 PM
DateTime

Can I get the same results without writing "Value" at the end of the lines when I retrieve the data like this:

$Level1.Level2v2.Level3

Maybe by adding a Method or a script or something to my customobject?

Thank you


Identifying the first Sunday of a month...

$
0
0

Evening,

I hope that one of you can help me.

I need to write a script that on the first day of every month FTP downloads a file to an archieve area and uploads it to a diffrent FTP site (as i keep forgetting to do it).

That part was relatively easy to do and i have all the FTP code to do it, I now need to do the same basic task on the first sunday of every month, obviously with the dates varying all the time i am not to sure how to get the infomation i need.

So in the most basic of ways i can think of putting it i need to be able to do the following:

if ($ItsTheFirstSunday -eq $true) { do stuff }

I just dont know how to get $ItsTheFirstSunday

Thanks in advance

Liam

Using LanManServer with Powershell to get Share level permissions & Setup Share level permissions

$
0
0

hi Script Guy,

I would like to know the how to use LanManServer with Powershell to get share level permissions. And apply share level permissions.

I have the two following powershell script that can create share folder and delete share folder.

function create-share {
 param (
 [string]$Server = $(Throw "you must specify a server"),
 [string]$NewShare = $(Throw "Newshare name is mandatory"),
 [string]$Localpath,
 [string]$Description
 )

 $ServerObj = [adsi] "WinNT://$Server/lanmanserver"
 $newshareobj = $ServerObj.create("fileshare",$NewShare)
 $newshareobj.put("path",$Localpath)
 $newshareobj.put("Description",$Description)
 $newshareobj.setinfo()
 $dummy = [adsi] "WinNT://$Server/lanmanserver/$NewShare"
 }
 
# delete a file share
function delete-share {
 param (
 [string]$Server = $(Throw "you must specify a server"),
 [string]$DeleteShare = $(Throw "deleteshare name is mandatory")
 )
 $ServerObj = [adsi] "WinNT://$Server/lanmanserver"
 $ServerObj.delete("fileshare",$DeleteShare)
 $dummy = [adsi] "WinNT://$Server/lanmanserver/$DeleteShare"
 }


 # use this function to test the argument if it has a value or not
function test ($VALUE) {
 if ($VALUE) {
     Write-Host -ForegroundColor GREEN “Good”
 } else {
     Write-Host -ForegroundColor RED   “No Good”
     }
  }

Unable to set user account properties

$
0
0

I'm trying to write a script where I ensure that local user accounts are set with the proper configurations. I can access all of the properties, but I'm getting error messages every time I try to modify them.

When I try to run the following code:

$Computername = $env:COMPUTERNAME

$adsi = [ADSI]"WinNT://$Computername"

$Users = $adsi.Children | where {$_.SchemaClassName -eq 'user'}

$Users[0].MinPasswordLength.value #This returns the minimum password length just fine

$Users[0].MinPasswordLength.value = 8

$Users[0].SetInfo()

I get the following error message:

Exception setting "value": "Exception from HRESULT: 0x80000500F"

Any ideas as to why this fails?



Powerchell: Scan users in multiple AD OU

$
0
0

Hi i have a problem that i need you to help to solve, I want so search through multiple OU´s for Users. I have it working for one OU but i need to make a script that can search through multiple I am currently trying to get it working with two, but i can't seem to get it to work.

Function Update-ADUsers {


Import-Csv -path $csvfile | `

ForEach-Object { 



$Description = $_.'Descripcion'

$sam = $_.'Logon Name'



    Try{ $SAMinAD = Get-ADUser -server $ADServer -Credential $GetAdminact -LDAPFilter "(sAMAccountName=$sam)"}
    Catch{}


    If($SAMinAD -ne $null -and $sam -ne '')
    {
IF ($Description -ne '' ) { Set-ADUser -server $ADServer -Credential $GetAdminact -SearchBase "OU=maincra,DC=depresion,DC=com" -Identity $sam -Replace @{Description = $Description}} 

}
}

    

-ConfigPath not working

$
0
0

Hello,

I am trying to execute the following script but I keep getting the following error...

ERROR: Unable to locate environment configuration

SCRIPT: powershell d:\util\ControlM\DEV\Tools\Wrapper.ps1 -ConfigPath D:\WW\environment\DEV\test.config  -Environment DEV-Country NA

The config is there, so I am not sure if my syntax is off.

Any help would be greatly appreciated.



ps script to archive folders only when the folder has certain file types

$
0
0

How to write powershell script to archive folders only when the folder has files of certain type for instance (.txt, .csv, .xls, .xlsx). My source path is "C:\Temp\Test\" and there are 5 sub-folders

  • foldera
  • folderb
  • folderc
  • folderd
  • foldere
  • Archive

Only foldera, folderb, folderc have the files to be archived, the archive path is "C:\Temp\Test\Archive" and this has folders foldera, folderb so these folders need not be created but files need to be zipped and copied, folderc needs to be created and the files have to be zipped and copied.

$source = "C:\Temp\Test\"
$archive = "C:\Temp\Test\Archive"

if (!(Test-Path -path $archive)) {New-Item $archive -Type Directory}
Copy-Item $source -Destination $archive -recurse -include *.txt,*.csv,*.xls,*.xlsx


SQLEnthusiast


Problems with get-scheduledtask

$
0
0

I'm monitoring multiple 2012 R2 servers (all deployed roughly at the same time) task scheduler where I use get-scheduled task within Invoke-Command to pull information on specific tasks. On one server however I get errors for some reason.

The parameter is incorrect. +CategoryInfo : Invalid argument: (MSFT_ScheduledTask:Root/Microsoft/...T_ScheduledTask) [GetScheduledTask], CimException  +FullyQualifiedErrorId: HRESULT 0x80070057,GetScheduledTask

Any idea what would be causing this sort of behavior just on that one server where it works fine on all the others.


yaro

Powershell Revoke CA

$
0
0

Hello

I have a Powershell which revokes the User and Computer CA but gives Error:

Revoking "05" -- Reason: Unspecified
ICertAdmin::RevokeCertificate: The parameter is incorrect. 0x80070057 (WIN32: 87 ERROR_INVALID_PARAMETER)
CertUtil: -revoke command FAILED: 0x80070057 (WIN32: 87 ERROR_INVALID_PARAMETER)
CertUtil: The parameter is incorrect.

Where is the problem?

Import-Module PSPKI
Import-Module ActiveDirectory
$RequesterNameComputer = "A\B$";
$RequesterNameUser = "A\C";

certutil -view -out "RequestID,SerialNumber,RequesterName,RequestType,NotAfter,CommonName,Certificate Template" csv > "$env:TEMP\tempcerts.csv";

$Csv = Import-Csv -Path "$env:TEMP\tempcerts.csv";
$csv | Select-Object "requester name" | Group-Object -Property "requester name" | Sort-Object -Property count;

$computer = $csv | Where-Object {$_."requester name" -eq $RequesterNameComputer} | ?{$_."Certificate Template" -like "*PlaygroundComputer"};
$computer

ForEach ($com in $computer){
certutil -revoke $com.SerialNumber 5
$computer
}
$User = $csv | Where-Object {$_."requester name" -eq $RequesterNameUser} | ?{$_."Certificate Template" -like "*User"};
$User

ForEach ($usr in $User){
certutil -revoke $usr."SerialNumber" 5
}
$User

unable to get the output of Invoke-sqlcmd while using in scriptblock

$
0
0

I am using a script block to run a query and perform an action depending upon the results of it. Invoke-sqlcmd doesn't seem to be working inside script block. It produces blank output, whereas i put in the same command outside script block, i get the desired output.

Invoke-sqlcmd -query "Select top 1 Message from dbo.xxx order by Timestamp desc" -serverinstance "xxx/sss"

This produces the output as "Data Uploaded;Success:True" when used outside the script block. When i use within a script block, no output. i tried to use -OutVariable and get the result to a variable but no go. 

The other functions such as moving and copying files within script block works. Its only this query that doesn't work.

Powershell ISE Suspend Debug option stop the output

$
0
0

Hi

I have an annoying problem while using Write-Debug in ISE

Example Script:

for ($i = 0 ; $i -lt 10 ; $i++)
{
    $i
    Write-Debug -Message "Loop" -Debug
}

This will output $i then "Loop" then ask you to if to Continue with the options Yes/Yes to All/Halt Command/Suspend and repeat 10 times (If you select Yes)

The problem is if you run the script then select "Suspend", do something then write "exit" the output will not update until you "Suspend" again or "Halt Command" or Select "Yes" 10 times so the script will end.

How can I fix this or work around this?

Also is there any difference between "Yes" and "Yes to All" I don't see that "Yes to All" do something different then "Yes"

Thank you

Viewing all 21975 articles
Browse latest View live


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