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

Has anyone else been successful

$
0
0

I have not been able to successfully run the PowerShell script on the specified website.  I understand the explanation of why it is difficult to gather cross-domain memberships, but I am struggling with running the PowerShell script.

www.itadmintools.com/2011/08/list-forest-wide-active-directory-group.html

Has anyone else been successful?  If so, can you please provide instructions on how you saved and executed this script?

Thank you!

 

Getting AD users with expired accounts

$
0
0

Hello looking for help with this script. It appears to work as expected, gets the expired users, disables the account and moves them to the correct OU. What I can't figure out is why I keep getting the same results each time it runs. I've verified the activity from a previous run, however, after running the script again it still gives me the same list of users that are no longer in the OU, as they have been moved to "disabled".

$today = Get-Date -UFormat "%m-%d-%Y"

# Setting date interval to 14 days.
$expire = (Get-Date).AddDays(-14)

# Outfile and append date string to name.
$ITout = "C:\ExiredITUsers_$today.txt"
$Userout = "C:\ExpiredEndUsers_$today.txt"

$ITsearch = "OU=Users,OU=IT,OU=xxx,OU=xxx,DC=xxx,DC=xxx,DC=xx,DC=xx"
$usersearch = "OU=Users,OU=xxx,OU=xxx,DC=xxx,DC=xxx,DC=xx,DC=xx"

# Get IT expired users and move to the disabled OU.
$ExpiredIT = Get-ADUser -SearchBase $itsearch -Filter * -Properties AccountExpirationDate, Name, DisplayName | where {$_.AccountExpirationDate -le $expire} | where{$_.AccountExpirationDate -ne $null} | select Name, DisplayName, AccountExpirationDate | sort AccountExpirationDate | fl Name, DisplayName, AccountExpirationDate
$ExpiredIT | Out-File -FilePath $ITout
$ITtotal = $ExpiredIT.Count
    if ($ExpiredIT -eq $null){
    
    $body = "No IT accounts have been expired within the last 14 days.`n`nOutput file for IT users is: `n$ITout"
    }
        
    else{
    
    $body = "The following IT accounts have expired. They have been disabled and moved to the IT disabled users OU.`nTotal accounts expired is: $ITtotal `n`nOutput file for IT users is: `n$ITout"
    #$out = $ExpiredIT #| Out-String
    #$body += $out      
        }

$body += "`n`nAdditionally...`n`n"

# Get expired end users and move to the disabled OU.
$ExpiredUser = Get-ADUser -SearchBase $usersearch -Filter * -Properties AccountExpirationDate, Name, DisplayName | where {$_.AccountExpirationDate -le $expire} | where{$_.AccountExpirationDate -ne $null} | select Name, DisplayName, AccountExpirationDate | sort AccountExpirationDate | fl Name, DisplayName, AccountExpirationDate
$ExpiredUser | Out-File -FilePath $Userout
$totals = $ExpiredUser.Count
    if ($ExpiredUser -eq $null){
    
    $body += "No end user accounts have been expired within the last 14 days. `n`nScript location is xxx.ps1 `nOutput file for end users: `n$Userout"
    }
        
    else{
    
    $body += "The following end user accounts have expired. They have been disabled and moved to the disabled users OU.`nTotal accounts expired is: $totals `n `nOutput file is: `n$Userout `n`nScript location is: `nServer: MailServer`nC:\xxx.ps1"
    #$out = $ExpiredUser #| Out-String
    #$body += $out      
        }

    
Send-MailMessage -To "xxx@xxx" -From "xxx@xxx" -Subject "Expired Accounts" -SmtpServer "xxx" -Body $body -Attachments $ITout, $Userout

# Disable and move expired IT staff.
$ExpiredITS = Get-ADUser -SearchBase $ITsearch -Filter * -Properties AccountExpirationDate, Name, DisplayName | where {$_.AccountExpirationDate -le $expire} | where{$_.AccountExpirationDate -ne $null} | select Name
foreach ($account in $ExpiredITS){

$account = $account.Name
Disable-ADAccount -Identity $account
Get-ADUser $account | Move-ADObject -TargetPath "OU=Users,OU=IT,OU=xxx,OU=xxx,DC=xxx,DC=xxx,DC=xx,DC=xx"
}

