Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all 15028 articles
Browse latest View live

Generate Distribution List and send automatically

$
0
0

I need to generate a Distribution List that was created the day before. I can successfully run the command below and export the CSV file. 

Get-DistributionGroup -resultsize unlimited | Where{$_.WhenCreated -ge ((Get-Date).AddDays(-1))} |
select Name,Displayname,GroupType,PrimarySmtpAddress,WhenCreated |Export-Csv DLCreatedYesterday.csv -NoTypeInformation

Now i need to add a command to send the CSV file to an email address. Please help



Break a powershell menu with a timeout

$
0
0

I'm pretty new in powershell. Looking for a solution to end a menu with a timeout Option.

Operators are asked to end the program with  a yes/no Option. If the y don't press a key in a selected time the menu should end with a Default value

Any ideas ?

Problem with WinRM and Invoke-command

$
0
0

Hi

I'm running a simple script to enumerate the version of Powershell on all my servers.

$servers  = gc ("c:\servs.txt")

foreach ($server in $servers){

 $version = invoke-command -computername $server -scriptblock {$psversiontable.psversion.major}

 }

unfortunately around 70& of the servers respond with the error

[Servername] Connecting to remote server Servername failed with the following error message :

WinRE cannot process the request. The following error occurred while

using Kerberos authentication: Cannot find the computer Servername.

Verify that the computer exists on the network and that the name provided is spelled correctly.

For more information, see the about_Remote_Troubleshooting Help topic.

    + CategoryInfo          : OpenError: (servername:String) [],

PSRemotingTransportException   

+ FullyQualifiedErrorId : NetworkPathNotFound,PSSessionStateBroken

I've run winrm QC on both devices, tried using the hostname, FQDN and IP. The account I use is a domain admin with local rights and I've tested with unrestricted execution policy on both ends. A procmon trace reveals PowerShell reading the HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WSMAN\Client key. In a successful Invoke command it then goes on to send a packet to the end queried device in an unsuccessful attempt it stops there.

Any ideas gratefully accepted.

Alex

Convert excell and csv file cell value to integer

$
0
0

I am trying to compare IP address from an excel sheet and CSV. .If they are equal then I am updating excel sheet value in different column. The problem is power shell is thinking both cell value as string .I am getting the below error while using [int]

Error: "Input string was not in a correct format"

Excel sheet contains both integer and string values.I just need to compare these integer values.Let me know if any idea.

Thanks,

VJ

VBScript and Active Directory Authentication

$
0
0

Hi I want to add code to my VBScript that would run at the start of my script and prompt for a username and PW. If the PW matches AD then continue If not then end

I tried something like this but it doesn't seem to work

'Connect & Authenticates To AD
Dim objNetwork, userPass, userName, userInput
Set objNetwork = CreateObject("WScript.Network")
    ldapServer = "test.testserver.com"
    userName = objNetwork.UserName
    userPass = Inputbox("Enter your password","Input Required")
    sRoot = "LDAP://" & ldapServer
    
    Set dso = GetObject("LDAP:")
    Set xResult = dso.OpenDSObject(sRoot, userName, userPass, ADS_SECURE_AUTHENTICATION)
    MsgBox"Login Successful"
    If Err.Number = "-2147023570"Then
        MsgBox"Wrong Username or password !!!"
    EndIf

---------------------------------------------------------------------------------------------------------------------------

There Error I get is Line 14

Logon Failure: unknown user or bad password
Code: 8007052E

Source Active Directory

System: Logon failure: unknown username or bad password.

Get-ADUser : Object reference not set to an instance of an object

$
0
0

Hi guys!

I created a script to extract a users list from Active Directory, but it works only if I specify that I want users created today.



When I have removed the created date, my script doesn't worked. 

