Keep in mind I'm new to this and be gentle.
I have a full file path for a document "C:\folder1\folder2\01.03.2017 - FileName.csv" and I want to manipulate it to return the dir that the file is stored in (C:\folder1\folder2), minus the filename (01.03.2017 - FileName.csv).
I'm trying to make this modular so that it will work regardless of the amount of sub-folders a file sits in; we also won't know the FileName in advance, so again this needs to be modular and remove up to and including the last "\"
For background info on how this is currently built, I nicked a bit of code from a previous question I saw on StackOverflow:
Function Get-FileName($initialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName(“System.windows.forms”) |
Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = “All files (*.*)| *.*”
$OpenFileDialog.ShowDialog() | Out-Null
$OpenFileDialog.filename
} #end function Get-FileName
# *** Entry Point to Script ***
$originalData = Get-FileName -initialDirectory “c:\” | Out-String
Write-Host $originalData
$originalDir = $originalData.Split('\')
$originalDir
Running this currently prompts for an "open dialog box" you would see in Windows. You select a folder and the output is currently:
C:\folder1\folder2\01.03.2017 - FileName.csv
C:
folder1
folder2
01.03.2017 - FileName.csv
I've tried a few different -join attempts but none successful.
We will have an input of C:\folder1\folder2\01.03.2017 - FileName.csv as a variable $originalData.
We want the output to be C:\folder1\folder2 as a variable $originalDir.
Function Get-FileName($initialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName(“System.windows.forms”) |
Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = “All files (*.*)| *.*”
$OpenFileDialog.ShowDialog() | Out-Null
$OpenFileDialog.filename
} #end function Get-FileName
$originalData = Get-FileName -initialDirectory “c:\”
Write-Host $originalData
$originalDir = (Get-ChildItem $originalData).DirectoryName
you can use it like so, so take result or your function and use it with get-childitem.
edit: notice there's no | Out-String on the third to last line
Related
I have a string like this, retrieved from a txt file:
$txtindex = 5
$PRINTERNAME = get-content $txtPrinterfile | select -Index $txtindex
$PRINTERNAME = $PRINTERNAME.Trim()
$PRINTERNAME = $PRINTERNAME.Replace(" ","")
$Printername
NAME="W018"
So I thought I could easily add this to a hashtable:
$HashPrinter = #{}
$HashPrinter.Add($PRINTERNAME)
but this is not working.
Either this:
$HashPrinter = #{$PRINTERNAME}
If I type it manually:
$HashPrinter = #{NAME="W018"}
it works as expected.
What I am doing wrong?
PS C:\Users\alHaos> $HashTable = #{}
PS C:\Users\alHaos> $HashTable.Add("Name", "Pr001")
PS C:\Users\alHaos> $HashTable.Add("Manufacture", "Epson")
PS C:\Users\alHaos> $HashTable
Name Value
---- -----
Name Pr001
Manufacture Epson
I have a script that cycles through a folder and condenses multiple CSVs to one xlsx file with the names of the CSV as worksheets. However, when the script runs as part of a larger script it failes when it refreshes the query.
$Query.Refresh()
On its own the script runs fine, but when added to the larger one it fails. Can anyone advise why this is the case?
Below is the error I get:
Insufficient memory to continue the execution of the program.
At C:\Temp\Scripts\Shares_Complete.psm1:254 char:13
+ $Query.Refresh()
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], OutOfMemoryException
+ FullyQualifiedErrorId : System.OutOfMemoryException
I have tried single csv with the same code and still the same result.
$script:SP = "C:\Temp\Servers\"
$script:TP = "C:\Temp\Servers\Pc.txt"
$script:FSCSV = "C:\Temp\Server_Shares\Server Lists\"
$script:Message1 = "Unknown Hosts"
$script:Message2 = "Unable to connect"
$script:Message3 = "Unknown Errors Occurred"
$script:Txt = ".txt"
$script:OT = ".csv"
$script:FSERROR1 = $FSCSV+$Message1+$OT
$script:FSERROR2 = $FSCSV+$Message2+$OT
$script:FSERROR3 = $FSCSV+$Message2+$OT
$script:ERL3 = $E4 + "Shares_Errors_$Date.txt"
$script:ECL1 = $E4 + "Shares_Exceptions1_$Date.txt"
$script:ERL1 = $E4 + "Shares_Errors1_$Date.txt"
$script:ECL3 = $E4 + "Shares_Exceptions_$Date.txt"
function Excel-Write {
if ($V -eq "1") {
return
}
[System.GC]::Collect()
$RD = $FSCSV + "*.csv"
$CsvDir = $RD
$Ma4 = $FSCSV + "All Server Shares for Domain $CH4"
$csvs = dir -path $CsvDir # Collects all the .csv's from the driectory
$FSh = $csvs | Select-Object -First 1
$FSh = ($FSh -Split "\\")[4]
$FSh = $FSh -replace ".{5}$"
$FSh
$outputxls = "$Ma4.xlsx"
$script:Excel = New-Object -ComObject Excel.Application
$Excel.DisplayAlerts = $false
$workbook = $excel.Workbooks.Add()
# Loops through each CVS, pulling all the data from each one
foreach ($iCsv in $csvs) {
$script:iCsv
$WN = ($iCsv -Split "\\")[-1]
$WN = $WN -replace ".{4}$"
if ($WN.Length -gt 30) {
$WN = $WN.Substring(0, [Math]::Min($WN.Length, 20))
}
$Excel = New-Object -ComObject Excel.Application
$Excel.DisplayAlerts = $false
$Worksheet = $workbook.Worksheets.Add()
$Worksheet.Name = $WN
$TxtConnector = ("TEXT;" + $iCsv)
$Connector = $worksheet.Querytables.Add($txtconnector,$worksheet.Range("A1"))
$query = $Worksheet.QueryTables.Item($Connector.Name)
$query.TextfileOtherDelimiter = $Excel.Application.International(5)
$Query.TextfileParseType = 1
$Query.TextFileColumnDataTypes = ,2 * $worksheet.Cells.Column.Count
$query.AdjustColumnWidth = 1
$Query.Refresh()
$Query.Delete()
$Worksheet.Cells.EntireColumn.AutoFit()
$Worksheet.Rows.Item(1).Font.Bold = $true
$Worksheet.Rows.Item(1).HorizontalAlignment = -4108
$Worksheet.Rows.Item(1).Font.Underline = $true
$Workbook.Save()
}
$Empty = $workbook.Worksheets.Item("Sheet1")
$Empty.Delete()
$Workbook.SaveAs($outputxls,51)
$Workbook.Close()
$Excel.Quit()
$ObjForm.Close()
Delete
}
Should continue script and create the xlsx.
Looking at your script, it doesn't surprise me you eventually run out of memory, because you are continouisly creating Com objects and never release them from memory.
Whenever you have created Com objects and finished with them, use these lines to free up the memory:
$Excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
Also, take a good look at the code.
You are creating a $Script:Excel = New-Object -ComObject excel.application object before the foreach loop but you don't use that. Instead, you are creating new Excel and workbook objects inside the loop over and over again where there is absolutely no reason for it since you can re-use the one you created before the loop.
As an aside: The following characters are not allowed in excel worksheet names
\/?*[]:
Length limitation is 31 characters.
EDIT
I had a look at your project and especially the Shares_Complete.psm1 file.
Although I'm not willing of course to rewrite your entire project, I do have some remarks that may help you:
[System.Net.Dns]::GetHostByName() is obsolete. Use GetHostEntry()
when done with a Windows form, use $ObjForm.Dispose() to clear it from memory
you do a lot of [System.GC]::Collect(); [System.GC]::WaitForPendingFinalizers() for no reason
Why not use [System.Windows.MessageBox]::Show() instead of using a Com object $a = new-object -comobject wscript.shell. Again you leave that object lingering in memory..
use Join-Path cmdlet instead of $RD = $FSCSV + "*.csv" or $Cop = $FSCSV + "*.csv" constructs
remove invalid characters from Excel worksheet names (replace '[\\/?*:[\]]', '')
use Verb-Noun names for your functions so it becomes clear what they do. Now you have functions like Location, Delete and File that don't mean anything
you are calling functions before they are defined like in line 65 where you call function Shares. At that point it does not exist yet because the function itself is written in line 69
add [System.Runtime.Interopservices.Marshal]::ReleaseComObject($worksheet) | Out-Null in function Excel-Write
there is no need to use the variable $Excel in script scope ($Script:Excel = New-Object -ComObject excel.application) where it is used only locally to the function.
you may need to look at Excel specifications and limits
fix your indentation of code so it is clear when a loop or if starts and ends
I would recommend using variable names with more meaning. For an outsider or even yourself after a couple of months two-letter variable names become confusing
I have a text file with a list of words with definitions, like this...
的 of / ~'s (possessive particle) / (used after an attribute) / (used to form a nominal expression) / (used at the end of a declarative sentence for emphasis)
我 I / me / my
你 you (informal, as opposed to courteous 您[nín])
是 is / are / am / yes / to be / variant of 是[shì] / (used in given names)
了 (modal particle intensifying preceding clause) / (completed action marker)
不 (negative prefix) / not / no
I need to create a text file in Windows 10 for each Chinese word in the list with the content of the file being the English definition.
For example I need a text file named 的.txt ...
...with this content in the file:
of / ~'s (possessive particle) / (used after an attribute) / (used to form a nominal expression) / (used at the end of a declarative sentence for emphasis)
I'm fairly proficient with Javascript, familiar with python, and have powershell available on my computer.
How can I accomplish this?
If I understand correctly, this should do the trick.
with open('yourfile.txt') as definitions:
for line in definitions:
name, definition = line.split(maxsplit=1)
with open(name + '.txt', 'w') as out:
out.write(definition)
It iterates over the content of the definitions-file line by line, splits each line into the filename and definition part, and then writes the definition into a file with the appropriate name.
You can just look through each line and split it at triple spaces:
powershell
$Content = Get-Content -Path C:\Temp\Temp.txt
foreach ( $Line in $Content )
{
$Temp = $Line -split ' ' | Where-Object -FilterScript { -not [System.String]::IsNullOrWhiteSpace($_) }
New-Item -Path "C:\Temp" -Name "$($Temp[0]).txt" -Value $Temp[1]
}
to read
with open ("File_name","r") as f:
f.read()
to write
with open ('file_name','w') as f:
f.write('content')
I am using a Powershell script to write to a text file. A client showed me this Powershell script to use to replace a excel macro I used to use...
$computers= gc "C:\Users\Powershell\DeviceList.txt"
foreach ($computername in $computers)
{
write-output "<$computername>
active = yes
group =
interval = 5min
name = $computername
host = $computername
community =
version = 1
timeout = 0
retries = default
port = 161
qos_source = 1
</$computername>" | Out-File -filepath "C:\Users\Powershell\Cisco_Mon.txt" -append
}
It works great but now I wanted to build on it to add additional variables. In a perfect world I would like it to read from an excel spreadsheed grabbing each rowof data and each column being defined as a variable. For now using another text file is fine as well. Here is what I started with (it doesnt work) but you can see where I am going with it...
$computers= gc "C:\Users\Powershell\devicelist.txt"
$groups= gc "C:\Users\Powershell\grouplist.txt"
foreach ($computername in $computers) + ($groupname in $groups)
{
write-output "<$computername>
active = yes
group = $groupname
interval = 5min
name = $computername
host = $computername
community =
version = 1
timeout = 0
retries = default
port = 161
qos_source = 1
</$computername>" | Out-File -filepath "C:\Users\Powershell\Cisco_Mon.txt" -append
}
Of course it is not working. Essentially I would LOVE it if I could define each of the above options into a variable from an excel spreadsheet, such as $community, $interval, $active, etc.
Any help with this would be very much appreaciated. If someone could show me how to use an excel spreadsheet, have each column defined as a variable, and write the above text with the variables, that would be GREAT!!!.
Thanks,
smt1228#gmail.com
An Example of this would be the following...
Excel Data: (Colums seperated with "|"
IP | String | Group
10.1.2.3 | Public | Payless
Desired Output:
<10.1.2.3>
active = yes
group = Payless
interval = 5min
name = 10.1.2.3
host = 10.1.2.3
community =
version = 1
timeout = 0
retries = default
port = 161
qos_source = 1
</10.1.2.3>
Addition:
Pulling data from CSV for IP, String, Group where data is as follows in CSV...
10.1.2.3,public,group1
10.2.2.3,default,group2
10.3.2.3,public,group3
10.4.2.3,default,group4
to be writting into a .txt file as
IP = 10.1.2.3.
String = public
Group = Group1
and look for each line in the CSV
Ok, new answer now. The easiest way would be to save your Excel document as CSV so that it looks like this (i.e. very similar to how you presented your data above):
IP,String,Group
10.1.2.3,Public,Payless
You can still open that in Excel, too (and you avoid having to use the Office interop to try parsing out the values).
PowerShell can parse CSV just fine: with Import-Csv:
Import-Csv grouplist.csv | ForEach-Object {
"<{0}>
active = yes
group = {1}
interval = 5min
name = 10.1.2.3
host = 10.1.2.3
community =
version = 1
timeout = 0
retries = default
port = 161
qos_source = 1
</{0}>" -f $_.IP, $_.Group
}
I'm using a format string here where {0}, etc. are placeholders. -f then is the format operator which takes a format string on the left and arguments for the placeholders on the right. You can also see that you can access the individual columns by their name, thanks to Import-Csv.
The following script spits out all UserProfile properties for users on Sharepoint 2007:
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server.UserProfiles")
# Function: Get-UserProfiles
# Description: return a UserProfileManager object containing all user profiles
# Parameters: SSPName SSPName
#
Function global:Get-UserProfiles($SSPName)
{
$ServerContext = [Microsoft.Office.Server.ServerContext]::GetContext($SSPName);
$UPManager = new-object Microsoft.Office.Server.UserProfiles.UserProfileManager($ServerContext);
return $UPManager.GetEnumerator();
}
$profiles = Get-UserProfiles("SharedServices");
$profiles | ForEach-Object { $_.GetEnumerator();}
However, what I want to do is be able to return a table, or csv file of specific values in the profile, e.g. Username, WorkEmail, WorkPhone. I have tried piping the output to |ft Username, WorkEmail, Workphone and | select Username, WorkEmail, WorkPhone but this just returns blanks.
I feel like I am so close. I don't want to replace the $_.GetEnumerator() call with lots of $_.Item("property") calls and it doesn't feel like I should have to. Any ideas?
I've further developed the code so that it now accepts a comma delimited list of properties and writes them to a delimited file.
# Outputs a delimited file with specified user profile properties for each user in Sharepoint
# Create array of desired properties
$arProperties = 'UserName','FirstName','LastName','Title','WorkEmail','WorkPhone','Manager','AlternateContact','RoleDescription','PictureURL';
# Specify output file
$outfile = 'UserProfiles.csv';
#Specify delimiter character (i.e. not one that might appear in your user profile data)
$delim = '^';
# Specify Shared Service Provider that contains the user profiles.
$SSP = "SharedServices";
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server.UserProfiles")
# Function: Get-UserProfiles
# Description: return a UserProfileManager object containing all user profiles
# Parameters: SSPName SSPName
#
Function global:Get-UserProfiles($SSPName)
{
$ServerContext = [Microsoft.Office.Server.ServerContext]::GetContext($SSPName);
$UPManager = new-object Microsoft.Office.Server.UserProfiles.UserProfileManager($ServerContext);
return $UPManager.GetEnumerator();
}
$profiles = Get-UserProfiles($SSP);
#Initialise Output file with headings
$header = [string]::join($delim,$arProperties);
Write-Output $header | Out-File $outfile
#Output the specified properties for each
$profiles | ForEach-Object {
foreach($p in $arProperties){
# Get the property name and add it to a new array, which will be used to construct the result string
$arProfileProps += $_.Item($p);
}
$results = [string]::join($delim,$arProfileProps);
# Get rid of any newlines that may be in there.
$CleanResults = $results.Replace("`n",'');
Write-Output $CleanResults
Remove-Variable -Name arProfileProps
} | Out-File -Append $outfile
This gets me a bit closer. I'd still really like a script that iterates through all the profile properties and puts them into a CSV or XML file more gracefully. This will do for now.