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

Get-ADuser from CSV and retrieve the DistinguishedName Attribute sent to a new CSV

$
0
0

Title kind of says it all, but I'm looking to use a csv that I have created with a column for Name, being the USERID from AD. I want to leverage this data and get back the DistinguishedName attribute from AD and pipe that to a new csv. These users don't share a common AD group or OU so I can't search it that way. I've tried this below. 

Get-Content C:\VMs.txt | Get-ADUser -properties DistinguishedName| Select-Object DistininguishedName | Out-File -filepath c:\temp\output.txt


Certificate remote request

$
0
0

Hi forum,

You have helped me quite few times, so once again I'm asking smarter people if there's a way to :

-remotly request for machine certificate?

What I'm trying to do is to automate IIS web deployment, and one of steps is to create bindings to https and it's certificate.

Template is set to autoenroll, permision are granted, locally I can request for cert and I'm getting it.

But if I try to wrap this pice of script into invoke, then....nothing good come out of it.(error 80070057)


$scriptToExecute =
{
# certificates 1-way
set-location 'cert:\localmachine\my'
#$cert = get-certificate -template WebServer -credential $cred -dnsname test1.demo1.ad.local -url ldp: -subjectname ("cn="+"test1") -certstorelocation cert:\localMachine\My
}
Invoke-Command -ComputerName hosts -Credential $Cred -ScriptBlock $scriptToExecute

Powershell RDS Installed License Report - Sent to email

$
0
0

Hi Experts, I have a PowerShell command that will get an output of how many CAL's I have installed and how many are used. Instead of write-host (to screen), I'd like to change it to a variable so that I can add it to the body of an email and have it run on a schedule and email me weekly reports on usage (Available CAL's) I would like to have the variable something like $report as shown in the $body of the email, this is what I have so far..

$fileName = (Invoke-WmiMethod Win32_TSLicenseReport -Name GenerateReportEx).FileName
$summaryEntries = (Get-WmiObject Win32_TSLicenseReport|Where-Object FileName -eq $fileName).FetchReportSummaryEntries(0,0).ReportSummaryEntries
$Report = ($summaryEntries|ForEach {Write-Host $_.ProductVersion $_.TSCALType "Installed:" $_.InstalledLicenses "Issued:" $_.IssuedLicenses})

$EmailTo = "itgroup@microsoft.com"
$EmailFrom = "admin@microsoft.com"
$user = 'admin@microsoft.com'
$password = Unprotect-CmsMessage -Path C:\Scripts\Powershell\EncryptedSecret.txt
$Subject = "Alert: CAL USAGE "
$Body = "Alert; $Report"
$SMTPServer = "smtp@contonso.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
$SMTPClient.EnableSsl = $false
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($user, $password)
$SMTPClient.Send($SMTPMessage)

I have used both parts of this script separately, but I would like to join them together, to make more useful. I have tried every way I know how in my limited experience, hopefully it is possible. Thanks in advance..


Powershell StackedColumn100 graph

$
0
0

Hello,

I was finally able  to generate a StackedColumn100 graphic from powershell :)
This is the result for two data series:

Used space:
$ProcessList = "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","Z","X"
$Placeholder = 142,130,147,143,156,47,28,148,110,120,107,117,133,142,119,111,146,124,152,90,126,147,148,161

Free space:
$ProcessList = "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","Z","X"
$Placeholder = 28,49,22,39,24,132,151,22,61,59,72,62,38,28,52,59,24,47,18,89,44,24,36,23

This represent Used and Free space for Storage devices A,B,C...
What I'm unable to figure out is how to print as labels the data from $placeholder and not the % value
For example for the first column:
A Used Space = 142
A Free Space = 28
142+28=170 (170 is 100%)
Used space = 83.53% - printed as label
Free space = 16.47% - printed as label

Instead %83.53 & %16.47, I would like to print 142 and 28.
I've used for each series .IsValueShownAsLabel = $true but this will display the %value and not the data value

Thank you for any suggestion!

Create firewall rule even if path is not existing

$
0
0

Hello

I have here a script from Microsoft to create two rules in the Firewall, but after testing, teams application has to be installed, which are not the case for all our corporate devices. Is it possible to change this powershell ,and create the two rules, even if the path doesn’t exist?

Thank you for your help

