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

Binary cmdlet - C# or invoke PowerShell?

$
0
0

I am currently writing a cmdlet to start/stop remote services. I am writing it in C# as a learning activity (I know I could script a PSSession etc quite easily).

I can see two approached:

  • Use a ServiceController object in C# and connect to the remote machine
  • Use a PowerShell Runspace and invoke PowerShell cmdlets (ie powershell.AddCommand("Get-Service"); )

Does anyone know which is the better approach? Does it matter? Pros/cons of either?


removing spaces in active directory attributes

$
0
0

Hi All powershell guru's I need to edit our telephoneNumber attribute in AD for all users, to remove any spaces in the numbers like "1234 567890" is there a way of doing this using powershell? I am a complete powershell newbie so go gently.

thanks in advance


User access login on Windows 2012 R2 Datacenter

$
0
0

Hello, 

I have tried the following scripts on my Window 2012 R2 servers and looks, like is working correctly:

param(
    [alias("CN")]
    $ComputerName="localhost"
)

$UserProperty = @{n="User";e={(New-Object System.Security.Principal.SecurityIdentifier $_.ReplacementStrings[1]).Translate([System.Security.Principal.NTAccount])}}
$TypeProperty = @{n="Action";e={if($_.EventID -eq 7001) {"Logon"} else {"Logoff"}}}
$TimeProperty = @{n="Time";e={$_.TimeGenerated}}
$MachineNameProperty = @{n="MachinenName";e={$_.MachineName}}

Write-Host $MachineNameProperty

foreach ($computer in $ComputerName) {
    Get-EventLog System -Source Microsoft-Windows-Winlogon -ComputerName $computer | select $UserProperty,$TypeProperty,$TimeProperty,$MachineNameProperty
}

Seems to be working fine, since it looks for EventID 7001 on the System Audit Log. 

When I try the script above on my Windows 2012 R2 Datacenter edition I do not get a response or simply, times out.

On the Windows 2012 R2 Datacenter server I did not find any EventIDs 7001 in the System Audit Log.

I have tried different combinations of UAL queries and the following application:

https://gallery.technet.microsoft.com/scriptcenter/Find-user-logon-duration-667b8c48

The application above looks for EventID (EventCode='4624' or EventCode='4647')

I can see the events on the Security Audit Log, but I always get the following response from the script:

"VERBOSE: Cannot find interactive user logon/logoff events on SCVMM within the specified time....etc"


is there a script oor a change I need to make to check user activity on Windows 2012 R2 Datacenter Edition?

Thanks

check in files to svn repository

$
0
0

Hi, I am new to working with powershell & svn. I am writing a script to update svn, add files, commit changes, log the newly committed changes from my local working copy to svn repository. Let's say all the files in CS Project A folder should check-in to trunk\CS Project A and so on.

CD C:\Program Files\TortoiseSVN\bin\ START TortoiseProc.exe /command:update /path:"https://mytortoiseSVN/trunk" /command:add /path:"C:\SourceControl\MyFolderA\*.cs*C:\SourceControl\MyFolderB\*.cs" /command:commit /path:"C:\SourceControl\MyFolderA\*.cs*C:\SourceControl\MyFolderB\*.cs" /closeonend:0

Please guide me.

Thank you.


SQLEnthusiast

Active Diretory permissions fail with Set-Acl

$
0
0

I have to run a script as an account  NOT being member of the Domain Admins group. (runs on member server W2k8 R2 being local admin - powershell runs as administrator). Everthing is working perfect accept setting ACL on OUs stopping with “Access Denied”.

If I do run the script as Domain Admin it does work perfectly => so an account’s permission problem, but:

The user account I use is able to create the OU Structure (having Full Control permission on the parent) and does show up as Owner of the newly created OUs with Full Control permissions (the OU where I have to change the ACL).

If I use the AD U&C, started as the mentioned account, it is possible to set the required permissions on that OU.

Now – what could be the reason why powershell script returns Access Denied while ADU&C doesn’t?

A similar behaviour is blogged at

http://www.bilalaslam.com/2010/12/14/powershell-workaround-for-the-security-identifier-is-not-allowed-to-be-the-owner-of-this-object-with-set-acl/ dealing with folder permissions but I can't use "(Get-Item AD:$path).GetAccessControl("Access")" as it does not work against AD.

(using Add-QADPermission is not an option)

Below the used steps out of my function and it errors at Set-ACL line

$GUID = New-Object GUID bf967a86-0de6-11d0-a285-00aa003049e2
$ID = "AD-company-team"

