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

Comparing directories

$
0
0

I am trying to compare two directories and then copy file not in the destination from the source directory. Basically a manual sync. I am running into a problem.

A)  the Compare-Object wont work with variable and I can not figure out why

Here is the Code:

$SourceFiles ='C:\Test\Test1\'
$DestinationFiles = 'C:\Test\Test2\'
$Differences = Compare-Object (Get-ChildItem -Recurse $SourceFiles) (Get-ChildItem -Recurse $DestinationFiles)

Foreach ($File in $Differences)
{
    if ($File.SideIndicator -eq "<=")
    {
        echo "Copying $SourceFiles\$File!"
        Copy-Item "$SourceFiles\$File" -Destination "$DestinationFiles" -Recurse
    }
}

Any help would be great and before suggested, we can not use a third party application for security reasons.


Export Office 365 Mailbox

$
0
0

How to Export Office 365 Mailbox to .PST as an Admin?

Process I used:

1. Using powershell, establish a connection to the Microsoft Exchange Servers:

Import-Module MSOnline

$credential = get-credential$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $ocred -Authentication Basic -AllowRedirection

Import-PSSession $Session

2. Using powershell, grant access to the mailbox you wish to export:

Add-MailboxPermission -User {My Info} m -Identity {My Info} -AccessRights FullAccess -InheritanceType all

Mute speakers

$
0
0

I googled and found the following can mute speakers but it does not work. I ran it in Powershell ISE but it sent 173 in ISE. Any suggestions?

$obj = new-object -com wscript.shell
$obj.SendKeys([char]173)

The given path's format is not supported in powershell

$
0
0

Hi All,

I am getting 'The given path's format is not supported' in powershell scripting.Below is the code

Can anyone please help me in this:

if ($PropertiesFileConfiguration.SiebelServerENTLocalPath)
{
$SiebelServerENTLocalPath   = $PropertiesFileConfiguration.SiebelServerENTLocalPath
Write-Message $LogFileName "Srvrmgr remote local batch is $SiebelServerENTLocalPath"
}

where SiebelServerENTLocalPath is defined in an XML File as:

<SiebelServerENTLocalPath>E:\sba815</SiebelServerENTLocalPath>


my script doesn't work on Win Srv 2012

$
0
0

Hi guys,

thanks with your help I created a script that delete the files older than 14days and it works on my Win10 machine.

When I try to run in my PROD environment (Windows Server 2012) it doesn't work.

can you please help me to find a solution?

The script is here below.

function remove-files
{
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true)]
[ValidateScript({
if ((Test-Path "$_") -eq $true) { $true }
else { Throw "folder cannot be located" }
})]
[string]$FolderPath
)
$filesToBeDeleted = dir -Path "$FolderPath" | where { $_.LastWriteTime -lt ((Get-Date).AddDays(-14)) }
$remaingfiles = $filesToBeDeleted | select *, @{ n = 'DayofFile'; e = { $_.lastwritetime.toshortdatestring() } }
$groups = $remaingfiles | Group-Object dayoffile | where { $_.count -gt 1 }
if ($groups)
{
foreach ($group in $groups)
{
($group).group | sort lastwritetime -Descending | select -Skip 1 | Remove-Item -Force -Verbose -Confirm:$false >> copylog


}
}
}

Thanks everyone!

Mizter

Need Script to fectch task scheduler details

$
0
0

Hi, I got a task to change domain administrator password but before that we have to check the constraints so I got to know that our  team member has configured task scheduler by domain administrator password in many servers. So it is not easy to login and check each and every serve so I need a powershell scirpt to fetch the TASK SCHEDULER configuration so I get to know that by which account TASK SCHEDULER has configure.

Thanks

Kuldeep.

list primary users for machines listed in csv

$
0
0

Hi All,

I've been searching high and low for a way to use powershell to import a list of machines and output their primary users.

I have only been able to find the opposite - finding primary devices for list of users.

I'm quite new to Powershell and I understand the concepts, but I don't know the commands.

If anyone can help with this it will be greatly appreciated.

Thanks.

Get-ADDomainController : Directory object not found

$
0
0

Hi

While running below command, getting error message:

Command and error as well

PS C:\temp> $allDCs = (Get-ADForest).Domains | %{ Get-ADDomainController -Filter * -Server $_ }
Get-ADDomainController : Directory object not found
At line:1 char:39
+ $allDCs = (Get-ADForest).Domains | %{ Get-ADDomainController -Filter * -Server $ ...
+                                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (:) [Get-ADDomainController], ADIdentityNotFoundException
    + FullyQualifiedErrorId : Directory object not found,Microsoft.ActiveDirectory.Management.Commands.GetADDomainCont
   roller













How to Check whether the Domain user(s) is having the logon access to the given server(s) or not

$
0
0
Hi, Good day friends. iam new to powershell. still learning it. can you help me with the script for Checking whether the Domain user(s) is having the logon access to the given server(s) or not.

Strange behaviour of Powershell on one DC

$
0
0

Dear all,

Recently I've add new DC to infrastructure (in the same way like other DC's). Cause it is the closest DC for me very often I am using it to for Powershell with ADModule jobs to do.

What is strange: (Tested on Powershell with AD module run normally and as an administrator) I am logged to this particular DC which have problem.

Get-ADUser -Filter * -Properties gidNumber, uidNumber -SearchBase "Path" | ft gidNumber, uidNumber

I've got as result no value for these parameters. So I decrease scope of filter to only one user

Get-ADUser -Filter 'samAccountName -eq "username"' -Properties gidNumber, uidNumber -SearchBase "Path" | ft gidNumber, uidNumber

Still no result

Doing the same commands but with switch -server

Get-ADUser -Filter 'samAccountName -eq "username"' -server otherdc.domain.com -Properties gidNumber, uidNumber -SearchBase "Path" | ft gidNumber, uidNumber

I am getting results as I expect.

When I am login to other DC and do the first two commands I've got result as I expect.

Funny is that if I am going to this problematic DC and looking for this info via console Active Directory Users and Computer (connected do problematic dc) -> user -> attributeEditor I can see values which I am looking for :)

Other strange thing is that if I am connecting from other server with Powershell with AD Module and doing the command like before with switch to problematic server I got proper values.

I think it may be related somehow with UAC but it should not appear when I start PS as Admin.

Second strange thing on this DC is that sometime when I trying to do some Set-commands as return I got info about insufficient rights to perform this operation (I mean when I am doing it directly from machine) but If I will use switch -server otherdc.domain.com everything works :):)

ExecutivePolicy is set to Unrestricted.  Account which I am using is a domain Admin,

Do you have any idea of strange behaviour of Powershell on this DC? Maybe I forgot about something?

Thank you in advance,

BR,

Sebastian,

Powershell 4: Start-Transcript does not log Write-Host

$
0
0

Hi, 

After creating an instance of the latest Windows Server 2012 R2 image on Windows Azure, we see a strange issue with Powershell transcripts: Write-Host is not transcribed. However, "foobar" | Out-Host IS transcribed! Very strange. However, both Write-Warning, and any errors (exceptions, or write-error) does give output.

Anyone else seen this issue? Is this expected behavior or a bug?

Thanks a lot in advance! :-)

Sincerely,

Hallgeir

Here's my powershell version info:

PS C:\> $psversiontable

Name                           Value
----                           -----
PSVersion                      4.0
WSManStackVersion              3.0
SerializationVersion           1.1.0.1
CLRVersion                     4.0.30319.34014
BuildVersion                   6.3.9600.17400
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion      2.2

Example:

**********************
Windows PowerShell transcript start
Start time: 20150114143638
Username: xxx\xxx
RunAs User: xxx\xxx
Machine: xxx (Microsoft Windows NT 6.3.9600.0)
Host Application: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Process ID: 2160
**********************
Transcript started, output file is C:\foobar.txt