# Disable and move expired end user staff.
$ExpiredUsers = Get-ADUser -SearchBase $usersearch -Filter * -Properties AccountExpirationDate, Name, DisplayName | where {$_.AccountExpirationDate -le $expire} | where{$_.AccountExpirationDate -ne $null} | select Name
foreach ($account in $ExpiredUsers){

$account = $account.Name
Disable-ADAccount -Identity $account
Get-ADUser $account | Move-ADObject -TargetPath "OU=Users,OU=xxx,OU=xxx,DC=xxx,DC=xxx,DC=xx,DC=xx"
}

copy files to folder dest from SQL table read results

$
0
0

  I'm trying to copy files to a network share based upon results from a SQL query. The files names are stored in the SQL table

with  Invoice_Path(field name)    like \\srv1\pdf\archive\5433_012819.pdf

 I want to parse the file name in table an have a result of 5433.pdf to be copied to a Destination folder example:

  


copy \\srv1\pdf\archive\5433.pdf \\srv2\dailypdf\


  I'm also trying to keep an output of the files read that meets the sql criteria then a count of the files it actually copied.

$targetFolder = "C:\CSV_Destination\" #"

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
 
$SqlConnection.ConnectionString = "Server=(local);Database=StagingDatabase;Integrated Security=True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $("Select * from tbl_Invoices where inv_pdf is null")
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$data = $dataset.Tables[0]
$Data

foreach ($file in $Data)  { 
	$fname = ($file.Invoice_Path).split('.')[0]	# item before the '.'
    $fname
	$prefix = $fname.split('_')[0] # item before the '_'
    $prefix
	$newname=$prefix + '.pdf'

    copy-item  -path $newname -Destination $targetFolder
   
}

Write-Host 'Total number of files read from Table '$fname ' is ' $numFiles
Write-Host 'Total number of files that was copied to '$targetFolder ' is ' $i
 Thanks.


Powershell script to get last password changed for local server accounts and export to csv

$
0
0

Hello I am trying to get the Last Password Changed for Local Server Accounts (Windows Server 2012) and export them to .csv. This is for an Audit purposes.

Thank you.

Merge Multiples PSTs files in to one PST

$
0
0

I need to merge / combine multiples PSTs files in to one PST. I generate multiples small PST files which I would like to merge into one PST.

Thanks for any help

NuGet not found but confirmed exists in AppData

$
0
0

Hello,

When I try Invoke-ASCmd I get the error 'Invoke-ASCmd' is not recognized as the name of a cmdlet.

So, I attempted to install the module sqlserver module.

  • Install-Module sqlserver -Scope CurrentUser.

This yields:

NuGet provider is required to continue.  PowerShellGet requires NuGet provider version '2.8.5.201' or newer to interact with NuGet-based repositories. The NuGet  provider must be available in 'C:\Program Files\PackageManagement\ProviderAssemblies' or...

But when I check the required directory the following exists

AppData\Local\PackageManagement\ProviderAssemblies\nuget\2.8.5.208\Microsoft.PackageManagement.NuGetProvider.dll

The error suggests I run the following, but I am not sure what to do...

Get-PackageProvider -ListAvailable

Name                     Version          DynamicOptions
----                     -------          --------------
msi                      3.0.0.0          AdditionalArguments
msu                      3.0.0.0
PowerShellGet            1.0.0.1          PackageManagementProvider, Type, Scope, AllowClobber, SkipPublisherCheck, ...
Programs                 3.0.0.0          IncludeWindowsInstaller, IncludeSystemComponent

Any ideas what to do?

PowerShell Script Text Output

$
0
0

Hi

I am using the below script and its working accept the text it adds to the file.

It adds the below to the file:

<InstrumentationKey>@{InstrumentationKey=xxxxxx-xxxxx-xxxx-xxxxxx-xxxxxxxxx}</InstrumentationKey>

It should be adding the below without the @{Instrumentaion key}

<InstrumentationKey>xxxxxx-xxxxx-xxxx-xxxxxx-xxxxxxxxx</InstrumentationKey>