$users = Get-ChildItem (Join-Path -Path $env:SystemDrive -ChildPath ‘Users’) -Exclude ‘Public’, ‘ADMINI~*’
if ($null -ne $users) {
foreach ($user in $users) {
$progPath = Join-Path -Path $user.FullName -ChildPath “AppData\Local\Microsoft\Teams\Current\Teams.exe”
if (Test-Path $progPath) {
if (-not (Get-NetFirewallApplicationFilter -Program $progPath -ErrorAction SilentlyContinue)) {
$ruleName = “Teams.exe for user $($user.Name)”
“UDP”, “TCP” | ForEach-Object { New-NetFirewallRule -DisplayName $ruleName -Direction Inbound -Profile Any -Program $progPath -Action Allow -Protocol $_ }
Clear-Variable ruleName
}
}
Clear-Variable progPath
}
}

Table is automatically colour-filling rows

$
0
0

I am inserting tables in a large MS Word document and after many successful events, now every time I:

  • create a new table;
  • add a new row to an existing table;
  • copy an existing table to a new locations;

the rows in the table are assuming a mid-blue colour which I am unable to remove - furthermore, I cannot "no fill colour" or alternatively fill-colour these rows...

how do i make test path to a registry key

$
0
0

Hello all,

I have a very interesting problem, in my machine I have a registry key: "HKEY_LOCAL_MACHINE\SOFTWARE\Opal\Insight\SEM\SRA\Clock 1/3"

how can i test that it exists via PowerShell? 

I have already tried the following:

1. Test-Path -Path 'HKEY_LOCAL_MACHINE\SOFTWARE\Opal\Insight\SEM\SRA\Clock 1/3'

2. Adding escape charecters like:

   a. Test-Path -Path 'HKEY_LOCAL_MACHINE\SOFTWARE\Opal\Insight\SEM\SRA\Clock 1`/3'

   b. Test-Path -Path 'HKEY_LOCAL_MACHINE\SOFTWARE\Opal\Insight\SEM\SRA\Clock 1\/3'

   c. Test-Path -Path 'HKEY_LOCAL_MACHINE\SOFTWARE\Opal\Insight\SEM\SRA\Clock 1/3'

nothing seems to work

Thank you in advance

Boris

Using variables while running Powershell script

$
0
0

Hello to all, 

I am trying to learn how to use variable in a command. 

I have a script with number of variables and i want the user to choose which variable to use when running the script. 

example: 

File.ps1 /variable

Where can i find documentation about this? 

example to powershell script that uses this method. 

https://gallery.technet.microsoft.com/scriptcenter/Remove-Expired-Superseded-

Clean-CMSoftwareUpdateGroup.ps1 -SiteServer CM01 -SUGName "Security and Critical Updates" -ShowProgress -RemoveContent -Verbose

Thank you

Amir


How to extract the users list via Powershell script

$
0
0

Hi,

Using powershell script, I want to pull the members of one specific security group/distribution list in excel file.


Some Question Of Powershell

$
0
0
powershell run install-module shows:

install-moudule:: The "install-moudule" item cannot be recognized as the name of a cmdlet, function, script file, or executable program. Please check the spelling of the name if
Include the path, make sure the path is correct, and try again.
Location Line: 1 Character: 1
+ install-moudule -Name AzureAD
+ ~~~~~~~~~~~~~~~~~~
     + CategoryInfo: ObjectNotFound: (install-moudule::String) [], CommandNotFoundException
     + FullyQualifiedErrorId: CommandNotFoundException

When I run cmd and then run this command, it shows: install is not an internal or external command, nor a runnable program, or batch file.

So what's going on? PS version 3.0, run with administrator rights.

By the way, how does win8 upgrade ps version now? The downloads are not applicable to your computer updates.

It is not clear why the staff gave the address of the US region, if there is a problem with the translation, please see the original text below.

powershell 运行 install-module 显示:

