How to use SSL with different port in Send-MailMessage?
PowerShell Credential
Hi Techies,
I have created a form with powershell and when in the form when i enter credentails, it prompts a credential wizard and ask for login credential, which i dont want.
i want to execute the credentials which i enter in the form, please suggest.
regards
Vinay
Execution policy modification audit trail
What's the best way to track execution policy changes on a server? One of the engineers on my team inadvertently changed the execution policy on a production server to Restricted which caused a whole bunch of tasks to fail. I spent hours trying to figure out who did it but none of the event logs on the server are showing who did it and when.
Creating In-Memory Mail Attachments
Hi,
What I am trying is to send a string ($myString) in an email directly as attachment (.txt file). OR, writing string ($myString) into memory and creating mail attachment reading the memorystring directly and sending mail. I do not want any external file dependancy (eg. creating & deleting file).
I found a C# code. Trying to convert this into powershell. Just need suggestion on conversion if it is possible?
// Create a memory stream
using (MemoryStream memoryStream = new MemoryStream())
{
byte[] contentAsBytes = Encoding.UTF8.GetBytes(fileContentTextBox.Text);
memoryStream.Write(contentAsBytes, 0, contentAsBytes.Length);
// Set the position to the beginning of the stream.
memoryStream.Seek(0, SeekOrigin.Begin);
// Create attachment
ContentType contentType = new ContentType();
contentType.MediaType = MediaTypeNames.Application.Octet;
contentType.Name = fileNameTextBox.Text;
Attachment attachment = new Attachment(memoryStream, contentType);
// Add the attachment
message.Attachments.Add(attachment);
// Send Mail via SmtpClient
smtpClient.Send(message);
}
The specified path is too long error
Hi Guys,
I want to get the FullName, LastWritetime and Length for multiple folders. i wrote the below mentioned lines to get the details.
get-childitem "E:\Common" -rec | where {!$_.PSIsContainer} |select-object FullName, LastWriteTime, Length
But i am getting as
"get-childitem : The specified path, file name, or both are too long. The fully qualified file name must be less than 26
0 characters, and the directory name must be less than 248 characters."
How to workaround this issue. please help me to fix it.
//Bala R
Issue disabling LLDP
I am running a test on a personal computer to see the outcome of disabling LLDP and what strain/constraints that will put on a system in a business environment before even thinking of rolling it out in an office but I am met with this error when attempting:
PS C:\>Disable-NetLldpAgent -NetAdapterName "Ethernet2"
Get-Process : A parameter cannot be found that matches parameter name 'NetAdapterName'.
At line:1 char:29
+ PS C:\>Disable-NetLldpAgent -NetAdapterName "Ethernet2"
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-Process], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.GetProcessCommand
I am using the recommended method from the Microsoft Docs on disabling LLDP, any help would be appreciated :)
Source: https://docs.microsoft.com/en-us/powershell/module/netldpagent/disable-netlldpagent?view=win10-ps
convert .eml to .msg
I have 500000 .eml files that needs to be converted to .msg file and save in local folder.
I want to know if we have any powershell command to do so?
Or any other efficient method to achieve this??(C#)
PS: Dont want to use third party converters.
Get-Childitem for files with similar names
Is it possible to use something like get-childitem to get files with similar names, then only keep the latest two versions by date?
I know this can be done if they were in individual folders, but all files are in the same folder.
Example files below in B:\backups. The files have same name followed by the date.
backup21302019
backup22032019
backup23032019
test21032019
test22032019
test23032019
Invoke-RestMethod credentials
I am working on a powershell script that communicates with an API of an internal application. I got it to work by using the "Invoke-RestMethod" cmdlet, but the credentials are hardcoded into the script. I am using this script in a Task Sequence. The authentication must contain 'Basic username:password' and must be base64 encoded over a TLS 1.2 tunnel in the header over HTTPS request. The contenttype must be JSON format.
I've tried several things:
- Use the "-UseDefaultCredentials" parameter when making the "Invoke-RestMethod" request. This doesn't work because the authentication accepted by the application API is the format mentioned above.
- Run the script as a service account that have the credentials that have access to the API. Within the script get the password of the current user running the script. And then use that password to authenticate with the API. This doesnt work, because you can't get the password of the current user running the script.
- Create a PSCredentials XML file with the credentials encrypted. This also doesnt work, because I cant decrypt the xml format because these credentials can only be decrypted by the user that created the file in combination on the pc where the PSCredentials XML file was created. Every client is different that communicates with the API so I cant create a general XML file.
You can find my code under here. Do you guys have any suggestions from a Powershell perspective?
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $RestAPIServer = "https://applicationserver.com" $RestAPIURI = "/rest/application/" $RestRequest = $RestAPIServer + $RestAPIURI $Header = @{"Authorization" = "Basic "+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("username"+":"+"password"));} $Type = "application/json" Invoke-RestMethod -UseBasicParsing -Uri $RestRequest -Headers $Header -Method GET -ContentType $Type
Array disk DeviceID
Hi,
I'm running into the following challenge:
I have an Array which is filled with deviceID Drive letters from windows.
When I enter a Result en view the result the value is returnd in a value 0-1-2-3
Now I want to connect the result value to a drive letter. But I'm not getting this done :)
Hope you can help me
$disk_info = Get-WmiObject -Class Win32_logicaldisk $a =@("all") $a += $disk_info.DeviceID $options = [System.Management.Automation.Host.ChoiceDescription[]]($a) $title = 'Select drive to query' $message = 'choice' $results = $host.ui.PromptForChoice($title, $message, $options, 0) ForEach ($result in $results) { if (($result -eq 0) -or ($result -eq 1)) { Write-host -ForegroundColor red "Blablabla." } elseif ($result -gt 1 ) { } }
Thank's in advance for the help
Roel Knippen
Reference user list in Powershell
Hey folks,
I have this script, but I want a variable to look up a txt file instead of that single user. I cannot get anything to work. How can I insert this?
if (-not (Get-Module ActiveDirectory)){Import-Module ActiveDirectory
}
$ou = "OU=*,DC=yourmom,DC=com"
## allow logon 8am - 6pm Monday to Friday
[byte[]]$hours = @(0,0,0,0,255,3,0,255,3,0,255,3,0,255,3,0,255,3,0,0,0)
"`nMicrosoft"
$name = "aaronr1"
Get-ADUser -Identity $name |
Set-ADUser -Replace @{logonhours = $hours}
How to derive computer name from entering user name into a csv file containing both sets of items?
Create Active Directory Groups with users from CSV
Hello everyone,
I'm trying to create a Group with Users from CSV. The CSV looks like:
GroupName|Description|Members
Group1|Group Description 1|user1;user2;user3;user4
Group2|Group Descruption 2|user1;user2;user4;user8;user9;user999
I've searched the forums and found a few things that may or may not be relevant, however each OP seems to have at least some background with PS functions.
I'm not looking to particularly have my hand held, but if someone could point me in the right direction, I would greatly appreciate the help.
Thank you to anyone who can take the time to help me out. Peace!
Maca
Timestamping an out-file
Hello I would like add a timestamp to an out file but I can't seem to get it to work using this.
$yourdir="\\directory\home\%username%\rz\backup" $destfile= ([Environment]::GetFolderPath("Desktop") + "\totalresult_$(get-date -Format yyyymmdd_hhmmtt).txt") Get-ChildItem $yourdir -File -Filter *.txt | %{"________________________" |out-file $destfile -Append; $_.Name | Out-File $destfile -Append; gc $_.FullName | Out-File $destfile -Append}
I get everything else to work except this part.
No pop window apeared when run a script in windows schedule
Hi Guys,
I saved msgbox "testing..." to a vbs file and double click it works and there is a pop window show up, but when I put this vbs script in the windows schedule it works fine but no pop window apeared , I just found a wscript.exeprocess in the task manager, I also tried bat, ps1 script, it the same, no pop windows show up when I run it in windows schedule. So, can you tell me why and how to fix this? Thanks!
What am I doing wrong in my powershell POST for an API?
I was able to GET but i am not able to post. See screenshot:
There is a field called = Last Sign in" where I want to write "Last Sign in API"
However, I want to only add it to the Organization ID 1893961 and Flexible-asset-type-id: 122389
I am getting some kind of syntax error. This is my first time using APIs: I am following the tutorial here:https://kb.itglue.com/hc/en-us/articles/236404927-Getting-started-with-the-IT-Glue-API
Screenshot of my code: https://imgur.com/a/zEQyV8I
Please help me loop through a CSV.
I have a script that pushes $firstname $lastname to our documentation portal via API (See code below). How can I do it so that $firtname $lastname is actually extracted from a pre-determined users.csv file which will have two columns firstname and lastname?
Thank you~!
See my code below:
$firstname = "john"
$lastname = "smith"
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("X-API-KEY", 'ITG.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
$headers.Add("Content-Type" , 'application/vnd.api+json')
$body = @{
data = @{
type = 'flexible-assets'
attributes = @{
organization_id = 708164
flexible_asset_type_id = 122389
traits = @{
firstname = $firstname
lastname = $lastname
}
}
}
} | convertto-json -depth 4
invoke-RestMethod -Uri https://api.itglue.com/flexible_assets -Method POST -Body $body -Headers $headers
Powershell script to Connect and Eject Removal Drives(SD card) from laptop
Hi Guys,
I am looking for a script which connects and ejects removal drives (SD card) from laptop. This script will run based on Windows Scheduler so at certain day of week at specific time this script will be triggered and it will connect the external drive and after certain amount of time it eject the SD card.
Idea behind this script is to use SD card for Backup purpose. Laptop backup is done on SD card (256GB) and this SD card is inserted in laptop slot all the time and its kind of risk that we keep this SD card is connected to laptop all the time due to ransomware attack, if laptop been attacked by ransomware, for sure it will attack SD card thus encrypting backup as well.
So having backup is no use if this backup is also encrypted by virus attack, so best possible way is to eject SD card as soon backup is done.
If you have better idea dealing with SD card and external hard disk then let me know.
Thanks,
Govi
Struggle with Try/Catch Blocks in Powershell
How do I get this Try/Catch to work?
$session = "C:\Users\Bill.Langley\Documents\Testing\WinSCP.com"; # This is the name of the saved session you created using the WinSCP GUI.function SFTP-FileExists
{
param([string]$filename)
$scriptblock = {C:\Users\Bill.Langley\Documents\Testing\WinSCP.com "/command" "open $session" "stat $filename" exit}
$message = Invoke-Command -scriptblock $scriptblock
$result = $($message -like "*No such file or directory*").Length -eq 0
$result
Try
{
$result = $($message -like "*No such file or directory*").Length -eq 0
}
Catch
{
ErrorMessage = $_.Exception.Message
}
}
Script to check for files for a period of time
Here is my script the script correctly checks it for the first time but I would want it to check for a 60 minutes. the loop seems to work but I cannot get to work for 60 minutes then kick out and send either a success
or failure email. Is there a simple way of ding that?
#setup loop
$TimeStart = Get-Date
$TimeEnd = $timeStart.addminutes(2)
Write-Host "Start Time: $TimeStart"
write-host "End Time: $TimeEnd"
$files = Get-ChildItem -name Z:\folder1
Do
{
$TimeNow = Get-Date
if (Test-Path "Z:\folder1\filename.csv")
{
break
}
else
{
continue
}
$files
Start-Sleep -Seconds 10
}
#While (get>>date).hour -e 5 )
# Until ($TimeNow -ge $TimeEnd)
#while (!(Test-Path "Z:\folder1\filename.csv"))
#{
#Start-Sleep -s 10
#}
Then send an email