$Path = "OU=Computers,OU=TEST,DC=company,DC=net"
$Right = "GenericAll"
$Inherit = "Descendents"
$Type = "Allow"

$acl = (Get-Acl -Path AD:$Path -WarningAction:Stop -ErrorAction:Stop)
$sID = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList "", $ID
$acr = New-Object -TypeName System.DirectoryServices.ActiveDirectoryAccessRule -ArgumentList $sID, $Right, $Type, $GUID, $Inherit
$acl.AddAccessRule($acr)

Set-Acl -AclObject $acl -Path AD:$Path -WarningAction:Stop -ErrorAction:Stop

Set-Acl : Access is denied

At line:1 char:8

+ Set-Acl <<<<  -AclObject $acl -Path AD:$Path

    + CategoryInfo          : PermissionDenied: (OU=Computers,OU...DC=company,DC=net:String) [Set-Acl], UnauthorizedAccessException

    + FullyQualifiedErrorId : ADProvider:SetSecurityDescriptor:AccessDenied,Microsoft.PowerShell.Commands.SetAclCommand

NTFS Permission

$
0
0

Dear all,

i need to retrieve NTFS permissions on all the folders (not files) stored into a Windows Server 2012 R2 File Server.

Probably some folders exceed the 260 characters.

Do you have a Powershell script ready to use for this job ?

Thank you.

Assigning permissions to Personal Certificate on 100+ computers

$
0
0

Very new to PowerShell and was wondering if is it possible to assign permissions to the Personal Certificate on 100+ computers.  I can pull the thumbprint for the certs ok now but granting permissions is the problem now.

This is the manual way that I would like to script if possible.

Launch MMC - Add Certificate snap-in for computer account - local computer.

In the Certificates snap-in, in the console tree, expand Certificates (Local Computer), expand Personal, and navigate to the SSL certificate that you would like to use.
Right-click the certificate, select All Tasks, and select Manage Private Keys.
In the Permissions dialog box, click Add, type NETWORK SERVICE, click OK,  select Read under the Allow checkbox

I've done a lot of searches and can't seem to find anything that pertains to what I want to do that works.

Thanks!


Bruno Frisan

Send-Mailmessage with multiple attachments.

$
0
0

Hello,

I have a website that transfers files to my 2008 r2 file share.  I want to move those files to our 2007 Sharepoint server.  I use a task  batchfile to run a powershell script that sends the file as an attachment to the sharepoint site then deletes the file on the share.  It works perfect when there is only one file in the folder.  When there are two or more files, the emails fail. I have tried the cmdlet and the script I have included.   Here is the cmdlet:

 send-mailmessage -from "jgarritsen@cucompanies.com" -to "upfw@sp1.main.lan"  -subject "New Files" -Attachments "E:\Correspondent\UnderwritingSubmissionPKG\*.*" -priority  High -dno onSuccess, onFailure -smtpServer  corporate2.main.lan

And here is the script, this script fails with "exception calling send with 1 argument "failure sending mail"" which doesn't seem right because the other can send mail for one file.

function send-email(
 [string] $To
, [string] $From = "jgarritsen@cucompanies.com"
, [string] $subject = "new"
, [string] $Body = ""
, $fileAttachments
, [string] $SmtpServer = "corporate2.main.lan"
, [string] $SmtpUserName = "jgarritsen"
, [string] $SmtpPassword = "xxxxxxxx"
){
$smtp = new-object system.net.mail.smtpClient($SmtpServer)
if ($SmtpUserName -and $SmtpPassword) {
$smtp.Credentials = new-object system.net.networkcredential($smtpUserName,$SmtpPassword)
}
$mail = new-object System.Net.Mail.MailMessage
$mail.From = $From
$mail.To.Add($To)
$mail.Subject = $subject
$mail.Body = $Body
#$mail.IsBodyHtml = $true
Foreach ($a in $fileAttachments){
$attachment = New-Object System.Net.Mail.Attachment $files
$mail.Attachments.Add($attachment)
}
# send the message
$smtp.Send($mail)
}

$files = @(get-childitem "E:\Correspondent\UnderwritingSubmissionPKG\*.*")

send-email "jgarritsen@cucompanies.com"  "upfw@sp1.main.lan"  -fileAttachments $files -SmtpServer localhost

Ijust want to move multiple files!  Thank you for any insight.

Jeff


Keeping only the last part of filanmes with PowerShell

$
0
0