Get-ADUser -Filter {(enabled -eq $true) -and (extensionattribute3 -eq "colaborador") -or (extensionattribute3 -eq "terceiro")} -Properties * | Select @{ expression={$_.Surname}; label='TSLASTNAME' },@{ expression={$_.GivenName}; label='TSFIRSTNAME'},@{
 expression={$_.DisplayName}; label='TSDISPLAYNAME'},@{ expression={$_.PostalCode}; label='TSPOSTALCODE'},@{ expression={$_.Country}; label='TSCOUNTRY'},@{ expression={$_.StreetAddress}; label='TSADDRESSLINE1'},@{ expression={$_.State}; label='TSSTATEPROVINCE'},@{
 expression={$_.Office}; label='TSLOCATIONSITE'},@{ expression={$_.OfficePhone}; label='TSPRIMARYPHONE'},@{ expression={$_.UserPrincipalName}; label='TSPRIMARYEMAIL'},@{ expression={$_.Title}; label='TSTITLE'},@{ expression={$_.Department}; label='TSDEPARTMENT'},@{
 expression={$_.City}; label='TSCITY'},@{ expression={$_.UserPrincipalName}; label='TSLOGINID'},@{ expression={$_.UserPrincipalName}; label='TSUSERID'},@{ expression={$_.msExchUserCulture}; label='TSLOCALE'},@{ expression={$_.extensionAttribute14}; label='TSTYPE'},@{
 expression={$_.extensionAttribute14}; label='TSGROUPUSER' },@{expression={$_.extensionAttribute14}; label='TSPLUSPCUSTVENDOR'},@{expression={$_.extensionAttribute14}; label='TSLANGUAGE'},@{expression={$_.extensionAttribute14}; label='TSTIMEZONE'},@{expression={$_.UserPrincipalName};
 label='TSPERSONID'},@{expression={$_.extensionAttribute14}; label='TSJOBCODE'} | Export-Csv "\\server\integracao.adibm\teste.csv" -NoTypeInformation -Encoding unicode -Force
'99999999 LASTRECORD'| Out-File  "\\server\integracao.adibm\teste.csv" -Append
(Get-Content \\server\integracao.adibm\teste.csv) | % {$_ -replace '"', ""} | out-file -FilePath "\\server\integracao.adibm\teste.csv" -Force -Encoding unicode


Error message:

Get-ADUser : Object reference not set to an instance of an object.
At C:\Scripts\Matricula\script_IBM_V2.ps1:2 char:1
+ Get-ADUser -Filter {(enabled -eq $true) -and (extensionattribute3 -eq "colaborad ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-ADUser], NullReferenceException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.NullReferenceException,Microsoft.ActiveDirectory.Management.Commands.GetADUser

Do you know how to fix this problem?

Thanks.


David Soares MCTS:MBS - MCTS - MCITP


ActiveDirectory

$
0
0

I have created the following script in order to create some groups and have their Group IDs increased according to the msSFU30MaxGidNumber in my domain.

Although their GIDs are successfully increased and assigned to each group, the value of msSFU30MaxGidNumber does not, so everytime i have to manually create a Group and activate Unix attributes, so as to get the value from the one manually created. 

$NIS = Get-ADObject "CN=xxxxx,CN=ypservers,CN=ypServ30,CN=RpcServices,CN=System,DC=internal,DC=xxxs,DC=xxxx" -Properties:*
$maxGid = $NIS.msSFU30MaxGidNumber

                       

Import-CSV $groupfile | ForEach-Object {

Try{
New-ADGroup -Name $_.Name -SamAccountName $_.Name -GroupCategory $_.GroupCategory -GroupScope $_.GroupScope -DisplayName $_.Name -Path $location -Description $_.Description
Set-ADGroup -Identity $_.Name -Replace @{"msSFU30NisDomain" = $_.NISDomain}
Set-ADGroup -Identity $_.Name -Replace @{gidNumber=$maxGid}
$maxGid++
}
Catch
{
Write-Host "Error during group creation"
Exit 1
}

}

Any idea how to overcome this ?

Power shell: Add users from an OU to an AD security Group

$
0
0

Hi,

I know that I can put all users of an ou to an AD security groupe with this PS command:

Get-ADUser-SearchBase'OU=UserAccounts,DC=contoso,DC=local'-Filter*|%{Add-ADGroupMember'gp001'-Members $_ -WhatIf}

But I want to check first if the users are not in 3 AD security groups (gp001, gp002 and gp003). If a user is not and these 3 groups so add him in grp001. And If a users is already in these 3 groupe do not putt him in grp001.

Anybody tell me how can do this script in PS ?

Thanks


New-Partition assignes driver letter to mount point after reboot.

$
0
0

Trying to create a series of mount points using powershell on Server 2012 R2. When I have used diskpart in the past I could initialize the disk, create a partition, format a volume and assign a mount point without assigning a driver letter to the drive. When I try to do the same thing in Powershell on Server 2012 R2, everything looks great until I reboot. Every partition I created and assigned as a mount mount gets a driver letter added to it... I am using mount points to avoid drive letters. Is there a way to prevent this behavior.  The following is an example:

Get-Disk 3 | Initialize-Disk -PartitionStyle GPT
Get-Disk 3 | new-Partition -UseMaximumSize -AssignDriveLetter:$False | Format-volume -confirm:$False
Add-Partitionaccesspath -DiskNumber 3 -Partition 2 -AccessPath c:\someFolder
Everything looks good at this point with no driver letter assigned. Rebooting adds a driver letter to the volume with no impact on the mount point... Is there a way to suppress the driver letter assignment?


Exporting data to CSV

$
0
0

Hello,

I am having an issue with appending printer info to a CSV file it just shows as blank in the file.

Here is my script

@echo off

Echo Querying Programs...Please Wait...

Powershell -ExecutionPolicy Bypass -Command "& {Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Export-Csv -Path "C:\programdata\Programs.csv"}"


Powershell -ExecutionPolicy Bypass -Command "& {Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Export-Csv -Path "C:\programdata\Programs.csv" -append}"


Echo. >>"C:\programdata\Programs.csv"
Echo. >>"C:\programdata\Programs.csv"

Powershell -ExecutionPolicy Bypass -Command "& {Get-Printer | Select-Object Name, DriverName, PortName | Export-Csv -Path "C:\programdata\Programs.csv" -append -force}"

Echo. >>"C:\programdata\Programs.csv"
Echo. >>"C:\programdata\Programs.csv"
net use >>"C:\programdata\Programs.csv"


rename "C:\programdata\Programs.csv" "%username% %computername% Programs.csv"


xcopy "C:\programdata\%username% %computername% Programs.csv" "\\usl5cb2075kgr\SW_Share\User_Programs\" /c /i /y

Del /q /f "C:\programdata\%username% %computername% Programs.csv"

The command in bold is what is giving me trouble. any help would be awesome!


Powershell Script - What is Publickeytoken?

$
0
0
Hi all,
I have this doubt.. reflection.assembly.load (version = 4.0, culture = neutral, publickeytoken = 64b818b3ff69ccfa). What does this mean? Why we are using it?

Parameswaran.

Script for search and delete registry key

$
0
0

Hi Guys,

I'm writing a script to remotely delete a specified users profile. A section of my script gets the SID for the profile that will be removed. I've found that sometimes when Reg Delete runs I get an error saying the path doesn't exist, as though the $ComputerName or $UserProfile variable hasn't been filled. Other times it works perfectly though... I'm confused about why. Is there a way I can perform this task better? Why would it fail when testing on one computer but then be successful on another??

When I test the variables in ISE they seem to work OK. I can do a test-path on "\\$ComputerName\HKLM\SOFTWARE\MICROSOFT\WINDOWS NT\CurrentVersion\ProfileList\$UserProfile" and it returns True...

$UserProfile = Get-WmiObject Win32_UserProfile -Property * |
Where-Object {$_.LocalPath -Contains "C:\Users\$UserName"} |
Select-Object Sid
$UserProfile = $UserProfile -Replace ".*="
$UserProfile = $UserProfile -Replace "}"
$ProfilePath = "\\$ComputerName\HKLM\SOFTWARE\MICROSOFT\WINDOWS NT\CurrentVersion\ProfileList\$UserProfile"
Reg Delete "$ProfilePath" /f



Remotely installing software with batch script or PowerShell?

$
0
0

Hey everybody,

So for the past year or so myself a few other IT guys have been able to use a batch script to PsExec into a list of systems (pulling from a .txt file) and install software that way. Whether it be pushing out the newest version or anything of that kind. Recently we started getting Access Denied errors when trying to run the script. The error is with PsExec. We are managed by a higher level, so I'm not sure if they can have any management over us using PsExec, but they are saying they haven't/can't make any changes. We would open Command Prompt as Admin, navigate to where the batch script is (run.cmd) which would then say hey, for every system in sys.txt, run this batch script (install.cmd).

From anyone else's experience, have you seen this before? We can't seem to find a workaround. I am open to any other kind of scripts that may work exactly how that batch used to. PowerShell and batch are more of my better areas. I am not to familiar with Python or anything. If anyone has any info it would be GREAT! Thanks in advance.

Compare two hashtables

$
0
0

Hello,
i need help to compare two hashtables:

Hashtable 1:

$replace = @{}
$replace['l'] = "Kempten"
$replace['Description'] ="Held des Tages" 
$replace['sn'] = "Proper"
$replace['StreetAddress'] = "Landstrasse"
$replace['wWWHomePage'] = "www.google.de"
$replace['mail'] = "Test@contoso.com"

Hashtable 2
$props = Get-ADUser -Filter { DisplayName -eq "Meister Proper" } -Properties *

$propkey = @{ }
$propkey['l'] = $props.l
$propkey['Description'] = $props.Description
$propkey['sn'] = $props.sn
$propkey['StreetAddress'] = $props.StreetAddress
$propkey['wWWHomePage'] = $props.wWWHomepage
$propkey['mail'] = $props.mail

compare $replace.Values $propkey.Values

Result:

Hashtable 1
Name Value 
---- ----- 
Description Held des Tages 
wWWHomePage www.google.de 
mail Test@contoso.com 
l Kempten 
StreetAddress Landstrasse 
sn Proper

Hashtable 2
Name Value 
---- ----- 
Description wwww 
wWWHomePage 
mail MProper@kempten.de 
l Kempten 
StreetAddress 
sn Proper

Compare-Result

InputObject SideIndicator
----------- -------------
{wwww, $null, MProper@kempten.de, Kempten...} =>
{Held des Tages, www.google.deTest@contoso.com, Kempten...} <=


I need now the different between the hashtables as a new hashtable filtered by SideIndicator as example:

Key Value
l Kempten

Thx a lot.

Alexander

Filtering command line dir | get-acl | fl

$
0
0

Hi

I have been appointed a task to get all folder permission from my file server.

I ran the following:

dir | get-acl | fl

it indeed gives me what I need but too much of unwanted information such as sddl.

how can I exclude the sddl from the cli?




Powershell - Getting Target Path of Shortcut w/ Target having Spaces

$
0
0

Hi Guys,

    I'm trying to get the target path of a few thousand shortcuts.  I'm using the Get-ChildItem and looking at targetpath but its not showing the full target path on some of the shortcuts. For example, If I have a shortcut:

Shortcut#1:  "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe\\server77\directory$\powershellcodescript.ps1"

it will only return: "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"

and omits the "\\server77\directory$\powershellcodescript.ps1" part that is being passed to powershell.exe

Does anyone have any ideas or has anyone ran into this before?  I tried looking at other properties of Get-ChildItem and not making any progress.  It seems to not read the full shortcut.  Any help/guidance would be greatly appreciated.

-Bill

Passing credentials to Novell eDirectory via Powershell

$
0
0

I'm trying to connect to a Novell eDirectory instance using Windows Powershell.  My current code should work with OpenLDAP (I know it works with LDS, but haven't had a non-MS LDAP instance to connect to before this).

My code at current reads:

$conn = "LDAPS://192.168.1.51:636/o=cspglobal"

$ldapfilter = "(objectClass=user)"

$entry = New-Object System.DirectoryServices.DirectoryEntry($conn,"$username","$password")

$directorysearcher = New-Object System.DirectoryServices.DirectorySearcher($entry,$ldapfilter)

$results = $directorysearcher.FindAll()

However, I'm getting an error returned: "Unknown error: (0x80005000)".  I've read elsewhere this is probably an authentication error.  I've been told the credentials I was given were granted rights to eDirectory, but I haven't been able to confirm this in practice, and I'm told there are several firewalls between the machine from which I'm running the code and the server I'm attempting to contact.

Am I passing the credentials correctly to bind to eDirectory?  Is my code correct?


Powershell $foreach.Movenext()

$
0
0

Supose a CSV file:

UserCR

11234

25555

25556

25557

32222

32221

46666

Here's my code:

$FedList = Import-CSV "File.csv" -Delimiter "," | Sort-Object Utilisateur

ForEach ($User in $FedList){
$LastUser = $User.Utilisateur
If ($User.CR -ge 5000) {
Do {
$Liste += "<ul>$User.CR</ul>"
[Void] $foreach.MoveNext()
}
While ($LastUser -like $User.Utilisateur)

#send mail to $LastUser

}

I'm trying to send a email to all users having a CR over 5000. This mail contains all the assign's CR for that user.

Thx for your help

Powershell - AD TimeoutValues

$
0
0

Hi,

I am running into timeout issues when searching active directory for matching employee id. I’ve tried few different ways with no luck. I am basically trying to search through all AD account to verify if given employee ID is assigned to any user. If not I would proceed to next step. This check is in place to verify that two accounts are not created with same employeeID

Get-ADUser -Filter {employeeid -eq $empID}

Get-ADUser -ResultPageSize 100000 -Filter {employeeid -eq $empID}

Error: Get-ADUser : This operation returned because the timeout period expired

Is there any way to adjust the timeout value? This search lasts about 2min beofre displaying the timeout error.

Thanks,

 

 

 

 


How to remove remote access program from my pc

$
0
0

I am a victim of computer fraud.  I allowed someone who claimed he was from Micro Soft to access my pc. 

Now he is trying to extort 320.00 from me.  When I refused he threatened that I will never be

True to his word I have major problems operating my pc.  He has full control of MY Computer.

Viewing all 15028 articles
Browse latest View live


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