How to reformat date from Get-ADComputer output - windows

Using a PowerShell script, how do I reformat the output from "Get-ADComputer -Filter * -Properties Created | FT Name,Created" and then write to reformated output to the computer description in AD.
the current output looks like this below
Name Created
---- -------
LAPTOP12 30/06/2011 10:22:52 AM
LAPTOP03 18/01/2016 3:47:06 PM
LAPTOP01 12/07/2011 11:04:29 AM
LAPTOP11 30/10/2015 8:27:00 AM
PC06 11/07/2011 2:03:17 PM
The format I am looking to create is
computername Provisioned ddMMyyyy
Then write this revised output of "Provisioned ddMMyyy" to the computer description in AD

Get-ADComputer -Filter * -Properties Created | foreach-object { Set-ADComputer $_ -Description "Provisioned $($_.Created.ToString("ddMMyy"))" }
No need for ft Name,Created here because ft is for a human-readable output
Use the | (pipe) character to send the results of Get-ADComputer to the next command
Use foreach-object on the piped output to iterate through each item from the Get-ADComputer output
Use Set-ADComputer with the -Description parameter to update the AD description
Use the .ToString method to reformat the $_.Created value to your desired format

Related

How to write a Powershell Script with a For-loop using a List of Users to Print Out Active Directory Information

So I have a list of users that I need to verify using the RSAT Tools and GetAD-User module within Powershell. As a result, I have determined that the following command will pull out user information, and I am passing another file off for users needing verification. The following command will work and give me user information and see if an email exists:
Get-ADUser -filter * -properties EmailAddress -SearchBase 'DC=xxx-xxxx,DC=xxx,DC=xx,DC=us'| select-object Name, EmailAddress | select-string 'doe,john'
I therefore tried a loop using the following:
cat .\PD.txt | ForEach-Object {Get-ADUser -filter * -properties EmailAddress -SearchBase 'DC=xx-xxxx,DC=xxx,DC=xx,DC=us'| select-object Name, EmailAddress | select-string '$_'}
**I have omitted some of the DC infor in terms of the AD names for security reasons.
Inside PD.txt, I would have something like a text files with usernames in Lastname, Firstname per line.
However, nothing prints back in terms of the information. If I did it without the "$_" and the forEach-Object command it would work, but nothing is printing back. Is my forloop wrong?
I tried it a different way and it still didn't work using the apostrphes for the string to pass a different way, by writing it into the users.txt file called Real.txt. While, I can forloop through it, it doesn't work, when I put in the GetAD-User command.
However, I think my for-loop might have something wrong not sure what it is though.
PS C:\Users\richard.barrett\Git> cat .\Real.txt | ForEach-Object {echo $_}
'Doe, John'
'Doe, Jane'
Comparative For-Loop:
PS C:\Users\richard.barrett\Git> cat .\Real.txt | ForEach-Object {Get-ADUser -filter * -properties EmailAddress -SearchBase 'DC=xx-xxxx,DC=xxx,DC=xx,DC=us'| select-object Name, EmailAddress | select-string $_}
So I found out the problem to my issue.
I was not passing the variable correctly into the select-string at the end.
Since I am taking this from a .txt file, I decided to set a variable and forgo the for loop just calling the list directly over the file instead of iterating over the Get-ADUser command for each user...very slow. As a result, the following worked for me:
echo "Users for AD Verification" ;
echo "============ LIST ============" ;
cat .\PD.txt | ForEach-Object {echo $_} ;
echo "============ END LIST ========" ;
echo "Executing Active Directory Verification" ;
echo "============ PROCESS =========" ;
$list = cat .\PD.txt;
Get-ADUser -filter * -properties EmailAddress -SearchBase 'DC=del-valle,DC=k12,DC=tx,DC=us'| select-object Name, EmailAddress | select-string $list
echo "============ END PROCESS =====" ;
This gave me the list that was defined within the .\PD.txt.
Despite my initial hesitance, I have included my Identity OU for users to understand where the OUs should go in the command to pull out users and their email accounts within the AD.
Hopefully this helps someone else, I often get asked to verify users within my Active Directory.
I forgot to add, but the initial issue was with how I was placing the variable into the select-string I should not have used apostrophes. Here is the actual command that works as well, but it is slightly longer as it iterates and executes a command for each line...really long.
cat .\PD.txt | ForEach-Object {Get-ADUser -filter * -properties EmailAddress -SearchBase 'DC=del-valle,DC=k12,DC=tx,DC=us'| select-object Name, EmailAddress | select-string $_}