I have a difficult for me, request for help. I am new to PowerShell and trying to rename some files for work. I need to keep only the last 15 characters, 19 if you include the extension. Problem I am running into is that the first part of the file name has different amounts of characters.

Some look like this:

Style_Brand_Color_US_**_******_**.jpg

my goal is to only keep US_**_******_**.jpg

I tried this:

Get-ChildItem 'C:\Users\jadams\Desktop\Complete\' -Exclude US_**_******_**.jpg | rename-item -newname { $_.name.substring(19,$_.name.length-6) }

Would any one know the way to write this? I have tried all over google and most that I find have set amounts of characters. When I try those it gives back errors.

running remote commands

$
0
0
Hello, we have remoting enabled and we can run remote commands on remote machines. but what I can't seem to get working is prompting users for a remote computer and a remote command to run.  for example:  You enter machine TEST123 and then you enter gpresult /H c:\temp\results.html    My output file never gets created, not on the remote machine and not even on my local workstation.

In the code below neither Invoke-Command works.  

$ComputerName = Read-Host "Enter a remote computer name"
$RemoteCommand = Read-Host "Enter a remote command to run: Example gpupdate /force"
$RemoteCommand = $RemoteCommand -replace '"' -replace "'"
$RemoteCommand
Invoke-Command -ComputerName $ComputerName -ScriptBlock {cmd /c $RemoteCommand}
Invoke-Command -ComputerName $ComputerName -ScriptBlock {$RemoteCommand}

I have also tried New-PSSession  and that does not seem to work either.

But what Does work is if I run this command

Invoke-Command -ComputerName $ComputerName -ScriptBlock {cmd /c gpresult /H c:\temp\results.html}

how come using a variable fails?  

mqh7

Password expiry dates for all users

$
0
0

What is the best way to pull when a password will expire for all users? I would like to add on to the following script below but where $90_days = (Get-Date) .AddDays (-90) and for 160 days also I don't think it is in the correct place. 

$ouList = 'OU=Users 7,OU=BOS,DC=domain,DC=domain1,DC=com','OU=Users Laptop 7,OU=BOS,DC=domain,DC=domain1,DC=com',
'OU=Users 7,OU=DC,DC=domain,DC=domain1,DC=com','OU=Users 7 Laptop,OU=DC,DC=domain,DC=domain1,DC=com',
'OU=Users 7,OU=DEL,DC=domain,DC=domain1,DC=com','OU=Users Laptop 7,OU=DEL,DC=domain,DC=domain1,DC=com',
'OU=Users 7,OU=HBG,DC=domain,DC=domain1,DC=com','OU=Users Laptop 7,OU=HBG,DC=domain,DC=domain1,DC=com',
'OU=Users 7,OU=NRK,DC=domain,DC=domain1,DC=com','OU=Users Laptop 7,OU=NRK,DC=domain,DC=domain1,DC=com',
'OU=Users 7,OU=PHL,DC=domain,DC=domain1,DC=com','OU=Users Laptop 7,OU=PHL,DC=domain,DC=domain1,DC=com',
'OU=Users 7,OU=PIT,DC=domain,DC=domain1,DC=com','OU=Users Laptop 7,OU=PIT,DC=domain,DC=domain1,DC=com',
'OU=Users Project 7,OU=PIT,DC=domain,DC=domain1,DC=com','OU=Users 7,OU=RIC,DC=domain,DC=domain1,DC=com',
'OU=Users Laptop 7,OU=RIC,DC=domain,DC=domain1,DC=com','OU=Users 7,OU=TTN,DC=domain,DC=domain1,DC=com',
'OU=Users Laptop 7,OU=TTN,DC=domain,DC=domain1,DC=com','OU=Users 7,OU=WNY,DC=domain,DC=domain1,DC=com',
'OU=Users Laptop 7,OU=WNY,DC=domain,DC=domain1,DC=com','OU=Users Departed,OU=PIT,DC=domain,DC=domain1,DC=com'

$90_days = (Get-Date).AddDays(-90)

$ouList | ForEach {

    Get-ADUser -Filter * -properties {(passwordlastset -le $90_days)} physicaldeliveryofficename,telephonenumber,emailaddress,initials,description,passwordlastset,lockedout -SearchBase $_

} | Select @{N='First Name';E={$_.GivenName}},
            Initials,
            @{N='Last Name';E={$_.surname}},
            @{N='Username';E={$_.Samaccountname}},
            @{N='Email Address';E={$_.emailaddress}},
            @{N='Office ID';E={$_.physicaldeliveryofficename}},
            @{N='Office Phone';E={$_.telephonenumber}},
            @{N='Password Last Set';E={$_.PasswordLastSet}},
            @{N='Locked Out';E={$_.LockedOut}},
            Description|
                Export-Csv 'c:\users\eorosz\desktop\adusers.csv' -NotypeInformation


