I want to add an append to my script. So if it should crash it gives me the data to this point and dont print like nothing.
Right now the use of the script is to filter a List by name and Date. After that it remove all names on the blacklist and only contains entries from the month i entered
[xml]$config = Get-Content -Path 'C:\Users\DZimmermann\Desktop\EVIM.Script\EVIM-Config.xml'
[xml]$blacklist = Get-Content -Path 'C:\Users\DZimmermann\Desktop\EVIM.Script\EVIM-Blacklist.xml'
#Names to filter
$BLN = $blacklist.Names
#Import Path
$info = Import-Csv $config.config.path.input -Delimiter ';'
$info | Format-Table
#from which month
#$dateCutoff = get-date "02.2020" -Format "MM.yyyy"
$dateCutoff = $config.config.date
$result = foreach($i in $info){
if(-Not($blacklist -contains $i.SCAN_USER)){
$entryDate = get-date $i.SCAN_DATE -Format "MM.yyyy"
if($entryDate -eq $dateCutoff){
$i
}
}
Write-Host $i.SCAN_DATE
}
#Export path
$result | Export-Csv $config.config.path.output -NoTypeInformation -Delimiter ';'
$dateCutoff
all my changeble vars are linkt with a config file so you dont have to edit the script every time.
Start-Transcript -Path "path to save the transcript" -Append
xml]$config = Get-Content -Path 'C:\Users\DZimmermann\Desktop\EVIM.Script\EVIM-Config.xml'
[xml]$blacklist = Get-Content -Path 'C:\Users\DZimmermann\Desktop\EVIM.Script\EVIM-Blacklist.xml'
#Names to filter
$BLN = $blacklist.Names
#Import Path
$info = Import-Csv $config.config.path.input -Delimiter ';' -Verbose
$info | Format-Table -Verbose
#from which month
#$dateCutoff = get-date "02.2020" -Format "MM.yyyy"
$dateCutoff = $config.config.date
$result = foreach($i in $info){
if(-Not($blacklist -contains $i.SCAN_USER)){
$entryDate = get-date $i.SCAN_DATE -Format "MM.yyyy"
if($entryDate -eq $dateCutoff){
$i
}
}
Write-Host $i.SCAN_DATE
}
#Export path
$result | Export-Csv $config.config.path.output -NoTypeInformation -Delimiter ';' -Append -Verbose
$dateCutoff
Stop-Transcript
thank you for your help but i think i got it :) My script looks now like this
[xml]$config = Get-Content -Path 'C:\Users\DZimmermann\Desktop\EVIM.Script\EVIM-Config.xml'
[xml]$blacklist = Get-Content -Path 'C:\Users\DZimmermann\Desktop\EVIM.Script\EVIM-Blacklist.xml'
#Names to filter
$BLN = $blacklist.Names
#Import Path
$info = Import-Csv $config.config.path.input -Delimiter ';'
$info | Format-Table
#from which month
#$dateCutoff = get-date "02.2020" -Format "MM.yyyy"
$dateCutoff = $config.config.date
$result = foreach($i in $info){
if(-Not($BLN -contains $i.SCAN_USER)){
$entryDate = Get-Date $i.SCAN_DATE -Format "MM.yyyy"
if($entryDate -eq $dateCutoff){
$i
}
}
$result | Out-File $config.config.path.output
Write-Host $i
$config.config.path.output + "\" + $info | Out-File -Append $config.config.path.output
}
Related
I need to import a few groups from a CSV file and then export members - but I need it like one row each, something like:
"Group_name1", "member1, member2,member3"
"Group_name2", "member1,member2,member3"
"Group_name3", "member1,member2,member3"
And my script is working fine for a single group but I'm having troubles with adding a for-each loop - the result contains only last item from the CSV..
#$DL='plum'
$DL_List = "C:\ps1\shared_mailboxes\groups.csv"
$DL_array = (Import-Csv -Path $DL_List).name
foreach ($DL in $DL_array)
{
$DL_Membership = (Get-DistributionGroupMember -identity $DL).displayName
if([string]$DL_Membership -ne "")
{
$Members = ""
foreach($DL_Membership in $DL_Membership)
{
if($Members -ne "")
{
$Members=$Members +","
}
$Members = $Members + $DL_Membership
}
}
}
$ExportCSV=".\group_members_$((Get-Date -format yyyy-MMM-dd-ddd` hh-mm` tt).ToString()).csv"
$Result = #{'Group'=$DL;'Users'=$Members}
$Results = New-Object PSObject -Property $Result
$Results |select-object 'Group','Users' | Export-Csv -Path $ExportCSV -Notype -Append
I googled it but I'm not sure what I should change in my script..
The script has been re-writed using -join operator and now it's working as excepted.
$DL_List = Import-Csv "C:\ps1\shared_mailboxes\groups.csv"
$CsvOut = foreach ( $dl in $DL_List ) {
$Group = $dl.name
$MemberArray = (Get-DistributionGroupMember -identity $Group).displayName
$MemberList = $MemberArray -join ','
# generate the output object
# that goes in $CsvOut
[PSCustomObject] #{
Group = $Group
Members = $MemberList
}
}
$Timestamp = Get-Date -Format 'yyyy-MM-dd-HHmm' # this is a string
$CsvOutPath = "c:\ps1\shared_mailboxes\memberlist.$Timestamp.csv"
$CsvOut | Export-Csv $CsvOutPath -NoTypeInfo
I think you are over-complicating this.
If your desired result is a CSV file, then output objects straight away like below:
$DL_List = 'C:\ps1\shared_mailboxes\groups.csv'
$DL_array = (Import-Csv -Path $DL_List).name
$outFile = '.\group_members_{0:yyyy-MMM-dd-ddd hh-mm}.csv' -f (Get-Date)
$result = foreach ($DL in $DL_array) {
# output an object with the name of the DL and its members
[PsCustomObject]#{
Group = $DL
Users = (($DL | Get-DistributionGroupMember).displayName |
Where-Object {$_ -match '\S'}) -join ','
}
}
$result | Export-Csv -Path $outFile -NoTypeInformation
Using calculated properties, you can also do this without a foreach loop:
$DL_List = 'C:\ps1\shared_mailboxes\groups.csv'
$DL_array = (Import-Csv -Path $DL_List).name
$outFile = '.\group_members_{0:yyyy-MMM-dd-ddd hh-mm}.csv' -f (Get-Date)
$DL_array | Select-Object #{Name = 'Group'; Expresssion = {$_}},
#{Name = 'Users'; Expresssion = {
(($_ | Get-DistributionGroupMember).displayName |
Where-Object {$_ -match '\S'}) -join ','
}} |
Export-Csv -Path $outFile -NoTypeInformation
The purpose of this code is to transfer files from one location to another and to log whether the transfer was a success or a failure.
Everything works except I am having issues with the log. I want the log to be in CSV format and there to be 3 columns: success/failure, from location, and to location. This is outputting the results all into rows with one column.
I've tried the Export-Csv option but that looks for objects/properties so only displays the length(I have strings too). Add-content works but there is only one column. Any suggestions?
#LOCATION OF CSV
$csv = Import-Csv C:\test2.csv
#SPECIFY DATE (EXAMPLE-DELETE FILES > 7 YEARS. 7 YEARS=2555 DAYS SO YOU WOULD ENTER "-2555" BELOW)
$Daysback = "-1"
#FILE DESTINATION
$storagedestination = "C:\Users\mark\Documents\Test2"
#LOG LOCATION
$loglocation = "C:\Users\mark\Documents\filetransferlog.csv"
$s = "SUCCESS"
$f = "FAIL"
$CurrentDate = Get-Date
foreach ($line in $csv) {
$Path = $line | Select-Object -ExpandProperty FullName
$DatetoDelete = $CurrentDate.AddDays($DaysBack)
$objects = Get-ChildItem $Path -Recurse | Select-Object FullName, CreationTime, LastWriteTime, LastAccessTime | Where-Object { $_.LastWriteTime -lt $DatetoDelete }
foreach ($object in $objects) {
try
{
$sourceRoot = $object | Select-Object -ExpandProperty FullName
Copy-Item -Path $sourceRoot -Recurse -Destination $storagedestination
Remove-Item -Path $sourceRoot -Force -Recurse
$temp = $s, $sourceRoot, $storagedestination
$temp | add-content $loglocation
}
catch
{
$temp2 = $f, $sourceRoot, $storagedestination
$temp2 | add-content $loglocation
}
}
}
All your | Select-Object -ExpandProperty are superfluous, simply attach the property name to the variable name => $Path = $line.FullName
Why calculate $DatetoDelete inside the foreach every time?
Output the success/fail to a [PSCustomObject] and gather them in a variable assigned directly to the foreach.
Untested:
$csv = Import-Csv C:\test2.csv
$Daysback = "-1"
$destination = "C:\Users\mark\Documents\Test2"
$loglocation = "C:\Users\mark\Documents\filetransferlog.csv"
$s = "SUCCESS"
$f = "FAIL"
$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.Date.AddDays($DaysBack)
$Log = foreach ($line in $csv) {
$objects = Get-ChildItem $line.FullName -Rec |
Where-Object LastWriteTime -lt $DatetoDelete
foreach ($object in $objects) {
$Result = $s
$sourceRoot = $object.FullName
try {
Copy-Item -Path $sourceRoot -Recurse -Destination $destination
Remove-Item -Path $sourceRoot -Recurse -Force
} catch {
$Result = $f
}
[PSCustomObject]#{
'Success/Fail' = $Result
Source = $sourceRoot
Destination = $destination
}
}
}
$Log | Export-Csv $loglocation -NoTypeInformation
I currently have a CSV file that has 2,440 lines of data. The data looks something like:
server1:NT:Y:N:N:00:N
server2:NT:Y:N:n:33:N
This is what I have so far:
$newCsvPath = Get-Content .\sever.csv |
Where-Object { $_ -notmatch '^#|^$|^"#' }
[int]$windows = 0
[int]$totalsever = 0
$Results = #()
$date = Get-Date -Format g
Clear-Content .\results.csv -Force
foreach ($thing in $newCsvPath) {
$totalsever++
$split = $thing -split ":"
if ($split[1] -contains "NT") {
$windows++
$thing | Out-File results.csv -Append -Force
} else {
continue
}
}
Clear-Content .\real.csv -Force
$servers = Get-Content results.csv
foreach ($server in $servers) {
$server.Split(':')[0] | Out-File real.csv -Append -Force
}
My issue is that when the script gets to the $server.Split(':')[0] | Out-File real.csv -Append -Force part, for some reason it only outputs 1,264 lines instead of all 2,440 to "real.csv". However, when I remove | Out-File real.csv -Append -Force, $server stores ALL 2,400 names of servers.
Does anyone have any idea of why this is happening?
I'm trying to loop a pipe delimited file, check if the line has 28 columns and just export that line to the file. This is the primary question and answer I'm looking for (I have researched a lot, but I'm new to PS and so many different ways I need some help). The following works but there are two issues. The export file will not let me choose pipe delimited, AND the output goes in alphabetical format by field name, not by ordinal.
Also, is there a way I can make the output not "text" qualified?
$path = Get-ChildItem c:\temp\*.txt
$staticPath = '0859'
$year = Get-Date -format yy
$month = Get-Date -format MM
$day = Get-Date -format dd
$output = 'c:\temp\' + $year + $month + $day + $staticPath + '.TXT'
$outputbad = 'c:\temp\BAD' + $year + $month + $day + $staticPath + '.TXT'
$input = 'c:\temp\' + $path.Name
$input
$csv = Import-Csv -path $input -Delimiter "|"
foreach($line in $csv)
{
$properties = $line | Get-Member -MemberType Properties
$row = ''
$properties.Count
$obj = new-object PSObject
for($i=0; $i -lt $properties.Count;$i++)
{
$column = $properties[$i]
$columnvalue = $line | Select -ExpandProperty $column.Name
#$row += $columnvalue
$obj | add-member -membertype NoteProperty -name $column.Name -value $columnvalue
}
if($properties.Count -eq 28)
{
$obj | export-csv -Path $output -Append -NoTypeInformation
#$row | Export-Csv -Path $output -Append -Delimiter "|" -NoTypeInformation
}
else
{
$obj | Export-Csv -Path $outputbad -Append -Delimiter "|" -NoTypeInformation
}
}
If you want to avoid any chance of changing the formatting of these lines files, perhaps you don't want to use the -CSV commands. Export-csv can add quotation marks etc. Here's different way that might do what you want:
$path | ForEach-Object {
$good = #()
$bad = #()
Get-Content $_ | ForEach-Object {
if (($value = $_ -split '\|').length -eq 28) {
$good += $_
} else {
$bad += $_
}
}
if ($good) { Out-File -Append -InputObject $good $output }
if ($bad) { Out-File -Append -InputObject $bad $outputbad }
}
Note however that this will count quoted values containing a pipe differently than import-csv. Pipe separated values are sometimes generated without any quoting logic.
The $values variable will be an array of individual columns, so if you want to write some code to fix them up inside the if, you can use that then join them back up with $good += $values -join '|', or perhaps use another regex to fix errors.
silly me, here is the answer. But if somebody could answer why the PSObject or the properties loop is alphabetical it would be helpful. Soon i would like to add intelligence to this to check ordinal (not alphabetic field name order) a field if its a integer or not, then i know how to fix the BAD record.
$path = Get-ChildItem c:\temp\*.txt
$staticPath = '0859'
$year = Get-Date -format yy
$month = Get-Date -format MM
$day = Get-Date -format dd
$output = 'c:\temp\' + $year + $month + $day + $staticPath + '.TXT'
$outputbad = 'c:\temp\BAD' + $year + $month + $day + $staticPath + '.TXT'
$input = 'c:\temp\' + $path.Name
$csv = Import-Csv -path $input -Delimiter "|"
foreach($line in $csv)
{
$properties = $line | Get-Member -MemberType Properties
if($properties.Count -eq 28)
{
$line | export-csv -Path $output -Append -NoTypeInformation -Delimiter "|"
}
else
{
$line | Export-Csv -Path $outputbad -Append -Delimiter "|"
}
}
I'm using the next Powershell Script to get items from Sharepoint List and export it
how can i edit this script to get only today created data or the data entered today
This is the code
$MyWeb = Get-SPWeb "http://ilike-eg.suz.itcgr.net/SM"
$MyList = $MyWeb.Lists["SCGC"]
$exportlist = #()
$Mylist.Items | ForEach-Object {
$obj = New-Object PSObject -property #{
"A"=" "+$_["AACCOUNT_ID"]
"B"=" "+$_["BTRANSACTION_ID"]
"C"=" "+$_["CDATE"]
"D"=" "+$_["DCUSTOMER_ID"]
"E"=" "+$_["ECUSTOMER_NAME"]
"F"=" "+$_["FAMOUNT"]
"G"=" "+$_["GCLASS"]
}
#Remove unnecessary sort
$exportlist += $obj
$DateStamp = get-date -uformat "%Y-%m-%d#%H-%M-%S"
$NameOnly = "CDP"
#Exporting with sorted properties
$exportlist |
Select-Object A,B,C,D,E,F,G |
Export-Csv -Delimiter "`t"-path "$NameOnly.txt"
}
#Removed duplicate get-content line
$a, ${d:CDP.txt} = Get-Content .\CDP.txt
$a, ${d:CDP.txt} = Get-Content .\CDP.txt
(Get-Content D:\CDP.txt) |
Foreach-Object {$_ -replace $([char]34) -replace "`t" -replace '/', '-'} |
Set-Content D:\CDP.txt
Thanks
Where you're piping in the SPListItems, insert a query to get items created today
Change this:
$Mylist.Items |
To this:
$Mylist.Items | where {$_['Created'] -eq Get-Date -format d}