Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

ACLs for OUs

$
0
0

Hello,

I am trying to get ACLs for each of the OUs but unable to achieve it, somehow the filter is not liking the $OU coming from for loop - any pointers pl.?

	Try{
		$OUs = (Get-REMADOrganizationalUnit -Filter *).Name
		Foreach($OU in $OUs){
		Invoke-Command -Session $ADSession -ScriptBlock {(Get-ACL $("AD:\"+(Get-ADOrganizationalUnit -filter "name -eq $OU").distinguishedname)).access | ft identityreference, accessControlType -a}
		}
	}
	Catch{"Exception while running remote AD PS commands | "+$_.Exception.Message
	}


Faizan


How to get a file shared folders including hidden folders using powershell script

$
0
0
I want to find script to get the all file share folders including hidden folders.

PowerShell Script fails to run when scheduled

$
0
0

Hello Ladies & Gentlemen,

I have a powershell script, which runs absolutely fine when I run with ISE.

When I schedule the script. It runs and fails. I am not able to figure out why the script is failing when run as schedule job.

I see the following error in the transcript logs. Although it says username and password is incorrect, it doesn't make much sense as the it's the same user under which I run script when using ISE.

PS>TerminatingError(New-Object): "Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 8000401a The server process could not be started because the configured identity is incorrect. Check the username and password. (Exception from HRESULT: 0x8000401A)."
New-Object : Retrieving the COM class factory for component with CLSID
{00024500-0000-0000-C000-000000000046} failed due to the following error:
8000401a The server process could not be started because the configured
identity is incorrect. Check the username and password. (Exception from
HRESULT: 0x8000401A).
At G:\AutomationScript\AutomateReferesh.ps1:39 char:13+ $excelObj = New-Object -Com Excel.Application+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : ResourceUnavailable: (:) [New-Object], COMExcept
   ion+ FullyQualifiedErrorId : NoCOMClassIdentified,Microsoft.PowerShell.Comman
   ds.NewObjectCommand

Here is the legendary script

# To Debug, uncomment Start-Transcript line

Start-Transcript -Path "G:\AutomationScript\transcript0.txt" -NoClobber -Force -Append

# Load .Net Assembly for Excel
Add-Type -AssemblyName Microsoft.Office.Interop.Excel

# ********** Update the $CurrentFilePath & $CurrentFileName variable with Actuals  **********#

# Current File Path of Excel
$CurrentFilePath = "G:\AutomationScript\"

# HardCode FileName
$CurrentFileName = "FileName.xls"


# Load Previous Day File
$previousDay = (Get-Date).AddDays(-1).ToString("ddMMyyyy")

# Dynamically build CurrentFileName
$CurrentFNFP = $CurrentFilePath + $previousDay + "_" + $CurrentFileName

# Test Path
if(!(Test-Path($CurrentFNFP)))
    {
        $CurrentFNFP = $CurrentFilePath + $CurrentFileName
    }

#Build Time Stamp for New FileName
$TimeStamp = (get-date -Format ddMMyyyy).ToString()

#Build New File Name
# $NewFileName = $NewFilePath.Path + "\" + $TimeStamp + "_" + $CurrentFileName

$NewFileName = $CurrentFilePath + $TimeStamp + "_" + $CurrentFileName

#Create the Excel Object
$excelObj = New-Object -Com Excel.Application

#Wait for 5 seconds then update the spreadsheet
Start-Sleep -s 5

#Make Excel visible. Set to $false if you want this done in the background
$excelObj.Visible = $false
$excelObj.DisplayAlerts = $false

#Open the workbook
$workBook = $excelObj.Workbooks.Open($CurrentFNFP)

#Wait for 5 seconds then update the spreadsheet
Start-Sleep -s 5

#Focus on the top row of the "Data" worksheet
#Note: This is only for visibility, it does not affect the data refresh
$workSheet = $workBook.Sheets.Item("ToDoList")
$workSheet.Select()

#Refresh all data in this workbook
$workBook.RefreshAll()

Start-Sleep -s 5

#Save any changes done by the refresh
$workBook.SaveAs($NewFileName)

Start-Sleep -s 5

$workBook.Close()

#Uncomment this line if you want Excel to close on its own
$excelObj.Quit()
$excelObj = $null

#write-host "Finished updating the spreadsheet" -foregroundcolor "green"
Start-Sleep -s 5

##### Email the results #####

# Date Format for Email
$Fdate = (Get-Date -Format "dd MMMM yyyy")



# Reading the username and password securely for SMTP Relay from XML
[xml]$Relay_config = Get-Content $CurrentFilePath\Relay_config.xml

$Relay_SecurePassword = ConvertTo-SecureString $Relay_config.Configuration.Password
$Relay_UserName = $Relay_config.Configuration.UserName
$Relay_UserCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Relay_UserName,$Relay_SecurePassword

# Update the $recepients with a single distribution email address or multiple email address as shown below

$recepients = "automate@domain.com"

#Send Email with attachment to DistributionList. Update the To, From, SMTPServer and, optionally Subject, Body 
Send-MailMessage -To $recepients  -From "user@domain.com" -Subject "Updated Excel for $Fdate" -Body "Kindly find updated Excel (ADP) for $Fdate" `
                 -Attachments "$NewFileName" -SmtpServer "smtp.office365.com" -Port 587 -Credential $Relay_UserCredential -UseSsl


Regards, Navdeep


script to disable all plan task in sql SQL Task Scheduler

$
0
0
Hi, Tell me how to create the script on PS, with such algorithm
1. there is a csv file
"C: \ Users \ admin \ Documents \ f.csv"
its format is now
"", "promoaction", "promoeffect1", "returneff", "promo_return", "dataload"
"1", 18557,18568,0,18557,2019-03-23 ​​17:11:28
every Monday morning, at 11 o'clock, the csv file is updated with a new row
for example, the 25th march may be so.
"", "promoaction", "promoeffect1", "returneff", "promo_return", "dataload"
“2”, 18558.18568.0.18558.2019-03-25 11:00:00

2. So, how to do, that if the  values of columns  promoaction  and promo_return  (do not touch other columns, their value is not important)
less than their values in previous date (dataload column)
 for example
"", "promoaction", "promoeffect1", "returneff", "promo_return", "dataload"
"3", 1000,18568,0,1000,2019-03-25 11:00:00 (1000 <18558)
and also, if values in   promoaction  and  promo_return  columns  ​​became  not equal, for example, in promoaction  = 1000, and in  promo_return  = 2000

all tasks  in SQL Task Scheduler (SQL agent)  in my SMSS
should not start, but simply postpone execution to the next day. for example if task must be done in 26th march, it should done in thuesday 2 apr and so on

Well, if in  promoaction  and  promo_return  values ​​are greater than on the previous date, and the values ​​ promoaction  =  promo_return 
then everything is fine, do not turn off anything

This ps should run every mon at 12 noon.

How to create such script?

if it is needed addition information

path to my SQL Agent

C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Log\SQLAGENT.OUT

name of sqlngn01(sql server 13.0.5081.1 - chlebozavod7\smith)


Install OS with DSC

$
0
0

Hi Guys,

I really hope that someone did this or that someone knows how to do it. I am in process of automating server deployment and I am using DSC to install roles and to configure servers. No problem there. But before doing it I need to install windows server OS first and that is soemthing I want to avoid. I know that we can use diffrerencing disks for this but I want to fresh install OS with DSC for every VM not to use parent disk. Is it possible to use DSC to install new VM and to install windwos server on it?

Powershell Outlokk - SendUsingAccount not working

$
0
0

I am trying to send en email with the below code.Only for the default outlook profile the code is working as expected , I need to send email from another outlook account. "sendusingaccount" property is no useful , below is the code. Please let me know any thoughts on this.

$argument=0
$outlook = New-Object -ComObject outlook.application
$appointment = $outlook.CreateItem(0)
$appointment.Subject = "subject"
$appointment.Body = "body"
$mail = "toaccount@technet.com"
$appointment.To=$mail
$appointment.SendUsingAccount="fromaccount@gmail.com"

$appointment.send()


Prathap SV

Sending email using Outlook 2016 with SendUsingAccount thru Poweshell not working

$
0
0

Im trying to send emails thru Outlook 2016 using Powershell with the following code:

$Outlook = New-Object -ComObject Outlook.Application
    foreach ($account in $Outlook.Application.Session.Accounts)
    {
        if ($account.UserName -eq "accountusername")
        {
        $thisaccount=$account
        }
    }
    $Mail = $Outlook.CreateItem(0)
    $Mail.SendUsingAccount=$thisaccount
    $Mail.To = "destination@emaildomain.com"
    $Mail.Subject = "a subject"
    $Mail.HTMLBody = "i am message<br /><br />"
    $Mail.Send()

It still sends it thru the default account. Both accounts are Exchange added accounts. In the client, manually, I can send email from both accounts so it is not a permissions issue.

Why isnt it working?

DNS Response Rate Limiting

$
0
0

Hello everyone, i have been attacked multiple times by a DDos and was wondering how to get into my DNSserverrrl through powershell. I really have no understanding on how to access it and would like to learn. When i try to run the command it gives me this error. 

PS C:\WINDOWS\system32> Get-Dnsserverrrl
Get-Dnsserverrrl : The term 'Get-Dnsserverrrl' is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
again.
At line:1 char:1+ Get-Dnsserverrrl+ ~~~~~~~~~~~~~~~~+ CategoryInfo          : ObjectNotFound: (Get-Dnsserverrrl:String) [], CommandNotFoundException+ FullyQualifiedErrorId : CommandNotFoundException

Help me, Micro-Soft Kenobi... you're my only hope.


Problem running Python scripts on PowerShell

$
0
0

I get this error when I try to run scripts in PowerShell. These scripts run fine in the command window. 




JohnB

How to use split to get the part after the first item

$
0
0

Hi Guys

for example

 $DN = "CN=LQIT010,OU=PCs_Keep_Local_Admins,OU=XXX,DC=corp,DC=bl,DC=com"

we want to split the $DN and save the part after the first "," to a new variable ,

like $partnet _DN = "OU=PCs_Keep_Local_Admins,OU=XXX,DC=corp,DC=bl,DC=com"

may i know how .

Thanks

Adding Script automatically on TaskSchduler

$
0
0

Hi 

I m new to scripting. I working on script to to add domain member to local Admin account and remove it automatically after a certain period of time.  After referring posts online i could able to add or remove accounts from a machine. I don't have programming skill and i stuck up with the step 3

Step are like

1. Get Input 

$DomainName = "xxxxx" #Read-Host -Prompt "Domain name:"
$ComputerName = Read-Host -Prompt "Computer name:"
$UserName = Read-Host -Prompt "User name:"

while(1){
Try{
$d = [datetime](read-host 'Enter any valid valid date/time')
break
    }
Catch{
Write-Host 'Not a valid date' -fore red
    }
}

$AdminGroup = [ADSI]"WinNT://$ComputerName/Administrators,group"
$User = [ADSI]"WinNT://$DomainName/$UserName,user"

2. Add the user account to local admin group

$AdminGroup.add($User.Path)

3. Create a PS file on the local machine and update it with command to remove the account

Connect-PSSession -ComputerName $ComputerName
New-Item -ItemType "directory" -Path "\\$ComputerName\c$\temp"
New-Item -ItemType "file" -Path "\\$ComputerName\c$\temp\test.ps1"
Add-Content \\$ComputerName\c$\temp\test.ps1 "$AdminGroup.remove($User.Path)"

4. Add the created Script file on the Task Scheduler to run it automatically

$Trigger= New-ScheduledTaskTrigger -At $d.ToString('yyyy-MM-dd HH:mm:ss') 
$PSUser= "NT AUTHORITY\SYSTEM" # Specify the account to run the script
$Action= New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "C:\Temp\test.ps1" 
Register-ScheduledTask -TaskName "Local Account removal" -Trigger $Trigger -User $PSUser -Action $Action -RunLevel Highest –Force 

Exit-PSSession

The output at the step 3 was not as expect . the file it getting updated as 

" System.DirectoryServices.DirectoryEntry.remove(System.DirectoryServices.DirectoryEntry.Path) "

Instead of Local admin group and the user account.

Could anyone please suggest me a solution to automated it with proper output. Or a different way to derive it ?

I m not sure how the step 4 will work

Equivalent of netAdapterBinding in powershell 2.0( windows 7)

$
0
0

Hello

I come back to you for a question 

I work in powershell 2.0 (windows 7) and I want to know the equivalent of the cmdlets :Net-adapterbinding a cmdlets to show the enables ordisables properties of interface.

Thanks

CSV AttributeEditing empty Value's

$
0
0

Hello,

I've been working on a simple script to edit several users in AD which require me to add some data in extensionattribute fields,
Not every user has data which requires this field to be filled in to my script runs if there is data present in the csv file with the correct header. However when i leave the field empty the script refuses the run, (see code below & CSV loadout below)

The question is how can i run my script that so that it will continu on even if the extensionattribute fields are left empty in the csv file. Can't seem to get it to run with out data

Import-Module ActiveDirectory           
$users = Import-Csv -Path \adtest.csv          
foreach ($user in $users)
{Get-ADUser -Filter "SamAccountName -eq '$($user.samaccountname)'" | Set-ADUser -title $($user.title) `
			-streetAddress $($user.streetAddress) `
			-OfficePhone $($user.OfficePhone) `
			-HomePage $($user.HomePage) `
			-MobilePhone $($user.Mobile) `
			-PostalCode $($user.postalCode) `
			-City $($user.city) `
            -Add @{"extensionattribute1"=$user.extensionattribute1;"extensionattribute2"=$user.extensionattribute2} `
            }

extensionattribute1,samaccountname,extensionattribute2,title,OfficePhone,Mobile,HomePage,streetAddress,postalCode,country,city
Dr,bd-tst-usr,Eng,Tile Of User Here, +123456789,+12346579 13,www.website.nl,StreetName 01,1234 AB , The Netherlands,City

concatenate variables only if defined or working with the switch parameter

$
0
0

Hi there

I have an Script which should accept parameters. At this time 0 1 or 2

Its working, but I would like to have an more elegant solution. And to understand.

param (
	[string]$first,
	[string]$second
)

Clear-Host

if ($second) {
$a = "$first", "$second"
}
else {
$a = "$first"
}

switch ($a) { 
	first {"First selected"}
	second {"Second selected"}
	default {"none"}
}

Although its working I would like to simplify it this way:

param (
	[string]$first,
	[string]$second
)

Clear-Host

$a = $first, $second

switch ($a) { 
	first {"First selected"}
	second {"Second selected"}
	default {"none"}
}

If only first ist given by the user the default parameter is shown.

This means that $a clues something togehter even if $second isnt filled.

Is there a way to avoid this.

(I hope I could describe this so anyone can understand the issue)

PowerShell module, call function in NestedModule from another NestedModule.

$
0
0

Hi,

I have a Powershell module set up and in the manifest I have declared the primary module and two nested modules.

Note: The nested modules are just simple script files. So in effect, I'm using the NestedModule concept to logically group some functions in other files.

What works

The module is setup correctly. I'm confident about this, because I even have Pester tests running on a build box without any special treatment.

Also, the Primary Module can call functions in the Nested Module files, without a problem.

What does NOT work

One Nested Module script file cannot call functions in the other Nested Module script file.

Should this work? If it should, is there some special syntax I need to use? If it should not work, then is there any recommendation about breaking scripts up into lots of files and allowing each of them to call onto the others?

I'm aware of "dot sourcing" but I'm pretty sure that using PowerShell modules is an advance on dot sourcing and so feel like there should be some way of achieving this?

Thanks.


SCRIPT - edit folder access

$
0
0

Hi everyone, 

i need a little bit of help to text a script in a domain.

I need to text a script to place in a shared folder.

The script when execute must remove the user that execute the script( the user has not admin access obviusly ) from any group he is member, so he cannot access anymore the share.

I don't have idea, neighter how to text the script with the correct variable neighter how to authorize him to remove himself without admin access.

Please help me and give a detailed reply, cause i need it :)

thanks everyone 

see u


Can't install module from private devops feed.

$
0
0

Hi,

I have problem with installing custom module from azure devops feed. I get an error Unable to find repository 'Test2'. Use Get-PSRepository to see all available repositories.

PS C:\WINDOWS\system32> Get-PSRepository

Name                      InstallationPolicy   SourceLocation
----                      ------------------   --------------
PSGallery                 Untrusted            https://www.powershellgallery.com/api/v2
Test2                     Trusted              https://pkgs.dev.azure.com/<CompanyName>/_packaging/TestArtifactsFeed/nuget/v2

PS C:\WINDOWS\system32> Install-Module -name MWS.Scripts -Repository Test2 -Credential $credsAzureDevopsServices -Force -Verbose
PackageManagement\Install-Package : Unable to find repository 'Test2'. Use Get-PSRepository to see all available repositories.
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\2.0.4\PSModule.psm1:9307 char:21
+ ...          $null = PackageManagement\Install-Package @PSBoundParameters
+                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Microsoft.Power....InstallPackage:InstallPackage) [Install-Package], Exception
    + FullyQualifiedErrorId : SourceNotFound,Microsoft.PowerShell.PackageManagement.Cmdlets.InstallPackage

*Of course i changed companyName in command.

regards 

Get all DHCP server and scope information for a domain

$
0
0

I am after some assistance in creating a powershell script to run that will allow me to get all DHCP server and scope information.  Below is what I need the script to do. Thank you.

1) It will first run this command:

  a) Get-DhcpServerInDC (write the output to a file)

  • This will list all DHCP servers in the domain

2) I then need it to loop through each DHCP server in this list (1a) and run

  a) Get-DhcpServerv4Scope –ComputerName variable (write the output to a file)

  • This will list the scopes of each DHCP server

  b) Get-DhcpServerv4OptionValue–ComputerName variable (write the output to a file)

  • This will list the server options of each DHCP server

 

3) I then need it to loop through each DHCP server (1a) and each scope (2a) and run

  a) Get-DhcpServerv4OptionValue–ComputerName (1a variable)–ScopeID (2a variable) (write the output to a file)

  • This will list the scope options of each scope


Formatting powershell results

$
0
0

Hello,<o:p></o:p>

I'm using JumpCloud powershell module for exporting command results.

I'm trying to format powershell result but unable to export all columns. 
>get-jccommandresult -byid 5c7fe06eba87c603cb1ddf4a | select name, command, system, output | format-table -wrap -autosize                     <o:p></o:p>

This works perfectly fine, but  i'm only selecting specific jccommandresult and i want to export all jccommandresults without filtering by id. But when I export, the “output” column is blank. I’m not sure if it is because of the output column format in the result displayed.

Below are the commands that I tried but couldn’t get “output” column result in exported file.

(I want the result to be in table format so that I can filter it by name and system so I didn’t use format-list. Also, I read somewhere that format-table wont work with export-csv but I tried that too.)

get-jccommandresult | Select name,command,system,output,_id | export-csv -path C:\Users\abc\Documents\JCcmdres.csv -append

get-jccommandresult | select name, command, system,output,_id | format-table -wrap -autosize |out-file -filepath C:\Users\abc\Documents\JCcmdres.csv -width 4096 -append

get-jccommandresult | select name, command, system,output,_id | Out-GridView

get-jccommandresult | Select name,output,system |convertto-csv -notypeinformation | out-file -filepath C:\Users\abc\Documents\JCcmdres.csv -width 4096 -append

DCIM Dell list - extraction data

$
0
0

Hi guys !
I found this DELL script online to connect to IDRAC and extract information.
Here only some information is extracted, I would like to extract many others such as the state of the disks etc ... but I cannot find the list of DCIM, in the specific I understood that it would be enough to change DCIM_CPUView with another specific name, the question is which !?

Does anyone have any ideas? 

$ CPU = Get-CimInstance -CimSession $ session -ResourceUri "http://schemas.dell.com/wbem/wscim/1/cim-schema/2/DCIM_CPUView";
#Enter the iDRAC IP Address

$IPaddress=Read-Host -Prompt "Enter the iDRAC IP Address"



#Enter the iDRAC Username

$Username=Read-Host -Prompt "Enter the iDRAC Username"



#Setup the CIM Session and Options

$Cimop=New-CimSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck -Encoding Utf8 -UseSsl

$Session=New-CimSession -Authentication Basic -Credential $Username -ComputerName $IPAddress -Port 443 -SessionOption $Cimop



#Retrieve & Store an instance of System,CPU,Memory,NIC,Fan,iDRAC Views

Write-Host #blank line

$System=Get-CimInstance -CimSession $session -ResourceUri "http://schemas.dell.com/wbem/wscim/1/cim-schema/2/DCIM_SystemView"

$CPU=Get-CimInstance -CimSession $session -ResourceUri "http://schemas.dell.com/wbem/wscim/1/cim-schema/2/DCIM_CPUView"

$Memory=Get-CimInstance -CimSession $session -ResourceUri "http://schemas.dell.com/wbem/wscim/1/cim-schema/2/DCIM_MemoryView"

$NIC=Get-CimInstance -CimSession $session -ResourceUri "http://schemas.dell.com/wbem/wscim/1/cim-schema/2/DCIM_NICView"

$Fans=Get-CimInstance -CimSession $session -ResourceUri "http://schemas.dell.com/wbem/wscim/1/cim-schema/2/DCIM_FanView"

$iDRAC=Get-CimInstance -CimSession $session -ResourceUri "http://schemas.dell.com/wbem/wscim/1/cim-schema/2/DCIM_iDRACCARDView"



#Store service tag & model and create a file

$Svctag=$System.ServiceTag

$Model=$System.Model

$File = New-Item -ItemType file -Name "$Svctag-$Model.txt" -Force



#Function for HW property output

function GetOutput

{

Write-Host "System Information: " -ForegroundColor Green; $System | Select Manufacturer,Model,BIOSVersionString,ServiceTag | fl

Write-Host "CPU Information: " -ForegroundColor Green; $CPU | Select FQDD,Manufacturer,MaxClockSpeed,NumberOfProcessorCores | fl

Write-Host "Memory Information: " -ForegroundColor Green; $Memory | Select FQDD, Manufacturer,Size,Speed | fl

Write-Host "NIC Information: " -ForegroundColor Green; $NIC | Select FQDD,ProductName | fl

Write-Host "Fan RPM Information: " -ForegroundColor Green; $Fans | Select FQDD,CurrentReading | fl

Write-Host "iDRAC Information: " -ForegroundColor Green; $iDRAC | Select FirmwareVersion,Model,PermanentMACAddress | fl

}

#Send output to the console and to the Svctag-Model.txt file

GetOutput | Tee-Object -FilePath $File

Viewing all 21975 articles
Browse latest View live