install-moudule: : 无法将“install-moudule”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果
包括路径,请确保路径正确,然后再试一次。
所在位置 行:1 字符: 1
+ install-moudule -Name AzureAD
+ ~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (install-moudule::String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

当我运行cmd 然后再运行这个命令是,就显示: install 不是内部或外部的命令,也不是可运行的程序,或批处理文件。

所以这是怎么回事? PS 版本3.0,管理员权限运行的。

顺便问下,win8现在要怎么升级ps版本?下载下来全都不适用于你的电脑更新。

Powershell script output to JSON - formatting issues

$
0
0

Hi,

I'm hoping someone can help me.

I've produced a script to export data from a SQL view, and to convert it into JSON, however I'm having issues with the format of the exported JSON.

Here is my code:

$sqlCmd = @"
SELECT * 
FROM SQL_VIEW"@

$results = Invoke-SqlCmd -Query $sqlCmd -ServerInstance "SQL_SERVER_INSTANCE"

$data = foreach ($grp in $results | Group-Object -Property idnumber){
	[ordered]@{
	data = @($grp.Group[0] | Select email,firstname,surname,idnumber,title,gender,nino)
	courses = @($grp.Group | Select courses.projectid,courses.courseid,courses.startdate)
	}
}

$body = ConvertTo-Json -InputObject $data | Out-File "c:\test\import.json"

The output needs to be as follows:

[
   {
     data: [
           {"email":"someone@somewhere.com","firstname":"John","surname":"Smith","idnumber":"1234","title":"Mr","gender":"M","nino":"AB123456C"
           }
           courses: [
                    {"projectid":"2222","courseid":"9999","startdate":"01/01/1900"
                    }
                    ]
           }
           ]
     data: [
           {"email":"someone@somewhere.com","firstname":"Jack","surname":"Smith","idnumber":"4321","title":"Mr","gender":"M","nino":"AB123456C"
           }
           courses: [
                    {"projectid":"2222","courseid":"9999","startdate":"01/01/1900"
                    }
                    ]
           }
           ]
   }
]

However, the output produced is this:

[
    {"data":  ["@{email=someone@somewhere.com; firstname=John; surname=Smith; idnumber=1234; title=Mr; gender=M; nino=AB123456C}"
                 ],"courses":  ["@{courses.projectid=2222; courses.courseid=9999; courses.startdate=01-01-1990}"
                    ]
    },
    {"data":  ["@{email=someone@somewhere.com; firstname=Jack; surname=Smith; idnumber=4321; title=Mr; gender=M; nino=AB123456C}"
                 ],"courses":  ["@{courses.projectid=2222; courses.courseid=9999; courses.startdate=01-01-1990}"
                    ]
    },
]

Is there something else I need to do in order to get the JSON formatting correct?

Powershell MSOnline Module load failure from SSIS

$
0
0

I have an SSIS package that calls a powershell function to set MSOL User Licensing.  The function imports the MSOnline module and establishes a Connect-MsolService session before running Set-MsolUser and Set-MsolUserLicense commands. The function works perfectly when run from powershell or passed through from a CMD shell, but returns the following error when run via an Execute Process Task in my SSIS package:

The 'Set-MsolUser' command was found in the module 'MSOnline', but the module could not be loaded.

This process worked without error until recently.

Any ideas offered to resolve will be appreciated.

Signing powershell script with a certficate

$
0
0

Hi there,

I'd like to sign a powershell script with a certificate but I always receive an error message. When I try using Set-AuthenticodeSignature I get this Set-AuthenticodeSignature : Impossible de signer le code. Le certificat spécifié ne convient pas pour la signature de code. I tried using a selft certificate and a publique certificate issuer by RapidSSL. I am getting certificates from My and Root folders.

Json payload from Powershell scripts not pushed to Terrafrom

$
0
0


This is my Terraform script file :

provider "external" {
  version = "1.2.0"

}


# Call Powershell.exe and pass in 'foo' and 'bar'
data "external" "powershell_azure" {
  program = ["Powershell.exe", "./azure.ps1"]
  query = {  
client = "$client_id"
secret = "$client_secret"
subscription = "$subscription_id"
tenant = "$tenant_id"    
  }
}

data "template_file" "azure" {
  template = "${filebase64("${path.module}/azure.ps1")}"
  vars = {
    client_id = "${data.external.powershell_azure.result.client}"

    client_secret  = "${data.external.powershell_azure.result.secret}"

    subscription_id = "${data.external.powershell_azure.result.subscription}"

    tenant_id = "${data.external.powershell_azure.result.tenant}"
  }
}




Am passing Jsonpayload from powershell to Terraform. The Jsonpayload is not be accessed by Terraform. How do i resolve it  

Getting the Active directory AD groups and user names with Powershell

$
0
0

Hi Everyone,

