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

Trying to find a powershell script which tells me the last time a user logged into active directory.

$
0
0

Hi,

I'm new to powershell.  I'm trying to find a powershell script which tells me the last time a user logged into active directory.  Everything I find on-line gives me errors.  This is probably because I'm using the wrong syntax when trying to apply to my domain environment.   If there is an easier way to run a command like this using adfind that would be good to.  We are tryin to determine a good way to handle stale Active Directory captive and service accounts so we can disable them. 

Thanks,

Kevin C. 


help with looking for more then than 1 eventID

$
0
0

Hi

i have a test server 2012 r2 set up with auditing enabled for the deletion of any files or folders, set up in the local policy and on the folder

i have a powershell script that will trigger in task scheduler on event ID 4660 (object deleted)

script is:-

$pcName = "GHSVR2012"
$Event = Get-Eventlog -log security | where {$_.eventID -eq 4663} | Sort-Object index -Descending | Select-Object -First 1
$User = $Event.ReplacementStrings[1]
$Domain = $Event.ReplacementStrings[2]
$File = $Event.ReplacementStrings[6]
$MailSubject = "A File has been deleted in the G Drive:"
$MailBody = "The account Name is :- " + $Domain + "\" + $User + "`r`n" + "The flie deleted was from :" + $File + "`r`n" + "Time: " + $Event.TimeGenerated
$SmtpClient = New-Object system.net.mail.smtpClient
$SmtpClient.host ="smtp.xxxxxxxxxxxxxx"
$MailMessage = New-Object system.net.mail.mailmessage
$MailMessage.from ="xxxxxxxxxxxxxxxxxx"
$MailMessage.To.add("xxxxxxxxxxxxxxxx
$MailMessage.IsBodyHtml = 0
$MailMessage.Subject = $MailSubject
$MailMessage.Body = $MailBody
$SmtpClient.Send($MailMessage)


I have everything working apart from one thing:-

if I delete, say 5 files at the same time, called, file 1, file 2, file 3, file 4, file 5,

the eventlog ID triggers the script to be sent and it will send 5 emails but wont name each file that has been deleted instead it will just give the first file it finds

e.g the email i receive look like the below and this comes through 5 times:-
The account Name is :- Domain\User1
The file deleted was from :C:\Users\User1\Documents\file 1
Time: 11/17/2014 11:49:35

any advice grateful

Gavin

Trying to set ADAccountExpiration using extensionAttribute

$
0
0

I have been trying to get this script to work and I am so close, but I just cant get the last section of the pipe to work!

We have our HR IS system assign the account expiry date as "2014-12-24" (no quotes) to AD extensionAttribute4.  I have my Powershell command setup to pull all the users in an OU, check to see if the attribute matches the set expiry date, and set the date if they do not match.  I just can't get the command to work with the information in the attribute field.

Command

Get-ADUser -Filter * -SearchBase "OU=Contractors,DC=corp,DC=com" -Property AccountExpirationDate,extensionAttribute4 | where {$_.AccountExpirationDate -ne (get-date $_.extensionAttribute4)} | Set-ADAccountExpiration -DateTime (get-date extensionAttribute4)

Error

Get-Date : Cannot bind parameter 'Date'. Cannot convert value "extensionAttribute4" to type "System.DateTime". Error: "The string was not recognized as a valid DateTime. There is a unknown word starting at index 0."

Any help would greatly be appreciated!

Thanks,

Stuck

ldap for one AD field

$
0
0

need to be able to query AD for one field that might be populated.

using Aduc &(objectClass=user)(objectCategory=person), what would I add to the end of this?

thanks

windows powershell

$
0
0

Dear Team,

I am fetching user information from domain with below command.

Get-ADUser -Filter * -SearchBase "DC=xyz,DC=com" -Properties * | select sAMAccountName,homeDirectory,homeDrive ,physicalDeliveryOfficeName,userAccountControl,displayName,l,mail | export-csv 0411.csv

but i want one more properties (Remote desktop profile tab) which i am not able to fetch up from above command and merge .

Get-ADUser -Filter * -SearchBase 'OU=User Group,DC=domain,DC=com' | ForEach {
    $userInfo = [ADSI]"LDAP://$($_.distinguishedName)"
    $userInfo.TerminalServicesProfilePath
}

......................................................................

Conclusion is Client want consolidated report :(.

Kindly Help...

Open a Word-Doc with activated Line-Numbers

$
0
0

Dear scripting-experts,

I want to print code with Powershell (PHP etc.) including line-numbers. The idea is to rename .php to .txt and print it with Office/Word. That works fine, but how can I open the Word-file so that line-numbers are automatically activated?  I know how to format things like this:

$WordObj.ActiveDocument.Content.Font.Size = 12
$WordObj.ActiveDocument.Content.Font.Name = "Verdana"

What would be a line for activated line-numbers?

Btw.:

What would be the code to add the full document-path in the header of the document?

What would be the code to add the content of a variable (used in powershell) to the document-header?

Goal is to print the working-results from a student-class.

:-)

Cheers,

Homer






Get-Help command not showing all the details

$
0
0

When I open the Exchange Management Shell on my laptop and do any command like the following:

help get-mailbox -detailed

I just get the following result:

SYNTAX

DESCRIPTION


PARAMETERS
    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer and OutVariable. For more information, see
        about_CommonParameters (link of some kind).

REMARKS
    To see the examples, type: "get-help  -examples".
    For more information, type: "get-help  -detailed".
    For technical information, type: "get-help  -full".

If I do the same commands from any of my Exchange servers, I get the full details.  I've done this command for years and this is the first time I'm seeing no details.  Any help would be appreciated.

Thanks,

Andrew

Calling a Powershell script with multi params from ASP.NET using Process.Start()

$
0
0

Hi, 

I've been trying to call a Powershell script with multi params from an ASP.NET file in the following way.

Process.Start(@"C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Powershell.exe", @"-File ""E:\\Testman.ps1"" ""'MAC1','MAC2'"" ""4.0"" ""xxx.xxx.xxx.xx""");

(Please note that here I have two inputs for the macList)

But while running, this is taking MAC1,MAC2 as a single param only. Here's the parameter list of Testman.ps1:

Param
(
[Parameter(Mandatory=$True,Position=1)]
[String[]]$macList,
[Parameter(Mandatory=$True,Position=3)]
[String[]]$version,
[Parameter(Mandatory=$True,Position=4)]
[String]$server
)

Please help me fixing this issue.

Thanks in advance,

/Aravind


How to retreive the IP Address of a terminal server connected user?

$
0
0

Hey everyone,
I have been tasked with configuring a script for users logging into a terminal server from thin clients and identifying their location and mapping specific printers specific to their locations. The problem is there are no real easy ways to uniquely identify the thin clients where it is easier to be able to identify users logging onto a server using a Windows workstation.

I was thinking if I could write a VBS script that executes at logon for users and identifies the IP address of the users session I could find a way to perhaps map a set of printers based on the third octet retrieved from the users session IP to the terminal server.

Anyone have any ideas on how to do this? I already came across this:
http://www.activexperts.com/activmonitor/windowsmanagement/scripts/terminalservices/retrieving/

Which has lots of cool useful stuff. But nothing I can find about retrieving the actual connected users IP addresses on the terminal server. You would think this would be useful for logging source addresses etc. If I can determine a device is connected from a particular subnet I could create a case selection scenario where I map a certain set of printers.

Thanks in advance! I'll keep hunting myself as well.

FTP process getting stuck, how to set a connection timeout in VBScript or FTP command-file?

$
0
0

I am running the below command from VB Script

Set objShell = WScript.CreateObject("WScript.Shell")
NTCommand = "%COMSPEC% /C ftp -n -s:CommandFile

objShell.Run(NTCommand, 1, TRUE)

The CommandFile is a .FTP file which contains complete set of FTP command i.e. as below:

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

open <IP address>
user <username>

Password <password>

cd <input folder>

ls *.*

bye

-----------

The problem is this FTP process (objShell.Run command) gets stuck when there is some temporarary issue with FTP server. The control never reaches the next line of code after objShell.Run if that is the case.

How can I handle this in FTP commandfile or my VBScript? Can I set connection time out here?


Powershell Array Export Issues

$
0
0

Hey everyone! So I might just be going about this the wrong way but here's my issue. The script functions as I need it to however, when I export the values to my .csv, the columns are in the wrong order than the way I think they should be. Here's what I've got:

$list = Get-content targets.txt
Foreach($_ in $list) {
    $SAM = Get-RegValue -ComputerName $_ -Key Software\Microsoft\Windows\CurrentVersion\Authentication\LogonUI -Value LastLoggedOnSAMUser
    $User = Get-RegValue -ComputerName $_ -Key Software\Microsoft\Windows\CurrentVersion\Authentication\LogonUI -Value LastLoggedOnUser
        @('Name','LastUserAccessed','LastUserLoggedOn')
        New-Object PSObject -Property @{
            Name = ($SAM).ComputerName
            LastUserAccessed = ($User).Data
            LastUserLoggedOn = ($SAM).Data
        } | Export-csv Results.csv -notypeinformation -append}

I would like it to read Name, LastUserAccessed, and LastUserLoggedOn but it comes out to be LastUserAccessed, Name, LastUserLoggedOn. Any ideas as to why this is happening? Thanks in advance!

Get-ChildItem with -LiteralPath is throwing "The specified wildcard character pattern is not valid" when filenames contain brackets

$
0
0

I'm trying to get a list of folders in a hierarchy that don't contain any mp3 files. (The goal here is to eventually clean up all the "empty" folders that only have album art, thumbs.db, desktop.ini, etc. files left). So I wrote a quick PowerShell command to try to do this. But it doesn't seem to be working.

I already checked out this thread <Get-ChildItem SomeFile[].txt occurs error because of the [brackets]: "specified wildcard pattern not valid"> and I think I'm using LiteralPath correctly. Any other hints for troubleshooting this problem? Here's the command I'm using.

Get-ChildItem -Recurse -Directory | ?{
	@( @(Get-ChildItem -LiteralPath $_.FullName -Recurse) | ?{
		$_.Extension -eq ".mp3"}).Count -eq 0 }

This is on the latest version of PowerShell found in Windows Technical Preview.


Change the IP address of existing printer port.

$
0
0

We have been given a task of changing the IP Addresses of our Network Printers (Actual Printer), which luckily will be carried out by our Local HP LaserJet Partner Technicians all 80 Printers on all sites.

While my team is assigned to changes all configured Shared Printer IP Address.

We are talking about the one recorded/configured under Printer Properties--->under "Ports" Section, Printer IP Address Setting) on all workstation which I believed time consuming and manpower entensive task.