Assistance with Disabled User Group Removal PS script

$
0
0

I am trying to create a powershell script that will do two things in regards to disabled computers and users:

For Disabled Computers: It will move the disabled computers to a disable OU in Active Directory

For Disabled Users: It will move the disabled users to a disable OU in Active Directory. In addition, it should remove the disabled user from all Active Directory groups EXCEPT Domain User. 

I am having issues with the Disabled Users script in that it is trying to remove ALL groups that the person is a member of, including Domain Users. Any suggestions on ways to have the script exclude the Domain Users group?

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

Code below:

import-module ActiveDirectory

$list = Import-Csv -Path "Sites.csv"
$LogMemFilePath = "Found $(get-date -f MM-dd-yyyy).txt"
Out-File $LogMemFilePath -InputObject "Below are the computers/users that were found disabled" -Encoding utf8

#Find Disabled computer objects, write them to a file and move them to Disabled OU
$DisComp = Get-ADComputer -Filter 'enabled -eq $false' -Searchbase "OU=AF,DC=af,DC=org" | where {$_.distinguishedname -match "AF-CT|AF-NY|AF-RI"}
foreach ($Comp in $DisComp) {
$CName = Get-ADComputer -Identity $Comp | select -expand Name
Add-Content -path $LogMemFilePath $CName
Get-ADComputer $CName | Move-ADObject -TargetPath 'OU=Computers,OU=DISABLED,DC=af,DC=org'
Add-Content -path $LogMemFilePath " - MOVED!"
}


$DisUse = Get-ADUser -Filter 'enabled -eq $false' -Searchbase "OU=AF,DC=af,DC=org" | where {$_.distinguishedname -match "Users|Temp" -and $_.distinguishedname -match "AF-CT|AF-NY|AF-RI"}

#Identify Users' Site location based on AD Department field, then remove Group emberships & move users to the appropriate Disabled Users OU
foreach ($User in $DisUse) {
$SAM = Get-ADUser -Identity "$User" | select -expand samaccountname
Add-Content -path $LogMemFilePath $SAM

$Dept = Get-ADUser -Identity "$User" -Properties Department | select -expand Department
$Site = $Dept
foreach ($item in $list){
$Loc = $item.Location
If ($Dept -match $Loc){
$Site = $item.Abbr
}
}
Add-Content -path $LogMemFilePath " - $Site"

if ($Site.substring(3) -match "S") {
Get-ADPrincipalGroupMembership -Identity $SAM | % {Remove-ADPrincipalGroupMembership -Identity $SAM -MemberOf $_ -Confirm:$false}
Add-Content -path $LogMemFilePath " - Removed Memberships"
Move-ADObject $User -TargetPath "OU=$Site,OU=Users,OU=DISABLED,DC=af,DC=org"
Add-Content -path $LogMemFilePath " - Moved to $Site Disabled Users OU"
} else {
Get-ADPrincipalGroupMembership -Identity $SAM | % {Remove-ADPrincipalGroupMembership -Identity $SAM -MemberOf $_ -Confirm:$false}
Add-Content -path $LogMemFilePath " - Removed Memberships"
Move-ADObject $User -TargetPath "OU=Users,OU=DISABLED,DC=af,DC=org"
Add-Content -path $LogMemFilePath " - Couldn't determine location.  Moved to root Disabled Users OU."
}
}

Azure Rights Management Premium

$
0
0

Hello,

If E3 is ENTERPRISEPACK, then what is Azure Rights Management Premium

Exception calling "Put".... when assigning a drive letter?

$
0
0

I have a script I am writing to replace some old SMS scripting for assigning drive letters on machines when applying a new image through SCCM 2007 OSD Task Sequencing. Everything is working, and all drive letters are being assigned properly except for S:.  I receive the following error for that drive:

 Exception calling "Put" with "0" argument(s): "Not available "