Can you please suggest me in listing the few AD groups and corresponding user list to an SQl table or to a file please?

I have more than 100 AD groups , I just need to pull 10 active directory groups based on some static text value in the group name and then list the corresponding users for each group.

ex : Get-AdGroup contains the list as A, B, C, D, E , F , G etc..

we just need  2 columns as below contains only few AD group information out of many groups.

ADGroupName, Username

A     , John

A     , Robert

B     , xx

G     , YY

G     ,  ZZ

G     , Stuart


help with a script

$
0
0

Hello-

I was tasked with running a script against a list of servers to filter for files on each drive and then locate any files that might have passwords in clear text.  However, the script will either A.) only return results for the local server, or B.) produce no output at all.  Even though the script is running without error, the output folder has nothing in it.

snippet below - the paths have been masked

$servers = Get-Content -Path c:\<scriptpath>\servers.txt

foreach ($server in $servers) {

Invoke-Command -ComputerName $server -ScriptBlock{Get-ChildItem c:\,d:\,e:\ -rec -include @("*.ps1","*.txt","*.bat") -Force -erroraction silentlycontinue | select-string '(credentials) | (pscredential) | (password)' } 

Export-Csv C:\<outputfolder>\$server-finder-$(get-date -f MM-dd-yyyy).csv -NoTypeInformation

}

What I need to have happen - run this script from my computer so that it goes to every server in the list, runs the query to find a matching string, then generates a csv file for EACH server (which is why the $server variable is in the output path) back on my system with the results of what was matched.   The command itself seems to work fine and return the results.....I'm trying to figure out how to give the script a list of servers to go out and do this on its own.  What am I missing here?

fyi- i do not do much with powershell scripting per se, this is a new challenge for me.


Got error "Object reference not set to an instance of an object"

$
0
0

I got error "Object reference not set to an instance of an object" error with the following (slim) PS scripts -

==========================

Import-Module WebAdministration

$webSites = Get-ChildItem IIS:\Sites

for ($i=0;$i -le $webSites.Count-1;$i++)
{
    func1 ($webSites[$i].Name)
}

function func1 ([String]$site_name)

{

    func2 -siteName $site_name -para2 "mystring"

}

function func2

{

Param

(

[Parameter(Mandatory=$True, Position=0)]

[String]$siteName,

[Parameter(Mandatory=$True, Position=1)]

[String]$para2

)

#do things with $siteName and $para2....

}

=============================

The error is from the bold line, and it seems from the usage of '$site_name'.

Can anyone help point out what's wrong here and how to fix it?

Thanks in advance


array and array list with custom object

$
0
0

Hello,

I would like to know what is/are the best possibility for this function :

(write-ezlog is function from a powershell module to provide log in a file)

$allDCs = (Get-ADForest).Domains | Foreach-Object { Get-ADDomainController -Filter * -Server $_ } | Sort-Object name


function Get-AllDCHardware {

$obj=@() Write-EZLog -Category INF -Message "### Start Get-AllDCHardware ###" $allDCs | Foreach-Object { Write-EZLog -Category INF -Message "Process Domain controller $($_.hostname)" $obj+=[PSCustomObject]@{ ServerName = $_.name LogicalCPUNb = (Get-CimInstance win32_computersystem -ComputerName $_.hostname).numberOfLogicalProcessors 'RAM(GB)' = (Get-CimInstance win32_computersystem -ComputerName $_.hostname).TotalPhysicalMemory/1GB -as [INT] Type = (get-CimInstance win32_computersystem -ComputerName $_.hostname).model OS = (Get-CimInstance Win32_OperatingSystem -ComputerName $_.hostname).caption LastBoot = (Get-CimInstance -ClassName win32_operatingsystem -ComputerName $_.hostname).lastbootuptime } Write-EZLog -Category INF -Message "object created. ServerName = $($obj.ServerName) ; LogicalCPUNb = $($obj.LogicalCPUNb) ; RAM(GB) = $($obj.'RAM(GB)')" Write-EZLog -Category INF -Message "Type = $($obj.Type) ; OS = $($obj.OS) ; LastBoot = $($obj.LastBoot)" Write-EZLog -Category INF -Message "End Domain controller $($_.hostname)" } $obj Write-EZLog -Category INF -Message "### End Get-AllDCHardware ###" }

or