PowerShell Format-Table -AutoSize not Producing an Output File

When running the following line in PowerShell including the "Format-Table -AutoSize", an empty output file is generated:
Get-ChildItem -Recurse | select FullName,Length | Format-Table -AutoSize | Out-File filelist.txt
The reason I need the output file to be AutoSized is because longer filenames from the directoy are being trunacted. I am trying to pull all Filenames and File Sizes for all files within a folder and subfolders. When removing the -Autosize element, an output file is generated with truncated file names:
Get-ChildItem -Recurse | select FullName,Length | Out-File filelist.txt
Like AdminOfThings commented, use Export-CSV to get the untruncated values of your object.
Get-ChildItem -Recurse | select FullName,Length | Export-CSv -path $myPath -NoTypeInformation
I do not use Out-File much at all, and only use Format-Table/Format-List for interactive scripts. If I want to write data to a file, Select-Object Column1,Column2 | Sort-Object Column1| Export-CSV lets me select the properties of the object I am exporting that I want to export, and sort the records as needed. you can change the delimiter from a comma to tab/pipe/whatever else you may need.
While the other answer may address the issue, you may have other reasons for wanting to use Out-File. Out-File has a "Width" parameter. If this is not set, PowerShell defaults to 80 characters - hence your issue. This should do the trick:
Get-ChildItem -Recurse | select FullName,Length | Out-File filelist.txt -Width 250 (or any other value)
The Format-* commandlets in PowerShell are only intended to be used in the console. They do not actually produce output that can be piped to other commandlets.
The usual approach to get the data out is with Export-Csv. CSV files are easily imported into other scripts or spreadsheets.
If you really need to output a nicely formatted text file you can use .Net composite formatting with the -f (format) operator. This works similarly to printf() in C. Here is some sample code:
# Get the files for the report
$files = Get-ChildItem $baseDirectory -Recurse
# Path column width
$nameWidth = $files.FullName |
ForEach-Object { $_.Length } |
Measure-Object -Maximum |
Select-Object -ExpandProperty Maximum
# Size column width
$longestFileSize = $files |
ForEach-Object { $_.Length.tostring().Length } |
Measure-Object -Maximum |
Select-Object -ExpandProperty Maximum
# Have to consider that some directories will have no files with
# length strings longer than "Size (Bytes)"
$sizeWidth = [System.Math]::Max($longestFileSize, "Size (Bytes)".Length)
# Right-align paths, left-align file size
$formatString = "{0,-$nameWidth} {1,$sizeWidth}"
# Build the report and write it to a file
# ArrayList are much more efficient than using += with arrays
$lines = [System.Collections.ArrayList]::new($files.Length + 3)
# The [void] cast are just to prevent ArrayList.add() from cluttering the
# console with the returned indices
[void]$lines.Add($formatString -f ("Path", "Size (Bytes)"))
[void]$lines.Add($formatString -f ("----", "------------"))
foreach ($file in $files) {
[void]$lines.Add($formatString -f ($file.FullName, $file.Length.ToString()))
}
$lines | Out-File "Report.txt"

PowerShell Issue With GUI

I am having an issue when setting labels text with a PowerShell command. I am trying to set a label to the size of the mailbox, this is the command I use.
$MailBoxSize.Text = Get-Mailbox -Identity $comboBox1.SelectedItem | Get-MailboxStatistics | Select TotalItemSize | ft -HideTableHeader
Here is the result I get.
Microsoft.PowerShell.Commands.Internal.Format.FormatStartData Microsoft.PowerShell.Commands.Internal.Format.GroupStartData Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData Microsoft.PowerShell.Commands.Internal.Format.GroupEndData Microsoft.PowerShell.Commands.Internal.Format.FormatEndData
You should never be capturing the output of a Format-Table (or any other Format- command). Those commands are used for formatting output, usually to the console. Instead, if you wish to get the value to a property use the -ExpandProperty parameter of the Select-Object cmdlet. Change your line to read:
$MailBoxSize.Text = Get-Mailbox -Identity $comboBox1.SelectedItem | Get-MailboxStatistics | Select -ExpandProperty TotalItemSize

Save the powershell's output in a CSV file

