.csv defaulting to unicode text when saving.
PowerShell script to Auto Logoff Admin Users if login > 2 days and session is inactive
Hi All
I was wondering if anyone could help me with this script. What i am trying to do its log off all inactive user login more-than 2 days. If anyone has any insight it would be greatly appreciated.
Thanks
Aditya Dugyala
issue to display function result with custom object
Hi,
I'm newbie to do script and I don't know where is my issue.
Piece of my script :
#Roles FSMO function FSMO { AfficheTitre ("ROLES FSMO") $result=@() #maitre de domaine $domainMaster=$forest.domainnamingmaster #maitre de schema $schemaMaster=$forest.schemamaster #Récupération des rôles FSMO de chaque domaines $alldomains | foreach { $domaine=$_ #maitre d'infrastructure $infraMaster=(Get-ADDomain -Identity $domaine).infrastructuremaster #maitre RID $RIDMaster=(Get-ADDomain -Identity $domaine).RIDMaster #emulateur PDC $PDC=(Get-ADDomain -Identity $domaine).PDCEmulator $obj=[PSCustomObject]@{ Domaine=$domaine MaitreDeDomaine=$domainMaster MaitreDeSchema=$schemaMaster maitreInfrastructure=$infraMaster maitreRID=$RIDMaster emulateurPDC=$PDC } $result+=$obj } return $result } #Permet d'afficher un titre encadré function AfficheTitre ($titre) { $nbchar=$titre.length $charhaut="#" $charbas="#" $nbsymbole=100 $debutEcriture=[math]::truncate(($nbsymbole-$nbchar)/2)-1 $return+=write-host "" $return+=write-host $($charhaut*$nbsymbole) $return+=write-host $($charhaut*$nbsymbole) $return+=write-host $(" " * $debutEcriture) $titre $(" " * $debutEcriture) $return+=write-host $($charbas*$nbsymbole) $return+=write-host $($charbas*$nbsymbole) $return+=write-host "" return($return) } #Récupération des niveaux fonctionnels function NiveauFonctionnel { AfficheTitre("NIVEAU FONCTIONNEL") $result=@() #niveau fonctionnel forêt $ffl=$forest.forestmode #niveau fonctionnel domaine $alldomains | foreach { #nom du domaine $domaine=$_ #niveau fonctionnel du domaine $dfl=(Get-ADDomain -Identity $domaine).domainmode $obj=[PSCustomObject]@{ Domaine=$domaine NiveauFonctionnelForet=$ffl NiveauFonctionnelDomaine=$dfl } $result+=$obj } return $result } function main { $forest=get-adforest $domain=get-addomain $alldomains=$forest.domains $allDCs = $forest.Domains | foreach { Get-ADDomainController -Filter * -Server $_ } NiveauFonctionnel FSMO } main
My issue is FSMO doesn't display what I want.
If I comment on main function "NiveauFonctionnel" FSMO displays result I want.
I have this issue with all my powershell function where I created custom object.
Can you explain me what I do wront pls.
Merci de marquer comme reponses les interventions qui vous ont ete utile.
Restore-SqlDatabase fails when specifying -Credential
Hi
Im getting an error when running the below PowerShell. I need to run as a specific user, any ideas? I have tried replacing localhost for the server name but still no luck. The error i get is:
Restore-SqlDatabase : Failed to connect to server localhost.
$password = ConvertTo-SecureString '*********' -AsPlainText -Force $cred = New-Object System.Management.Automation.PSCredential ('testadmin', $password) #Relocate the Database file $RelocateData = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile("DB_training", "S:\Data\Testing.mdf") #Relocate the Log file $RelocateLog = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile("DB_training_Log", "L:\Log\Testing.ldf") #Restore the template database Restore-SqlDatabase -ServerInstance "localhost" -Database "Testing" -Credential $cred -BackupFile "C:\Template\backup_V7_201810011430.bak" -RelocateFile @($RelocateData,$RelocateLog)
Thanks
Shane
Getting SQL version info from list of server names
I am wondering if there is a powershell script I can run against a .txt file with server names in it that will return the version of SQL on that list of servers. Any help is appreciated.
Thanks.
Chad Guiney
Meaning of powershell script script that uses $variable.Id
I am new to Powershell and Azure and I am trying to understand the scripts I have been written. The scripts are pretty standard in that they build up the contents of variables and then execute them SO to understand what is happening I am trying to recreate what the command line will look like at the bottom of thre script
New-AzureRMVM -VM $MyVM -ResourceGroupName $rg -Location $region
Working back up the scripts and replacing the variables with their contents.
for example:
$vNic = New-AzureRmNetworkInterface -Name $nicName -ResourceGroupName $rg -Location $region -Subnet $subnet
the vNic variable is later seen here:
$MyVM = Add-AzureRmVMNetworkInterface -VM $MyVM -Id $vNic.Id
What purpose is the .Id suffix? I have seen it elsewhere.
Also is there a way to run a powershell script in debug mode to see the resolve variables bit not execute
Delegate Rights to Add Computer Objects to a OU for one User with Powershell
Hi,
I would like to delegate this complex rights via Powershell.
The OU Name is OU=RDSH,OU=Clients,DC=XXX,DC=dom
The Username: svc_vm_join_ad
Access Right:
Reset password applied to Descendant computer objects
Read/write all properties applied to Descendant computer objects
I hope this description is ok.
I have write this part but I don't know that I must write for the user permission:
Import-Module ActiveDirectory $rootdse = Get-ADRootDSE $domain = Get-ADDomain $guidmap = @{ } Get-ADOject -SearchBase ($rootdse.SchemaNamingContext) -LDAPFilter '0(schemaidguid=*)' -Properties lDAPDisplayName, schemaIDGUID | ForEach-Object{ $guidmap[$_.lDAPDisplayName] = [System.GUID]$_.schemaIDGUID } $ou = Get-ADOrganizationalUnit -Identity 'OU=RDSH,OU=Clients,DC=XXX,DC=dom' -Server XXX-dc01.XXX.dom $oupath="AD:\$($ou.DistinguishedName)" $sid=(Get-ADGroup "RDSH").SID $p = New-Object System.Security.Principal.SecurityIdentifier($sid) $acl = Get-ACL $oupath $ace=New-Object System.DirectoryServices.ActiveDirectoryAccessRule($p, 'WriteProperty,WriteDacl', 'Deny', 'Descendents', $guidmap['user']) $acl.AddAccessRule($ace) $acl|Set-ACL $oupath
HELP!! Newbie is stuck
Hi guys,
I've googled this as much as i can handle and without going cap in hand to the resident powershell gurus (who are insanely busy), i need help please.
We have setup many groups (900+) with the group scope of Domain Local, instead of Global. I know we can powershell them into universal groups, then into global groups, but i would like to pull all the groups into a .CSV and then run the command to convert from there.
How do i get a list of all groups with a specific naming convention, that have a specific Group scope out into the CSV?
e.g - GL_
Domain local
Thanks
How to get all groups and members of a nested group into csv format with Export-Csv
Hello
I am new to Powershell scripting so i need a little help :)
I have a AD Group which have many nested groups with members in each group
I want to get a csv file with name of the nested group inside a group and the name of the member in the nested groups with their emai address
I have tried with PS script under but i am not able to get file formated correctly with one colum for group name and one for name and one for email so i can import it into Excel
get-ADGroupMember "ADgroup" | ?{$_.ObjectClass -eq "Group"} | %{Write-output $_.Name;Get-ADGroupMember $_ | Select-Object Name} |format-list | Out-File c\temp\groups.csv
If anyone could help me i would appreciate it.
Morten
mh
Active Directory Account Expiration Notification to Managers
Active Directory Account Expiration Notification to Managers
Hello script gurus - I wanted to send an automatic email notification to managers pertaining to their contractors that has an end date on their AD accounts. The script that I found had most of the features I'm looking for. However need assistance on how to add the following into the script.
- Add additional message into the body of the email.
- Exclude the "past" expired accounts from the report.
When the report runs it sends the email to managers just fine however, we've noticed that it is including the ones that are already expired. We want to only send the ones that are expiring within 30 days from this date forward.
Here's the script I found referenced in this forum:
https://social.technet.microsoft.com/Forums/windows/en-US/9d080c24-b2a2-4d9b-b50b-ca7fb9d95a91/account-expiration-email-notification?forum=winserverpowershell&prof=required
Thank you for your time and appreciate any assistance!
Cheers.
Get-ADUser -Filter * -Properties directReports,EmailAddress | ForEach {
$body = @()
If ($_.directReports) {
$managerEmailAddress = $_.EmailAddress
$_.directReports | ForEach {
$userDetails = Get-ADUser $_ -Properties AccountExpirationDate
If ( $userDetails.AccountExpirationDate ) {
If ( $userDetails.AccountExpirationDate -lt (Get-Date).AddDays(30) ) {
$sendEmail = $true
$props = [ordered]@{
Username=$userDetails.SamAccountName
'Account Expiration Date'=$userDetails.AccountExpirationDate
}
$body += New-Object PsObject -Property $props
}
}
}
}
If ($sendEmail) {
$body = $body | Out-String
Send-MailMessage -From 'email@domain.com' -To $managerEmailAddress -Subject 'Account Expiration Report' -Body $body -SmtpServer 'mail.domain.com'
}
$sendEmail = $false
}
# Generic check for users with no manager
$bodyNM = @()
Get-ADUser -Filter * -Properties AccountExpirationDate,Manager | ForEach {
If ( !$_.Manager ) {
If ( $_.AccountExpirationDate) {
If ($_.AccountExpirationDate -lt (Get-Date).AddDays(30) ) {
$sendEmailNM = $true
$propsNM = [ordered]@{
Username=$_.SamAccountName
'Account Expiration Date'=$_.AccountExpirationDate
}
$bodyNM += New-Object PsObject -Property $propsNM
}
}
}
}
If ($sendEmailNM) {
$bodyNM = $bodyNM | Out-String
Send-MailMessage -From 'email@domain.com' -To 'helpdesk@domain.com' -Subject 'Account Expiration Report' -Body $bodyNM -SmtpServer 'mail.domain.com'
}
Cheers, DB
No such interface supported
Hi All,
When I am running a below powershell command I am getting an error message as "No such interface supported";
gwmi win32_operatingsystem -ComputerName "hostname"
I am able to access target host through RDC from the source host. I can telnet the host and its listening on 135. All windows firewalls are disabled. Trying with Admin account.
Any idea how to get rid of this error?
escaping single quotes inside a variable
I am currently using scom to execute a powershell command which passes the scom alert description into the script. the alert description variable in scom has to be surrounded by single quotes to pass over however the containing string also contains single quotes so is being cut short.
anyone have any suggestions on how I can get powershell to ignore the single quotes inside the string ?
command being used is "C:\SCOM\Scripts\syslogcreateevent.ps1" '$Data/Context/DataItem/AlertDescription$'
with the string variable being Alarm event description: testing single ' quotes'
Richard Scott
Script to remove System Center Agent
I have this script to remove the system center agent, but the Next options pop up as if I am manually removing the agent by choosing Change instead of Uninstall. I tried using the quiet option but that did not work. How can I write the script so that it actually uninstalls with no popups as if I am changing the agent?
$SysCtr2007=Get-ChildItem-PathHKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall|`
Get-ItemProperty| Where{$_.DisplayName-match"System
Center Operations Manager 2007 R2 Agent"}
ForEach
( $verin$SysCtr2007) {
If($ver.UninstallString ) {
$uninst=$ver.UninstallString
Start-Processcmd-ArgumentList"/c$uninst/quiet /qn "
}
}
script to overwrite a file
Hi,
We have a client which has this application. The vendor of the app advised us to change a particular xml file in all computers. I was thinking of using a software deployment to run a powershell script to overwrite the existing filename
Thanks
Jeff
How to run several batch files in parallel and wait for them all to complete before continuing - with arguments
i have a bunch of processes i would like to run in parallel using powershell.
I found a bunch of examples where i can do this
$scripts = 'c:\j1.bat', 'c:\j2.bat','c:\j3.bat'$scripts |%{ Start-Job –scriptblock (iex "[Scriptblock] { & '$_' }") } | wait-job
However, i would like to send arguments to the same batch file.
e.g.
$scripts = 'c:\j.bat 1', 'c:\j.bat 2','c:\j.bat 3'
$scripts |%{ Start-Job –scriptblock (iex "[Scriptblock] { & '$_' }") } | wait-job
Is there an argument to pass an argument? When i run above it fails.
Thanks in Advance!
Deleting folders that are empty or only contain text files - cannot figure out why this doesn't work
The titles pretty much says it- I want to delete folders in a path that are empty or only have text files. I've played around with a bunch of variations, but cannot figure out why they don't work. The problem is they delete folders with a subfolder with files in it.
$tdc="C:\My Shared Folder"
Get-ChildItem $tdc -Recurse -Directory | Where-Object {(-not (Get-ChildItem $_.FullName -Recurse -Exclude '*.txt')) } | Remove-Item -Force -Verbose -WhatIf -Recurse
I also tried this:
$tdc="C:\My Shared Folder"
Get-ChildItem $tdc -Recurse -Directory | Where-Object {(-not (Get-ChildItem $_.FullName -Exclude '*.txt')) -and ($_.GetDirectories().length -eq 0) } | Remove-Item -Force -Verbose -WhatIf -Recurse
What am I doing wrong?
Runsapce use of System.Net.Sockets.tcpclient class
I am encountering an issue where the below code is returning incorrect results when running via a runspace. The same code executes perfectly when executed in a single instance. The verbiage on MSDN says that it is thread safe, am I correct in thinking this means, 'ok to run multiple instances of the class on separate threads' in the same winstation instance ?
function testport { param ( $hostname, $port, $timeout ) $client = New-Object System.Net.Sockets.TcpClient $beginConnect = $client.BeginConnect($hostname,$port,$null,$null) $stoptime = (get-date).AddMilliseconds($timeout) try { while ((-not $client.Connected) -and ((Get-date) -lt $stoptime)) { Start-Sleep -milli 50 $open = $false } if ($client.Connected) { $open = $true $client.EndConnect($beginConnect) } } finally { $client.Dispose() } return $open }
Start-Job Powershell
Hello Experts,
I need some help. i am running this script in order to apply permissions in existing shares however it taking so long as it taking permissions and share names from CSV file one by one. i want to convert this shell script as job so it will run multiple jobs withing same thread. i am not pro in script. can someone please help me with this.
Thanks,
Ron
CSV File :
folder | full_control | modify | read_execute |
$path = ""
$csvFile = ""
$logfile = ""
$existing = Import-CSV $csvFile
$Error.Clear()
function DoPermissions
{
param( $permissionGroup, $folder, $level)
$toAdd = $permissionGroup -split ";"
Write-Host $folder
foreach ($item in $toAdd)
{
$acl = (Get-Item $folder).GetAccessControl('Access')
$ar = New-Object System.Security.AccessControl.FileSystemAccessRule($item, $level, 'ContainerInherit,ObjectInherit','None','Allow')
$acl.SetAccessRule($ar)
Set-ACL -path $folder -AclObject $acl
}
}
foreach ($folder in $existing)
{
$fullPath = $folder.folder #$path + $folder.folder
if ((Test-Path $fullPath))
{
$fAcl = Get-Acl -Path $fullPath
$fAcl.SetAccessRuleProtection($true, $true)
Set-Acl -Path $fullPath -AclObject $fAcl
if ($folder.full_control) {DoPermissions $folder.full_control $fullPath "FullControl"}
if ($folder.modify) {DoPermissions $folder.modify $fullPath "Modify"}
if ($folder.read_execute) {DoPermissions $folder.read_execute $fullPath "ReadAndExecute"}
}
else
{
"$($folder.folder) doesn't exist" | Out-File -FilePath $logfile -Append
}
}
$Error | Out-File -FilePath $logfile -Append
Need to run Powershell script which placed on different server
Hello,
I want to call powershell script from Server A, Where script is placed in server B.
Anyway should be fine from batch file or any script..
Please suggest.
Thank You,
Avis
Not getting correct .CSV export after running script
I have a question about running scripts with a CSV output. I am running the script below with | out-file c:\scripts\last logon\results.csv and after it runs I get a csv file with everything in one column. Is there a different syntax I should use for this?
Thanks in advance.....
# PSLimitedLastLogon.ps1# Specify file of computer NetBIOS names.
$File = "c:\scripts\Last Logon\Computers.txt"
$Domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.PageSize = 200
$Searcher.SearchScope = "subtree"
$Searcher.SearchRoot = "LDAP://$Domain"
$Searcher.PropertiesToLoad.Add("sAMAccountName") > $Null
$Searcher.PropertiesToLoad.Add("lastLogonTimeStamp") > $Null
# Read computer names.
$Computers = (Get-Content $File)
# Filter on computers listed in file.
$Filter = "(|"
ForEach ($Computer In $Computers)
{
# sAMAccountName of computer is NetBIOS name with trailing "$" character.
$Filter = $Filter + "(sAMAccountName=$Computer`$)"
}
$Filter = $Filter + ")"
$Searcher.Filter = $Filter
$Results = $Searcher.FindAll()
ForEach ($Result In $Results)
{
$Name = $Result.Properties.Item("sAMAccountName")
$LL = $Result.Properties.Item("lastLogonTimeStamp")
If ($LL.Count -eq 0)
{
$Last = [DateTime]0
}
Else
{
$Last = [DateTime]$LL.Item(0)
}
If ($Last -eq 0)
{
$LastLogon = $Last.AddYears(1600)
}
Else
{
$LastLogon = $Last.AddYears(1600).ToLocalTime()
}
"""$Name"",$LastLogon"
}
Chad Guiney