function Get-AllDCHardware
{
    $obj=[System.Collections.ArrayList]@()
    Write-EZLog -Category INF -Message "### Start Get-AllDCHardware ###"
    $allDCs | Foreach-Object {
        Write-EZLog -Category INF -Message "Process Domain controller $($_.hostname)"
        $obj.add([PSCustomObject]@{
            ServerName = $_.name
            LogicalCPUNb = (Get-CimInstance win32_computersystem -ComputerName $_.hostname).numberOfLogicalProcessors
            'RAM(GB)' = (Get-CimInstance win32_computersystem -ComputerName $_.hostname).TotalPhysicalMemory/1GB -as [INT]
            Type = (get-CimInstance win32_computersystem -ComputerName $_.hostname).model
            OS = (Get-CimInstance Win32_OperatingSystem -ComputerName $_.hostname).caption
            LastBoot = (Get-CimInstance -ClassName win32_operatingsystem -ComputerName $_.hostname).lastbootuptime
        })
        Write-EZLog -Category INF -Message "object created. ServerName = $($obj.ServerName) ; LogicalCPUNb = $($obj.LogicalCPUNb) ; RAM(GB) = $($obj.'RAM(GB)')"
        Write-EZLog -Category INF -Message "Type = $($obj.Type) ; OS = $($obj.OS) ; LastBoot = $($obj.LastBoot)"
        Write-EZLog -Category INF -Message "End Domain controller $($_.hostname)"
    }
    $obj
    Write-EZLog -Category INF -Message "### End Get-AllDCHardware ###"
}

If I wouldn't want to log it I would have only to do this

function Get-AllDCHardware { $allDCs | Foreach-Object { [PSCustomObject]@{ ServerName = $_.name LogicalCPUNb = (Get-CimInstance win32_computersystem -ComputerName $_.hostname).numberOfLogicalProcessors 'RAM(GB)' = (Get-CimInstance win32_computersystem -ComputerName $_.hostname).TotalPhysicalMemory/1GB -as [INT] Type = (get-CimInstance win32_computersystem -ComputerName $_.hostname).model OS = (Get-CimInstance Win32_OperatingSystem -ComputerName $_.hostname).caption LastBoot = (Get-CimInstance -ClassName win32_operatingsystem -ComputerName $_.hostname).lastbootuptime }

} }



Merci de marquer comme reponses les interventions qui vous ont ete utile.



Unexpected token error when executing script

$
0
0

Hello All,

I'm having issues running a script and I've just included the relevant snippets below..

Below are variables declared and the assigned values.

$path = "\\abcdef.eu.domain.com\Reports"
$mp_address = "server.domain.com"
$site_code = "PR2"

The script throws an error a

$path\ccmsetup.exe /mp:$mp_address SMSSITECODE=$site_code

Error output below :

PS C:\Users\M123\Documents> .\SCCM_Client.ps1
At C:\Users\M123\Documents\SCCM_Client.ps1:87 char:7
+     $path\ccmsetup.exe /mp:$mp_address SMSSITECODE=$site_code
+          ~~~~~~~~~~~~~
Unexpected token '\ccmsetup.exe' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : UnexpectedToken

Any advice please?

Full script is available at the below location

https://gallery.technet.microsoft.com/SCCM-Client-Health-Check-7a17d672#content

Thank You.

SAMUEL


SamSV

Keeping specific files in a folder after deleting files older than 7 days

$
0
0

I am cleaning up a folder of daily database backup files and I need to keep the last 7 days worth of files which works fine in my code below. I would also like to keep 1 file per week for the last 5 weeks worth of files. How do I go about this??

functionCleanupDBDailyBackupFolder{Param(
    $SourceFolder,[int]$StartDaysAgo)

$fileList =Get-ChildItem $SourceFolder -Recurse|Where-Object-FilterScript{($_.LastWriteTime-le (Get-Date).AddDays($StartDaysAgo))}Write-Host $fileList

foreach ($file in $fileList){
    try {Remove-Item $file.FullName-ForceWrite-Host"Remove-Item $file"} catch {Write-Error $_}}Write-Host"Delete of files complete"}

$SourceFolder ="C:\temp\OctoTest"
$StartDaysAgo =-7CleanupDBDailyBackupFolder $SourceFolder $StartDaysAgo 


Viewing all 21975 articles
Browse latest View live