1 Computer at least 4 Network Printers are configured.

We are planning to deploy a script via SCCM 2012 however I am not lucky to find a working script.

We are targeting Windows XP, Windows 7, and Windows 8 OS Versions.

I came to browse some details on the forums but it works on XP, however I tried on Windows 7 it didn't work at all:

https://social.technet.microsoft.com/Forums/scriptcenter/en-US/65487281-a8e0-485a-8ffe-1341d2e0b2f0/change-the-ip-address-of-existing-printer-port?forum=ITCG

I just follow the script on the above forum by Bartek Bielawski: However I cant figure out what went wrong.

Scriptsample.bat

set IPToReplace=192.168.1.150
set NewIP=192.168.1.100 @echo off for/f "delims="%%I in ('reg query "HKLM\System\CurrentControlSet\Control\Print\Monitors\Standard TCP/IP Port\Ports"')do @call :CheckIP %%I
goto :EOF

 :CheckIP
:: Need to replace "HKEY_LOCAL_MACHINE" with"HKLM"
set KEY=%*
set KEY=HKLM%KEY:~18%
reg query "%KEY%" /v IPAddress 2> nul | find "%IPToReplace%"> nul || goto :EOF
:: Found printer ports with given IP
reg add "%KEY%" /v IPAddress /t REG_SZ /d %NEWIP%/f