Does anyone know whey it would be adding the extra text?

# Check if Application Insights Resource Exists

$EnvironmentName = "Testing"
$ResourceGroup = "TestRG"

$AIResource = Get-AzureRmApplicationInsights -ResourceGroupName "$ResourceGroup" -Name "$EnvironmentName" -ErrorAction SilentlyContinue

if ($AIResource -eq $null) 

{
# Create the App Insights Resource

$resource = New-AzureRMResource `
  -ResourceName $EnvironmentName `
  -ResourceGroupName $resourceGroup `
  -Tag @{ applicationType = "web"; applicationName = $EnvironmentName} `
  -ResourceType "Microsoft.Insights/components" `
  -Location "North Europe" `
  -PropertyObject @{"Application_Type"="web"} `
  -Force


}

$Key = Get-AzureRmApplicationInsights -ResourceGroupName "$ResourceGroup" -Name "$EnvironmentName" | select InstrumentationKey


# Modify Application Insights Config Files

$fileNames = "C:\temppath\ApplicationInsights.config","c:\Temp\ApplicationInsights.config"
$pattern = '<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">'
$IKey1 = "<InstrumentationKey>"
$IKey2 = "</InstrumentationKey>"

Foreach ($fileName in $fileNames)
{
(Get-Content $fileName) | 
    Foreach-Object {
        $_ # send the current line to output
        if ($_ -match "$pattern") 
        {
            #Add Lines after the selected pattern "<InstrumentationKey>$Key</InstrumentationKey>"
        }
    } | Set-Content $fileName

}

How to bulk edit CustomAttributes

$
0
0

Hi,

Can you please help, running through Office 365 and there are quite a few CustomAttributes for a specific thing that have been labelled incorrectly, is there a way to replace all, please see eg

CustomAttribute15 is "HPLaptop" and it needs to say "HP Laptop"

Many Thanks

Scott


New-WebServiceProxy : Schema item 'element' named 'RadarDeployResponse' from namespace 'urn:RadarDeploymentTNS'. If ref is present, all of , , , , , nillable, default, fixed, form, block, and type must be abse

$
0
0

I'm trying to connect to a webservice URI that ends in ?WSDL and im using New-WebServiceProxy -uri but the Powershell console keeps telling me the following:

New-WebServiceProxy : Schema item 'element' named 'RadarDeployResponse' from namespace 'urn:RadarDeploymentTNS'. If ref is present, all of <complexType>, <simpleType>, <key>, <keyref>, <unique>, nillable, default, fixed, form, block, and type must be absent.
At line:1 char:7
+ $WS = New-WebServiceProxy -Uri $WSURI
+       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [New-WebServiceProxy], InvalidOperationException
    + FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.NewWebServiceProxy

I've tried with different types of arguments which can be found in (docs.microsoft.com)
Does anyone know if the XML in ?WSDL is wrong?

Must i remove <s:complexType> tags from:

<s:element name="RadarDeployResponse">
<s:complexType>
<s:sequence>
<s:element name="felkod" type="tns:stringSimpleType8"/>
<s:element name="feltext" type="tns:stringSimpleType9"/>
<s:element minOccurs="1" maxOccurs="500" nillable="true" ref="ns1:ArrayOfUXGSW090"/>
</s:sequence>
</s:complexType>
</s:element>

What is wrong why cant i connect i managed to connect last week.

Clear-Dns​Server​Cache -CacheScope parameter syntax

$
0
0

Hi! I posted this in the DHCP/DNS forum but since it's powershell, they could not be of any help and they suggested I tried this here...

For a specific task, we need to clear only the cache for a specific zone (not the whole cache...)

I can use Clear-DnsServerCache with the -CacheScope parameter but any idea on how to use it ? Let's say I would like to only clear the "ac" cache entries

Clear-DnsServerCache-ComputerName"DNS-Server"-CacheScope"ac" or

Clear-DnsServerCache-ComputerName"DNS-Server"-CacheScope"DC=ac"

don't work...any idea on how to use the CacheScopre parameter ? The documentation only mentions it's a string...

https://docs.microsoft.com/en-us/powershell/module/dnsserver/clear-dnsservercache?view=win10-ps

Thanks!

How to run a powershell script as administrator

$
0
0
I am writing an automated script that changes the password of all the local admin accounts on servers. I am using encryption for the password but how can i elevate the script after it launches as a domain admin and not use any plan txt passwords in the script

Get Users with Office 365 License and City

$
0
0

The billing invoices from Microsoft for O365 services only include "Online Services" as the Product details. We have 4 warehouses, and Accounting needs to post these invoices to the appropriate warehouse, according to the number of users with various O365 licenses.

Would someone be able to provide me with a Powershell script that outputs a list of all licensed users, their specific license, and the City that is found in their AD. We have our OnPremise AD synced with O365 and Azure AD.

Thanks in advance.

Chris

PowerShell "quser" Question

$
0
0

Hi All,

I don't use PowerShell that much and am stuck on a query.

I am trying to logoff any Switched User account within Windows 10 that has been inactive for more than 2 hours.  I have found the following code that logs off any user that is marked as Disconnected.

quser | Select-String "Disc" | ForEach {logoff ($_.tostring() -split ' +')[2]}

But I want to logoff any user that is marked as disconnected (Disc), and who's idle time is more that 120 (2 hours).

Is this possible?  Even if the query just displayed anything over 120 within the "IDLE TIME".

Thanks

Richard

Wait for Internet Explorer to close when launched from Start-Process

$
0
0

I am trying to have my PS script wait until IE is closes before continuing on with the script.  I have tried the -wait and the -nonewwindow options (as found in other posting) - but that does not work.  My best guess is that IE is launching a new process when it loads and so PS detects the first process closing and continues on.  I have also tried saving the process in a variable and looping in a Start-Sleep until "Process.HasExited".

$IEProcess = Start-Process -FilePath $DefaultBrowser -ArgumentList $OWAURL -PassThru
do {Start-Sleep 1} until ($IEProcess.HasExited)

But nothing I have tried is working - the script continues on even though IE is still running.

Does anyone have other suggestions I might try?  What I am trying to do is:

1) Give myself permissions to a mailbox.

2) Launch IE to our OWA site for that mailbox so that I can login and set an OOO reply for a user or other maintenance for the account while they are on extended leave.

3) Close IE

4) Remove my permissions once IE is closef.

The problem being my permissions are being removed before I even have a chance to login to OWA.  So I need the script to "wait" until I close IE and THEN remove my permissions.

Thanks

NK

"Synchronize across time zones" scheduled task option and New-ScheduledTaskTrigger

$
0
0

Hello,

I'm attempting to create a scheduled task with PowerShell (Server 2016, PowerShell 5.1) WITHOUT the trigger option for "Synchronize across time zones" selected.  For example, using this simple script will create a task with the option selected.  I have been unable to not have the "synchronize across time zones" selected.

>>

# define the action for the new scheduled task
$action = New-ScheduledTaskAction -Execute 'notepad.exe'

# setup our trigger, when we are going to run the task
$trigger = New-ScheduledTaskTrigger -Daily -At 10:15am

# register/create the scheduled task with all the information we collected
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "test" -Description "test"

>>

Thanks,

Dasani


Help Convert Select-String into Get-ChildItem to replace Soc Sec

$
0
0

Well the devs finally got the Soc Sec with hyphens in the data so now I thought I can search and replace.  

This works fine but just displays it on my screen.  I would like it to change the text in the files.

Select-String FilePath\*txt -Pattern '\d{3}-\d{2}-(\d{4})'|ForEach-Object{$_ -Replace '\d{3}-\d{2}-(\d{4})' ,'XXX-XX-XXXX'}

How can I get it to write the files? I was thinking Get-ChildItem.

Get-ChildItem FilePath\*txt -Pattern'\d{3}-\d{2}-(\d{4}) |ForEach {(Get-Content $_) -Replace '\d{3}-\d{2}-(\d{4})' ,'XXX-XX-XXXX'}|Set-Content $_}

I receive an unexpected token error of }.  It doesn't matter if I leave the pattern in or not.  Maybe it needs to be on the right side?

If anyone could steer me in the right direction I'd appreciate it.  thanks



Dynamic parameter.... or a better solution?

$
0
0

Hello all,

I have created a script that depends on parameters. For example:

By default only -Main1, -Main2 or -Main3 should be accepted as a parameter. If -Main1 is used, then only -sub1, -sub2 and -sub3 should be accepted. If -Main3 is used, then only -sub4 should be accepted.

I was thinking of dynamic parameters, but maybe there is a better solution available. That is why I am asking here.

Your feedback is appreciated and with kind regards,

Willem-Jan

Searching for Duplicate User (duplicate Surname and Firstname)

$
0
0

Hi all,

I am looking for a way to find users with a duplicate SamAccountName/Name/Name/UPN... basically if a user has 2 or more accounts (excluding admin accounts). The way I am checking it now is by creating a CSV file with users filtered on duplicated Surnames (and excluding some OU's which contain Removed Accounts and Administration Accounts).

So that part is fixed, but now I have to manually check the Surnames to see if it has a duplicate Firstname (GivenName). Could you help me find a way to put this in Powershell as well?

I was thinking of a solution like: If Surname and Givenname -eq 1; then show results…

This is my code so far:

$users = Get-ADUser -Filter {(SN -like "a*")} -Properties SN
$filteredOU = $users | Where-Object -FilterScript { ($_.distinguishedname -notlike '*LSA*') -and ($_.distinguishedname -notlike '*Removed*') -and ($_.distinguishedname -notlike '*Disabled*') }
$idLookup = $filteredOU | ForEach-Object { $idLookup = @{} } { if($_.Surname) { $idLookup[$_.Surname] += 1 } } { $idLookup }
$filteredUsers = $filteredOU | Where-Object { if($_.Surname) { $idLookup[$_.Surname] -gt 1 } }
$filteredUsers | Select-Object -Property SN, Givenname, Name, DistinguishedName | Sort-object -property SN |
Export-Csv -Path H:\Test\Duplicate_ADusers4.csv -NoTypeInformation

Feel free to correct me and make the code much better, as i am in an early stage of learning Powershell.

Thanks in advance.

import csv file using PowerShell to update pager field

$
0
0

Hi there!

I am new in powershell and I would like to update pager field of users. I have done bunch of tests in my lab env, but with no success. As from above, I need to update users Pager field. At first I exported csv with command

Get-ADUser -Filter * -Properties sAMAccountName, pager | Select sAMAccountName, pager | Export-Csv C:\pagers.csv -NoTypeInformation

i have done some changes and tried to import csv with command:

Import-Csv -Path C:\Pagers.csv | ForEach {Set-ADUser $_.sAMAccountName -Replace @{pager=$_.pager}}

but it  doesnt work for me. Can anyone help me, how to accomplish import?

DSC pull to Multi clients?

$
0
0

Hi All,

I have question for DSC configuration problem.

1.I import PC-List csv file in $ComputerName , but can't to generate MOF file.

2.I join some cleints in "myDemo4 -ComputerName PC1,PC2,PC3" are work , but I join 500 clients can show error.

Can I use multi computer list to pull DSC configuration ?

$ComputerName = import-csv D:\PCList.csv 

Configuration myDemo4 {
    param([string[]]$ComputerName)
    Node "$ComputerName" { 
    Registry myDemoReg1 {
        Ensure="Present"
        Key="HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Excel\Security"
        ValueName="WorkbookLinkWarnings"
        ValueData="2"
        }

    Registry myDemoReg2 {
        Ensure="Present"
        Key="HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Word\Options"
        ValueName="DontUpdateLinks"
        ValueData="1"
        }

    Registry myDemoReg3 {
        Ensure="Present"
        Key="HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Word\Options\WordMail"
        ValueName="DontUpdateLinks"
        ValueData="1"
        }
    }         
} 

myDemo4 -ComputerName $computerName

Thanks.


Hi I can't to find solution for solve this issue, I have Event 364 Source File: /Content/1B/DCD02B975BCC454188A2BB1F036E3E590C25641B.exe Destination File: D:\WSUS\WsusContent\1B\DCD02B975BCC454188A2BB1F036E3E590C25641B.exe But I don't know how to deline this KB Number..

Viewing all 21975 articles
Browse latest View live


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