PS C:\> Write-Host "This is a test"

            CurrentMatchIndex              ReplacementIndex             ReplacementLength CompletionMatches
            -----------------              ----------------             ----------------- -----------------
                           -1                             0                            12 {System.Management.Automat...



PS C:\> Stop-Transcript
**********************
Windows PowerShell transcript end
End time: 20150114143658
**********************

Here's how it looks with piping to Out-Host:

**********************
Windows PowerShell transcript start
Start time: 20150114143755
Username: xxx\xxx
RunAs User: xxx\xxx
Machine: xxx (Microsoft Windows NT 6.3.9600.0)
Host Application: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Process ID: 2160
**********************
Transcript started, output file is C:\foobar.txt

            CurrentMatchIndex              ReplacementIndex             ReplacementLength CompletionMatches
            -----------------              ----------------             ----------------- -----------------
                           -1                            19                             8 {System.Management.Automat...



PS C:\> "This is a test" | Out-Host
This is a test

            CurrentMatchIndex              ReplacementIndex             ReplacementLength CompletionMatches
            -----------------              ----------------             ----------------- -----------------
                           -1                             0                             9 {System.Management.Automat...



PS C:\> Stop-Transcript
**********************
Windows PowerShell transcript end
End time: 20150114143809
**********************


Get-mailbox all users except those in csv list

$
0
0

Hello, please someone help.

I have a LIST.CSV of users want exclude.

_________________________________

;SimpleDisplayName;
;user1;
;user2;
;user3;

_________________________________

Need something like:

$exclude = get-content LIST.CSV

$users = Get-mailbox -Filter {(RecipientTypeDetails -eq 'UserMailbox') -and (SimpleDisplayName -notlike '$exclude')}

Thanks in advance

How to upload file from local drive to FTP site?

$
0
0

I tried using WinSCP tool for uploading data from local drive to FTP site.  It works fine but when I use the Windows FTP commands, I get Access Denied error 550.  I tried changing ownership, permission on the folder and c drive and also turned off firewall inbound and outbound. No luck!  I created a batch file and I trying to call this batch program from Oracle External Job Scheduler.  Any help would be appreciated. 

ftp> put functional.txt
200 PORT command successful.
550 functional.txt: Access is denied.
ftp>

Isssue with C# Class

$
0
0

HI,

I've a C# class (work on C# solution), I try to include the class on Powershell but, I've an exception when I try to execute.

Any idea !

$codetest = @"
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;

namespace PrinterColor
{
    public class Settings
    {
        #region "Private Variables"
        private IntPtr hPrinter = new System.IntPtr();
        private PRINTER_DEFAULTS PrinterValues = new PRINTER_DEFAULTS();
        private PRINTER_INFO_2 pinfo = new PRINTER_INFO_2();
        private DEVMODE dm;
        private IntPtr ptrDM;
        private IntPtr ptrPrinterInfo;
        private int sizeOfDevMode = 0;
        private int lastError;
        private int nBytesNeeded;
        private long nRet;
        private int intError;
        private System.Int32 nJunk;
        private IntPtr yDevModeData;
        #endregion

        #region "Win API Def"
        [DllImport("kernel32.dll", EntryPoint = "GetLastError", SetLastError = false,
        ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        private static extern Int32 GetLastError();
        [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true,
        ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        private static extern bool ClosePrinter(IntPtr hPrinter);
        [DllImport("winspool.Drv", EntryPoint = "DocumentPropertiesA", SetLastError = true,
        ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        private static extern int DocumentProperties(IntPtr hwnd, IntPtr hPrinter,
        [MarshalAs(UnmanagedType.LPStr)] string pDeviceNameg,
        IntPtr pDevModeOutput, ref IntPtr pDevModeInput, int fMode);
        [DllImport("winspool.Drv", EntryPoint = "GetPrinterA", SetLastError = true,
            CharSet = CharSet.Ansi, ExactSpelling = true,
            CallingConvention = CallingConvention.StdCall)]
        private static extern bool GetPrinter(IntPtr hPrinter, Int32 dwLevel,
        IntPtr pPrinter, Int32 dwBuf, out Int32 dwNeeded);
        [DllImport("winspool.Drv", EntryPoint = "OpenPrinterA",
            SetLastError = true, CharSet = CharSet.Ansi,
            ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        private static extern bool
            OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter,
            out IntPtr hPrinter, ref PRINTER_DEFAULTS pd);
        [DllImport("winspool.drv", CharSet = CharSet.Ansi, SetLastError = true)]
        private static extern bool SetPrinter(IntPtr hPrinter, int Level, IntPtr
        pPrinter, int Command);
        #endregion

        #region "Data structure"
        public enum PageColor
        {
            COLOR = 2,
            MONOCHROME = 1
        }
        public struct PrinterData
        {
            public PageColor Color;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct PRINTER_DEFAULTS
        {
            public int pDatatype;
            public int pDevMode;
            public int DesiredAccess;
        }
        [StructLayout(LayoutKind.Sequential)]
        private struct PRINTER_INFO_2
        {
            [MarshalAs(UnmanagedType.LPStr)]
            public string pServerName;
            [MarshalAs(UnmanagedType.LPStr)]
            public string pPrinterName;
            [MarshalAs(UnmanagedType.LPStr)]
            public string pShareName;
            [MarshalAs(UnmanagedType.LPStr)]
            public string pPortName;
            [MarshalAs(UnmanagedType.LPStr)]
            public string pDriverName;
            [MarshalAs(UnmanagedType.LPStr)]
            public string pComment;
            [MarshalAs(UnmanagedType.LPStr)]
            public string pLocation;
            public IntPtr pDevMode;
            [MarshalAs(UnmanagedType.LPStr)]
            public string pSepFile;
            [MarshalAs(UnmanagedType.LPStr)]
            public string pPrintProcessor;
            [MarshalAs(UnmanagedType.LPStr)]
            public string pDatatype;
            [MarshalAs(UnmanagedType.LPStr)]
            public string pParameters;
            public IntPtr pSecurityDescriptor;
            public Int32 Attributes;
            public Int32 Priority;
            public Int32 DefaultPriority;
            public Int32 StartTime;
            public Int32 UntilTime;
            public Int32 Status;
            public Int32 cJobs;
            public Int32 AveragePPM;
        }
        private const short CCDEVICENAME = 32;
        private const short CCFORMNAME = 32;
        [StructLayout(LayoutKind.Sequential)]
        public struct DEVMODE
        {
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCDEVICENAME)]
            public string dmDeviceName;
            public short dmSpecVersion;
            public short dmDriverVersion;
            public short dmSize;
            public short dmDriverExtra;
            public int dmFields;
            public short dmOrientation;
            public short dmPaperSize;
            public short dmPaperLength;
            public short dmPaperWidth;
            public short dmScale;
            public short dmCopies;
            public short dmDefaultSource;
            public short dmPrintQuality;
            public short dmColor;
            public short dmDuplex;
            public short dmYResolution;
            public short dmTTOption;
            public short dmCollate;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCFORMNAME)]
            public string dmFormName;
            public short dmUnusedPadding;
            public short dmBitsPerPel;
            public int dmPelsWidth;
            public int dmPelsHeight;
            public int dmDisplayFlags;
            public int dmDisplayFrequency;
        }
        #endregion

        #region "Constants"
        private const int DM_DUPLEX = 0x1000;
        private const int DM_IN_BUFFER = 8;
        private const int DM_OUT_BUFFER = 2;
        private const int PRINTER_ACCESS_ADMINISTER = 0x4;
        private const int PRINTER_ACCESS_USE = 0x8;
        private const int STANDARD_RIGHTS_REQUIRED = 0xF0000;
        private const int PRINTER_ALL_ACCESS =
            (STANDARD_RIGHTS_REQUIRED | PRINTER_ACCESS_ADMINISTER
            | PRINTER_ACCESS_USE);
        #endregion

        #region "Function to change printer settings"
        public bool ChangePrinterSetting(string PrinterName, PrinterData PS)
        {
            dm = this.GetPrinterSettings(PrinterName);
            dm.dmColor = (short)1;
            Marshal.StructureToPtr(dm, yDevModeData, true);
            pinfo.pDevMode = yDevModeData;
            pinfo.pSecurityDescriptor = IntPtr.Zero;
            Marshal.StructureToPtr(pinfo, ptrPrinterInfo, false);
            lastError = Marshal.GetLastWin32Error();
            nRet = Convert.ToInt16(SetPrinter(hPrinter, 2, ptrPrinterInfo, 0));
            if (nRet == 0)
            {
                lastError = Marshal.GetLastWin32Error();
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            if (hPrinter != IntPtr.Zero)
                ClosePrinter(hPrinter);
            return Convert.ToBoolean(nRet);
        }
        private DEVMODE GetPrinterSettings(string PrinterName)
        {
            DEVMODE dm;
            const int PRINTER_ACCESS_ADMINISTER = 0x4;
            const int PRINTER_ACCESS_USE = 0x8;
            const int PRINTER_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED |
                       PRINTER_ACCESS_ADMINISTER | PRINTER_ACCESS_USE);
            PrinterValues.pDatatype = 0;
            PrinterValues.pDevMode = 0;
            PrinterValues.DesiredAccess = PRINTER_ALL_ACCESS;
            nRet = Convert.ToInt32(OpenPrinter(PrinterName,
                           out hPrinter, ref PrinterValues));
            if (nRet == 0)
            {
                lastError = Marshal.GetLastWin32Error();
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            GetPrinter(hPrinter, 2, IntPtr.Zero, 0, out nBytesNeeded);
            if (nBytesNeeded <= 0)
            {
                throw new System.Exception("Unable to allocate memory");
            }
            else
            {
                ptrPrinterInfo = Marshal.AllocHGlobal(nBytesNeeded);
                nRet = Convert.ToInt32(GetPrinter(hPrinter, 2,
                    ptrPrinterInfo, nBytesNeeded, out nJunk));
                if (nRet == 0)
                {
                    lastError = Marshal.GetLastWin32Error();
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
                pinfo = (PRINTER_INFO_2)Marshal.PtrToStructure(ptrPrinterInfo,
                                                      typeof(PRINTER_INFO_2));
                IntPtr Temp = new IntPtr();
                if (pinfo.pDevMode == IntPtr.Zero)
                {
                    IntPtr ptrZero = IntPtr.Zero;
                    sizeOfDevMode = DocumentProperties(IntPtr.Zero, hPrinter,
                                       PrinterName, ptrZero, ref ptrZero, 0);


                    ptrDM = Marshal.AllocCoTaskMem(sizeOfDevMode);

                    int i;
                    i = DocumentProperties(IntPtr.Zero, hPrinter, PrinterName, ptrDM,
                    ref ptrZero, DM_OUT_BUFFER);
                    if ((i < 0) || (ptrDM == IntPtr.Zero))
                    {
                        throw new System.Exception("Cannot get DEVMODE data");
                    }
                    pinfo.pDevMode = ptrDM;
                }
                intError = DocumentProperties(IntPtr.Zero, hPrinter,
                          PrinterName, IntPtr.Zero, ref Temp, 0);
                yDevModeData = Marshal.AllocHGlobal(intError);
                intError = DocumentProperties(IntPtr.Zero, hPrinter,
                         PrinterName, yDevModeData, ref Temp, 2);
                dm = (DEVMODE)Marshal.PtrToStructure(yDevModeData, typeof(DEVMODE));
                if ((nRet == 0) || (hPrinter == IntPtr.Zero))
                {
                    lastError = Marshal.GetLastWin32Error();
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
                return dm;
            }
        }
        #endregion
    }
}"@

Add-Type -TypeDefinition $codetest
$data = New-Object -TypeName PrinterColor.Settings+PrinterData
$data.Color = [PrinterColor.Settings+PageColor]::MONOCHROME
$set = New-Object -TypeName PrinterColor.Settings
$set.ChangePrinterSetting("TEST",$data)

Help with Output to CSV

$
0
0

I am writing a script that will search each OU for users with the 'Password Never Expires' attribute and then export those users into a CSV with the OU name. Unfortunately, my current script creates CSVs with the FQDN of the OU ("OU=sales,ou=OrgUsers,DC=AD,DC=ORG") and I just want the OU name (sales.csv).
Any help would be appreciated.
------------------------
$SB="ou=OrgUsers,DC=AD,DC=ORG"
$prop = @("name","samaccountname","userprincipalname","employeeid","department","emailaddress","lastlogondate","passwordlastset","distinguishedname","enabled")
$oulist=get-adorganizationalunit -SearchBase "ou=OrgUsers,DC=AD,DC=ORG" -searchscope OneLevel -properties distinguishedname  -filter {distinguishedname -like "*"}
foreach ($ou in $oulist) {get-aduser -searchbase $ou -filter {passwordneverexpires  -eq $true} -properties $prop|select-object $prop|export-csv C:\scripts\pwne\$ou.csv -NoTypeInformation}
--------------------------
I have also tried
$oulist=get-adorganizationalunit -SearchBase "ou=OrgUsers,DC=AD,DC=ORG" -searchscope OneLevel -properties distinguishedname  -filter {distinguishedname -like "*"}|select-object name but that just produces all error text:
foreach ($ou in $oulist) {get-aduser -searchbase $ou -filter {passwordneverexpir ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-ADUser], ArgumentException
    + FullyQualifiedErrorId : The supplied distinguishedName must belong to one of the following partition(s):dc=ad,dc=org, cn=configuration,dc=ad,dc=org....

Thanks, Robert


Run a powershell script that is in a remote server

$
0
0

I am trying to run a powershell script that is in a remote server. Can anyone please help?

*note: I am NOT trying to run a local ps script on a remote server.

Thank you.

Compare 2 CSVs and Export Merged Results

$
0
0

Hi All

I am trying to move a large group of FTP User Accounts to new Sub OUs based on the names of the objects. for example anything named CIS_<name> will be moved from GENERAL OU to GENERAL OU > CIS. However I have 2 CSV files which I need to merge together and then export to a csv and then I can run the powershell command. I have made a start but I am stuck. Here are the 2 CSV's

CSV 1 contains SamAccountName, Description and NewPath (NewPath is the new OU Location)

CSV 2 contains SamAccountName and DistinguishedName

Merge 2 CSVs together matching the SamAccountName and then add the rest of the data to the correct rows.

Desire Result CSV =  SamAccountName, DistinguishedName, Description, NewPath

What I have so far (it is not complete yet)

$ftpuserscsv = import-csv C:\ps\import\ftpusers.csv
$ftpdncsv = import-csv C:\ps\import\ftpdn.csv
Compare-Object $ftpuserscsv $ftpdncsv -property samaccountname -IncludeEqual | select * | Export-csv C:\ps\exports\ftp_complete.csv –NoTypeInformation
$csv = import-csv C:\ps\exports\ftp_complete.csv
foreach ($row in $csv){
Move-ADObject $row.distinguishedName -TargetPath $row.NewPath
Please Help!




Time Stamps for AD users

$
0
0

Hi Guys,

A total newbie at PS but seeking help with running a script to find the following :-

a) Search AD and find last logon time stamp

b) Filter by anything older than 90 days

c) output to a CSV with the following format : Samaccount, name, stamp & location

Good news, all works fine except the location field is blank.  Tried OU, Country but returns with blank value :(   Please see script below :-

# Gets time stamps for all User in the domain that have NOT logged in since after specified date
import-module activedirectory 
$domain = "OU=CT,OU=EMA,OU=IA,DC=emrsn,DC=org" 
$DaysInactive = 90 
$time = (Get-Date).Adddays(-($DaysInactive))
 
# Get all AD User with lastLogonTimestamp less than our time and set to enable
Get-ADUser -Filter {LastLogonTimeStamp -lt $time -and enabled -eq $true} -searchbase $domain -Properties LastLogonTimeStamp |
 
# Output Name and lastLogonTimestamp into CSV
select-object samaccountname,Name,@{Name="Stamp"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp)}}  | export-csv c:\temp\OLD_User.csv -notypeinformation

Any help will be much appreciated, I'd love to see the location for the useraccount so I can contact the relevant site rather than seeing a long list of names and timestamps.

Kind regards

Kid

Active Directory power shell command to get ALL domain controller computer details

$
0
0

Hi,

how to get all computer details with below attributes:

OU name

user name

last logon

use powershell script to signal a file's age has exceeded 12 hours

$
0
0
hi, i'm new to powershell, how would you use powershell to monitor a directory on a server and write an event to event log whenever there's a file in that directory exceeds 12 hours in age?
Viewing all 21975 articles
Browse latest View live


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