Output

1. The Registry Entry has been changes from 192.168.1.150 to 192.168.1.100 successfully check in the Registry.

2. System/Computer Has been restarted, check on the Registryonce again (for the Shared Printer "PORTS" IP Address settings) the IP is 192.168.1.100 still in the registry which is good.

3. Check the "HP ColorLaserjet" Printer Propertieswith the previous IP Address of 192.168.1.150, on the "Port" the previous IP Address which is 192.168.1.150 still there however "Unchecked", the new IP Address 192.168.1.100 did not register.

Any help and suggestions? Maybe the above script needs few commands modification. Or maybe I need a deferent type of Script kindly share.


What could be DOS version of this linux command?

$
0
0

HI...

I want to store occurrence of a string in a temporary variable.

In short , What could be the DOS version of following linux scripting.

n=`grep -wc ${string} ${File}`

Here we can use find command in DOS.

But We want to store only a number in variable "n".

We know find /c returns the number of occurrence with a string, but we want only a number.

Copy and rename files if exist

$
0
0

Hi folks,

Let me explain the situation. FolderA and FolderB had identical data (the same files and folders structure) in them as they were in sync before. The sync between them has been broken and there is no way of knowing what got changed in FolderA and FolderB.

Now I want to get rid of FolderB. Before that I need a script that will copy data from FolderB to FolderA. However, it should not overwrite existing files/folders. If there is an exact same file name, but different modified date, then the script should append date modified to the file name that is being copied from FolderB. The script should do the same in all sub-folders and files.

Any kind of script is appreciated. Thank you for your help.




Blocking particular applications in Windows

$
0
0

I want to ask is there any script or command to block particluar applications asked from user from running.

(I know about parental controls but I want to know about script).

Manager field Active Directory

$
0
0

I'm working on a PS script to make it easier to create Active Directory users included some attributes. For now I need to process the "Manager" field. We have 4 departments, 4 managers. I want to create this like "if department = one of the 4 departments then give 1 of the 4 departmentmanagers".

How can I process this?

Import-Module activedirectory

#Store the data from ADUsers.csv in the $ADUsers variable
$ADUsers = Import-csv "c:\temp\scripts\ADUsers.csv"