I have a powershell script in which i can get information about my operating system (windows version, build...). However all that information is shown in the powershell console and I want them to be exported to a CSV or a XML file.
The script is :
Get-CimInstance Win32_OperatingSystem |
Select-Object Caption, CSDVersion, ServicePackMajorVersion, BuildNumber |
FL
Use Export-Csv cmdlet:
Get-CimInstance Win32_OperatingSystem | Select-Object Caption, CSDVersion, ServicePackMajorVersion, BuildNumber | Export-Csv -NoTypeInformation -Path .\OS_Info.csv
Result (OS_Info.csv):
"Caption","CSDVersion","ServicePackMajorVersion","BuildNumber"
"Microsoft Windows Server 2012 R2 Datacenter",,"0","9600"
Thank you it worked, the file is generated in the folder System32
As Rohin Sidharth mentioned, .\ prefix for the path will create file in the current dir ($PWD in PowerShell). You probably run PowerShell as administrator: in this case the default directory is %WinDir%\System32. Just use full path or GetFolderPath .Net method to get common folder path, like desktop:
... | Export-Csv -NoTypeInformation -Path 'C:\OS_Info.csv'
... | Export-Csv -NoTypeInformation -Path (Join-Path -Path [System.Environment]::GetFolderPath('Desktop') -ChildPath 'OS_Info.csv')
Can you also show me how to export many results in the same file ? for
example i have a script in which i can know all the update that are
installed :
Get-Hotfix | Select HotfixID,Description,InstalledOn | Sort InstalledOnfunction
and i want the results saves in the same CSV file
You can do this by using Select-Object's calculated properties:
# Get OS info
$OsInfo = Get-CimInstance -ClassName Win32_OperatingSystem
Get-Hotfix | # Get HotFixes
Sort-Object -Property InstalledOnfunction | # Sort them
Select-Object -Property #( # Select required fields
# Add Caption property from $OsInfo variable
#{
Name = 'Caption'
Expression = {$OsInfo.Caption}
}
# Add CSDVersion property from $OsInfo variable
#{
Name = 'CSDVersion'
Expression = {$OsInfo.CSDVersion}
}
# Add ServicePackMajorVersion property from $OsInfo variable
#{
Name = 'ServicePackMajorVersion'
Expression = {$OsInfo.ServicePackMajorVersion}
}
# Add BuildNumber property from $OsInfo variable
#{
Name = 'BuildNumber'
Expression = {$OsInfo.BuildNumber}
}
# Add other properties from original HotFix object
'HotfixID'
'Description'
'InstalledOn'
) | Export-Csv -NoTypeInformation -Path 'C:\OS_Info.csv'
You can also try to join objects using custom function.
Quick tip: Make sure you don't pipe to Format List (FL) then pipe to export-csv or you'll open the CSV file and your data will look like this.
ClassId2e4f51ef21dd47e99d3c952918aff9cd pageHeaderEntry pageFooterEntry
autosizeInfo shapeInfo groupingEntry
033ecb2bc07a4d43b5ef94ed5a35d280
Microsoft.PowerShell.Commands.Internal.Format.ListViewHeaderInfo
9e210fe47d09416682b841769c78b8a3
27c87ef9bbda4f709f6b4002fa4af63c
4ec4f0187cb04f4cb6973460dfe252df
cf522b78d86c486691226b40aa69e95c

Powershell group member ship field from AD

I have a powershell query here which look in a particular group in AD and extracts the users into a CSV. Currently it only extracts the SamAcountName and Display name. How would I get it extract the group membership of each user in that group ?
Get-ADGroupMember -identity GLS-IW-APP-QV-KPI-Full | select -Property Name,SamAccountName | Export-csv -path X:\QlikView_AD_Groups\GLS-IW-APP-QV-KPI-Full.csv -NoTypeInformation
So if you are looking to get the group membership of all users in a certain group this would be one approach. You need to add a calculated propery in your Select-Object
Get-ADGroupMember -identity GLS-IW-APP-QV-KPI-Full |
Select-Object -Property Name,SamAccountName,#{Label="MemberOf";Expression={(Get-ADUser -identity $_.SamAccountName -Properties memberof).memberof -Join ";"}} |
Export-csv -path X:\QlikView_AD_Groups\GLS-IW-APP-QV-KPI-Full.csv -NoTypeInformation
What the #{} portion does is take the SamAccountName and call Get-Aduser to extract the memberof property. Since that returns an object we concat that to a semicolon delimited string with a -Join for proper/better CSV output

Resources