The volume labels are assigned during the imaging process, and the script runs upon the first boot to the OS.  This is on Powershell v3 (we can't move higher due to some conflicts in our current OS build).  Below is the script

if(get-wmiobject win32_cdromdrive)

{$driveD = Get-WmiObject win32_volume -filter "DriveType = 5"

$driveD.driveletter = 'D:'

$driveD.put()

}

$driveC = Get-WmiObject win32_volume -Filter "Label = 'Default'"

$driveC.DriveLetter = 'C:'

$driveC.put()

$driveT = Get-WmiObject win32_volume -Filter "Label = 'Thaw'"

$driveT.DriveLetter = 'T:'

$driveT.put()

$driveS = Get-WmiObject win32_volume -Filter "Label = 'TLTDisk'"

$driveS.DriveLetter = 'S:'

$driveS.put()

Powershell to Execute a Batch file

$
0
0

Hi,

I want to execute vatch file though power shell script using the following command

 "cmd.exe" /C "C:\Program Files\SmartBear\SoapUI-5.2.1\bin\mockservicerunner.bat" -m "BasicHttpBinding_ITwoWayAsyncVoid MockService" 

it always gives me the Error

C:\Program is not recognised as an Internal or External COmmand

Can you Please hep me with this?

Thanks,

Sujith.


I need help on Creating a Powershell script to extract computer account and then add it to a group

$
0
0

I need help in fixing my Powershell script

I have used this command. It extracting all computer account starting with PC- and will add to the group.

Get-ADComputer -Filter 'SamAccountName -like "*pc-*"' |  Add-ADPrincipalGroupMembership -MemberOf One-abc-Cert

Issue:- This script need to run daily to update the group membership. It runs fine on first time because group was empty but second time it give error as some computer accounts already a member of this group

**********

WARNING: Could not add member(s) to ADGroup:
'CN=One-abc-Cert,OU=xxx,OU=yyy,OU=Machines,DC=bbb,DC=
ccc,DC=com'. Error is: 'The specified account name is already a member of
the group'.
Add-ADPrincipalGroupMembership : Could not add member(s) to one or more ADGroup

**********

Is there a way to skip the warning and error and let the script continue to add members who are not part of it

Add specific AD group to local administrator group.

$
0
0

I want to add specific user group to local administrator group, My DC is setup is asvd.mydomin.net every machine that i join to this DC have his own group under his own OU. Likevmaccount.vd.mydomin.net. i always use first name of VM to create OU and Group, I just wan that group should get added automatically via powershell script. Can below line of code help me to achieve 

function Add-LocalUser{
     Param(
        $computer=$env:computername,
        $group='Guests',
        $userdomain=$env:userdomain,
        $username=$env:username
    )
        ([ADSI]"WinNT://$computer/$Group,group").psbase.Invoke("Add",([ADSI]"WinNT://$domain/$user").path)
}



Akshay Pate

Separate items in array with comma

$
0
0

good day guys, I'm trying to separate items in my array with comma but I can't get it to work.

I've been trying to do this before with array of IPs, now with hotfix IDs.

Please help me with this. Thanks in advance!

$patch = Get-WmiObject Win32_QuickFixEngineering -ComputerName "Server1" | Sort-Object InstalledOn -Descending| Select-Object -First 5

$hotfixid = $null

$patch.hotfixid | % { $hotfixid += $_ } 

$hotfixid -join ","

I keep getting  results like this, same with IPs. KB3135445KB3134214KB3133043KB3127220KB3126593


Trying to get Detail Information from Get-Winevent -Filterxml

$
0
0

Hello, 

I am trying to get the User account for event ID 4624. 

I tried Get-Winevent -Filterhashtable, but I was not able. I got a recommendation to use FilterXML

$query = @"<QueryList><Query Id="0" Path="Security"><Select Path="Security">*[System[(EventID=4624) and TimeCreated[timediff(@SystemTime) &lt;= 604800000]]]</Select></Query></QueryList>"@

Get-Winevent -FilterXml $query

Using the query above I get the same results as the -Filterhashtable

On the EventID 4624 XML XML filter I need to get to the following value

-<EventData>
 <Data Name="SubjectUserSid">S-1-0-0</Data>
 <Data Name="SubjectUserName">-</Data>
 <Data Name="SubjectDomainName">-</Data>
 <Data Name="SubjectLogonId">0x0</Data>
 <Data Name="TargetUserSid">S-1-5-21-###################-500</Data>

 <Data Name="TargetUserName">Administrator</Data> ---> User name

Thanks and let me know if there is a book/link I should look into if it helps.

Thanks


Convert Hex to Registry String GUID

$
0
0

I've found a number of posts converting a GUID string to Hex but not the other way round. I'm looking to convert:

3baa84f2a56fb246adf5e3b9ddfd03b9

to

f284aa3b-6fa5-46b2-adf5-e3b9ddfd03b9

Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>