#Loop through each row containing user details in the CSV file
foreach ($User in $ADUsers)
{
    #Read user data from each field in each row and assign the data to a variable as below

    $Firstname  = $User.firstname
    $Lastname   = $User.lastname
    $Username   = $User.username
    $Password   = $User.password
    $OU         = $User.ou #This field refers to the OU the user account is to be created in
    $userprincipalname = $user.userprincipalname
    $displayname = $user.displayname
    $title = $user.jobtitle
    $department = $user.department

    #Check to see if the user already exists in AD
    if (Get-ADUser -F {SamAccountName -eq $Username})
    {
         #If user does exist, give a warning
         Write-Warning "A user account with username $Username already exist in Active Directory."
    }
    else
    {
        Write-host
        #User does not exist then proceed to create the new user account
        #Account will be created in the OU provided by the $OU variable read from the CSV file
    New-ADUser -Name $displayname -SamAccountName $Username -UserPrincipalName $userprincipalname  -GivenName $Firstname -Surname $Lastname -Enabled $True -DisplayName $displayname -AccountPassword (convertto-securestring $Password -AsPlainText -Force)
    }
} #end function


Pshell Script in SCCM pkg needs to write to all users Favorites Bar folder in IE10.

$
0
0

Hello All -

I have a need in my company to place a new Internet shortcut on the Favorites Bar(IE10) of every known profile in our Windows 7 environment via a SCCM 2012 pkg.

I've been thinking of the best way to do this...MSI, .bat file etc, but it seems best that Powershell would be the more efficient solution. I've read of the limitations of trying to populate any users Favorites Bar via GPO(can't use this route) and MSI's, but surely powershell can get me over this hurdle.

I think i'm close in using the Registry's profileList contents and throwing them into a variable, but not sure how to "page thru each" and place this link within each users favorites bar. This will need to be performed once the PC is logged out.

Any ideas?
TIA

$PracticeGroup=Get-childitem-path"C:\JLtools\utilities\Practice Areas home page.website"

$profileList='HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList'|

Get-ItemProperty|

Where-Object{$_.profileImagePath}|

Select-Object-propertyprofileImagePath

foreach($ProfileNamein$profileList) {

Copy-Item$PracticeGroup-Destination"$ProfileList\Favorites\Links"-Verbose-Recurse


            }

Anyway for me to use powershell/vba script to find if public folder sharing is enabled?

$
0
0

Is there a way I can run a powershell command to find out if this value is enable or disable? I don't want to change it. I just want to know the value of it for each computer. Bottom pic is the value i want to find. Thanks. 

Powershell system.Net.Mail.MailMessage Question

$
0
0

When I pass a custom object:

PS C:\Users\v-widekr\Documents\Powershell> $var1
From    : v-widekr@xxx.com
cc      : v-widekr@xxx.com
subject : Type Subject Here
body    : <html><body><H1> <center>enter HTML here</center></H1>
to      : {v-widekr@xxx.com, v-widekr@xxx.com}

To my send-Email function:

Function Send-Email($Mailobject){
 $Message = New-Object system.Net.Mail.MailMessage
 $From    = New-Object system.net.Mail.MailAddress $Mailobject.From 

 if ($Mailobject.To){
  $Mailobject.To | foreach{
   $To = new-object system.net.Mail.Mailaddress $_; $Message.To.Add($To)
  }
 }
 if ($Mailobject.cc){
  $Mailobject.cc | foreach{
   $cc = New-Object system.Net.Mail.Mailaddress $_; $Message.cc.Add($cc)
  }
 }
 if ($Mailobject.Subject){$Message.Subject = $Mailobject.Subject}
 if ($Mailobject.Body){$Message.IsBodyHtml = $True
        $Message.Body = $Mailobject.body}
$Message | get-member
 $Server = "smtphost.redmond.corp.microsoft.com" 
 $Client = New-Object system.Net.Mail.SmtpClient $server 
 $Client.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
 Out-LogEntry $message #Log results to text file
 $Client.Send($message);
}

I get error:

Exception calling "Send" with "1" argument(s): "A from address must be specified."
At C:\Users\v-widekr\Documents\Powershell\FunctionLibraryWinfred.ps1:175 char:14
+     $Client.Send <<<< ($message);
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

If I change the line first two lines to:

 $From    = New-Object system.net.Mail.MailAddress $Mailobject.From 
 $To      = new-object system.net.mail.Mailaddress $Mailobject.To
 $Message = New-Object system.Net.Mail.MailMessage $From, $To

It works, but the To is populated with three addresses not two (because I attach it once when creating the object and then twice with the add function).

Why can't I create with New-Object system.Net.Mail.MailMessage and then attach a Mailaddress  with To.Add?

Thanks,

Winfred

Viewing all 15028 articles
Browse latest View live


Latest Images

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