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

Debugging Powershell in Visual Studio 2017 RC

$
0
0

Hi,

I can't seem to run or debug powershell scripts in VS 2017 RC. Is this a known issue or did I not set something up properly?

Thanks!


how to schedule server reboot task on multiple servers

$
0
0

There are more than 1000 servers in the environment that needs to be rebooted on weekly basis.

need assistant to Remotely schedule a "server reboot task" on every Saturday at 12:00 am.

Changing file time

$
0
0
Is there a simple way to change date and time of a file with PowerShell - someting like "touch" in unix shell

How to remove spaces/white spaces in Environment variables.

$
0
0

Hi..

I have requirement in which to remove the spaces with the short file name from the Environment Variables

Below is my code..but it is throwing an error..please suggest.

$fso = New-Object -comobject "scripting.filesystemobject"

$shortpaths = @();

foreach ($path in $env:Path.Split(";")) 

{

    $shortpaths += $fso.GetFolder($path).ShortPath;

    }

$shortpaths -join ";";

$Reg = "Registry::HKLM\System\CurrentControlSet\Control\Session Manager\Environment"

$OldPath = (Get-ItemProperty -Path "$Reg" -Name PATH).Path

$shortpaths

Set-ItemProperty -Path "$Reg" -Name PATH –Value $shortpaths


Umeed4u

checking the Condition continuously whether the service is stopped or not

$
0
0

I have a service which takes around 30seconds to stop and start respectively. I used below code to take a pause to complete the execution of stopping the service, otherwise

$x = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") #press any key

#CODE =====

                     $service.stopservice() #takes 30 seconds
                     $up_st = Get-Service -Name $service.name -ComputerName $servername
                     Write-Host 'Wait for the service to stop then Press any key to continue'

                   if($up_st.status -eq 'stopped') {
                      Write-Host 'The Service' -f Red $up_st.name 'is' $up_st.status

                      } elseif($up_st.status -eq 'running') {

                      Write-Host 'The Service' -f Green $up_st.name 'is' $up_st.status}
                     else
                       {Write-Host 'The Service' -f Yellow $up_st.name 'is' $up_st.status ' wait for some time.'}

                      $x = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")

                     #take a pause so that service is successfully stopped before initiating startservice()
                      

                      $service.startservice()

**** IS There any other way to execute condition like this,...??? **** Where it continuously check the status of the service whether it is stopped or still StoppedPending..... and the Time it get stopped **** Gives a message The service is now stopped and then it automatically execute the startservice()

 So it will cut the human intervention to wait for 30 seconds and press any key to start the service.                                                      

Powershell $webclient.UploadFile

$
0
0

Hello Community!

I am new to powershell and i have been playing around with getting files to upload using FTP.

I have got it working and i am happy with the results but i would like to get the script to exit if the upload fails and to only move the file if its successful. 


#Files to Send
$Dir="C:\test\Output"

#ftp server
$ftp = "ftp://xxx.xxx.xxx.xxx/"
$user = "User"
$pass = "Password"
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)

foreach($item in (dir $Dir "*.csv")){"Uploading $item..."
$uri = New-Object System.Uri($ftp+$item.Name)
$webclient.UploadFile($uri, $item.FullName)

Move-Item c:\test\Output\*.csv c:\test\Output\copied

can anyone assist please?

Many Thanks in advance :-)

Kallum

Get-ADComputer : Could not load type 'System.Runtime.Diagnostics.ITraceSourceStringProvider'

$
0
0

Hi All,

I have a problem in running script, which gives details of all machines in AD when ever I try to run this particular script I am getting below error..

    
  • Get-AD Computer : Could not load type system.runtime.Diagnostics.ITraceSourceStringProvider' from Assembly 'system.servicemodel.internals', version=4.0.0.0, culture=neutral, publickkeytone=31bf3856ad4e35'

This was running earlier perfectly, can you please guide me in this.

Thanks

Vinod.










Vinod Kumar Devaragatla

Why can I set ownership with icals but not with set-acl On 2K12R2?

$
0
0

Why using get-acl -Path 'C:\Program Files' | set-acl -Path 'D:\Program Files' as an administrator tells me I am not allowed to set the ownership while using icACLs"C:\Program Files" /save Perms.txt then icACLs D:\ /restore Perms.txt works without errors ?

Also, why cannot I giveNT SERVICE\TrustedInstaller an ownership from the ACL GUI ? An error claims the object doesn't exist. (Yet the TrustedInstaller service is running)


replace operation in filename extension

$
0
0

In order to move files from one application to another I need to change extensions from the format .0123 to .123.  Throwing away the leading character is not a problem.  My newbie attempts with powershell have failed, e.g.,

dir | rename-item -NewName {$_.fullname -replace (".0",".")}

any suggestions?

How to remove string entries from host file without adding new line

$
0
0

I want to delete a line from host file upon matching the string and i am using below code..however it keeps adding new line and because of that new contents appear in middle of the host file.Kindly suggest what is wrong in below code.

(Get-Content "C:\Temp\host.txt") | 
Foreach-Object {$_ -replace "google.com", ""} | 
Set-Content "C:\Temp\host.txt"

(Get-Content "C:\Temp\host.txt") | 
Foreach-Object {$_ -replace "yahoo.com", ""} | 
Set-Content "C:\Temp\host.txt"


Umeed4u

Switching Between different networks- LAN , WIFI & 3G

$
0
0

Hi All ,

We are going to use tablets for some job functions to enable mobility and some additional functions. Tablets will be connected to LAN at office through a docking station and users  should be able to connect to Wifi or cellular network 3G when outside office .

They will even have the option for VPN .

Our concern is how to disable the use of Wifi and 3G when they are connected to LAN . Also the 3G data should not be used when connected to Wifi ( my understanding is the data will be taken from wifi once it is available atleast in mobiles , but it will be great if someone can clarify ) .


Regards Midhin


How to create a MOF file where admin can only query it

$
0
0

Hi,

         I have created a MOF file and registered the MOF in repository with mofcomp.exe. Now i can able to access the MOF from Powershell ISE using WMIC command. Can any one please let me know, how admin can only access the data from Powershell or any other source. For example, i have created a Sample.mof file and i can access the properties from powershell. Now my question is how can i restrict other users not to query the mof file without admin access. Please provide an example.

Thanks,

Siva_461

Issue with Pasting to Command Line/PowerShell

$
0
0

Hi,

We are unable to paste text from an application other than Command Prompt (CP) or Windows PowerShell (PS) to CP or PS.

  • The issue is only occurring on one of several Windows Server 2008 VMs.
  • The server has been fully patched and restarted since the issue first started to occur.
  • Copying and pasting text inside CP/PS and between other CP/PS windows works.
  • Copying and pasting text from CP/PS to other applications works.
  • UAC has never been turned on.
  • We attempted to troubleshoot via different Administrative and non-Administrative users.
  • We tried a clean boot - antivirus is not causing the issue.

Obviously performing a system recovery is an option.  We can copy and paste text to PS ISE from applications, which is an acceptable solution for PS users.  However, it is still unacceptable for CP users.

Thanks,

NuxCase



reading a variable for a certain word

$
0
0

I have a function that when run will return information letting you know if your target system needs to be rebooted.

The output if this function looks like this:

Computer           : PCName1
CBServicing        : False
WindowsUpdate      : False
CCMClientSDK       : False
PendComputerRename : False
PendFileRename     : True
PendFileRenVal     : {\??\c:\program files\dropbox\oldbinaries, , \??\c:\program files\google\update\1.3.31.5, ...}
RebootPending      : True
PSComputerName     : PCName1
RunspaceId         : c9735a17-50ed-4d81-9fbd-df417e48421c


I run this function and pipe this above information into a $Variable.   I then want to read that $Variable to see if it contains the word True.  I have tried everything I can think of and I do not get the correct results.   I have run this function against machines that need a reboot (like above) and machines that don't.  My write-host command will show up for machines that do Not have the word true.  Or it won't show up at all etc.....


$BootInfo = invoke-command "\\server1\share1\Get-PendingReboot.ps1" -computername PCName1
if ($BootInfo -eq 'True') {Write-Host "you need to reboot"}
$bootinfo


I have tried all of the following and so far I can't get consistent results.  What am I doing wrong?  

-eq '*True*'
-match '*True*'
-like '*True*'
-contains '*True*'

-eq 'True'
-match 'True'
-like 'True'
-contains 'True'


-eq "*True*"
-match "*True*"
-like "*True*"
-contains "*True*"

-eq "True"
-match "True"
-like "True"
-contains "True"

mqh7

Altering cluster share permissions - Error status 2310 (this shared resource does not exist)

$
0
0

Hi everyone,

I'm desperately after some assistance with a Powershell script. Following the necessity to implement anti-ransomware measures, we now have a script designed to set all share permissions to "deny" for a given user. The script works as file screening passes the username (in domain\username format) to Powershell on the file server; the script then retrieves all shares and sets full deny permissions on the share object for the user. Code is below:

param([string] $DomainUser)
Function DenySharePermission ([string] $ShareName, [string] $DomainUser)
{
    $domainUserSplit = $DomainUser.Split("\")
    $trusteeClass = [wmiclass] "ROOT\CIMV2:Win32_Trustee"
    $trustee = $trusteeClass.CreateInstance()
    $trustee.Domain = $domainUserSplit[0]
    $trustee.Name = $domainUserSplit[1]
    $aceClass = [wmiclass] "ROOT\CIMV2:Win32_ACE"
    $ace = $aceClass.CreateInstance()
    $ace.AccessMask = 2032127
    $ace.AceType = 1
    $ace.Trustee = $trustee
    $shss = Get-WmiObject -Class Win32_LogicalShareSecuritySetting | Where-Object {$_.Name -Eq "$ShareName"}
    $sd = Invoke-WmiMethod -InputObject $shss -Name GetSecurityDescriptor | Select -ExpandProperty Descriptor
    $sclass = [wmiclass] "ROOT\CIMV2:Win32_SecurityDescriptor"
    $newsd = $sclass.CreateInstance()
    $newsd.ControlFlags = $sd.ControlFlags
    foreach ($oace in $sd.DACL)
    {
        $newsd.DACL +=  [System.Management.ManagementBaseObject] $oace
    }
    $newsd.DACL += [System.Management.ManagementBaseObject] $ace
    $share = Get-WmiObject -Class Win32_LogicalShareSecuritySetting | Where-Object {$_.Name -Eq "$ShareName"}
    $setResult = $share.SetSecurityDescriptor($newsd)
    return $setResult.ReturnValue
}
# Let's try altering share permissions..
$DomainUser = "domain\username"
$Username = $DomainUser.Split("\")[1]
$affectedShares = Get-WmiObject -Class Win32_Share |
                    Select Name, Path, Type |
                    Where { $_.Type -eq 0 }
$affectedShares | % {
    Write-Host "Denying [$DomainUser] access to share [$($_.Name)].."
    DenySharePermission -ShareName $_.Name -DomainUser $DomainUser
}
Write-Host $affectedShares

Everything works fine until we use this in a clustered file server environment. Any shares with a__CLASS property of Win32_ClusterShare return an error code of 2130 (this shared resource does not exist) and the deny permissions are not set. Standard shares with a property value ofWin32_Share however work without issue.

Any suggestions on how to work around this would be hugely welcomed!

Thanks in advance,

Matt



Syntax for a PowerShell

Howto force a function to return a specific datatype?

$
0
0

I'm trying to create a powershell module with a function coded to return a "System.Data.DataTable".  However, the resulting datatype type from the calling program's perspective is an array if multiple rows are returned or a datarow if only a single row is returned - depending upon the SQL statement used to query the db.  This presents problems with how I process the resulting variable because the methods and properties between the two possibile returned datatypes aren't the same.  Ultimately, I'd like to be able to specify that datatype returned (i.e. a DataTable) but in the end, I'd be happy if I could just force it to always be something consistent (for example, an array).  Is there any way to do this? Snippets of my code are below:

** Calling Program **
$ResultingDataTable = Get-MyDataTable


** Function defined in the module **
Function Get-MyDataTable() {

        $SQLDataAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
        $SQLDataAdapter.SelectCommand = "Select * from Table1"
        $SQLDataAdapter.SelectCommand.Connection = $DB_CONNECTION_STRING

        # create a new DataTable
        $MyDataTable = New-Object System.Data.DataTable;
        #fill the DataTable
        $RowCount=$SQLDataAdapter.Fill($MyDataTable)
            
        return $MyDataTable
}

---

Thanks.

Who will be crowned the last PowerShell Guru of 2016!!

$
0
0

Calling all wise men! And all the Wise Ladies!

Join us and rejoice!

THE FINAL CHALLENGE OF 2016!!

December 2016 Guru, it’s time to share great skills as a TechNet Wiki article and WIN medal(s). Medals? Yes, you can share multiple articles in the same or different categories! Now, navigate to TechNet Guru Competition December 2016  to choose your categories and if it’s not listed add your content in Miscellaneous Category!

New and last month of the year 2016. It’s time for us to wave hands to say "bye bye 2016" by winning TechNet Wiki Guru medals. Let’s make this December to Remember! 

All you have to do is add an article to TechNet Wiki from the field of your interest. Something that fits into one of the categories listed on the submissions page. Copy in your own blog post, a forum solution, a white paper, or just something you had to solve for your own day’s work today.

A snippet you share can make you a December 2016 TechNet Wiki Guru in your favorite category and this is official Microsoft TechNet recognition!

HOW TO WIN

1) Please copy over your Microsoft technical solutions and revelations to TechNet Wiki.

2) Add a link to it on THIS WIKI COMPETITION PAGE (so we know you’ve contributed)

3) Every month, we will highlight your contributions, and select a “Guru of the Month” in each technology.

If you win, we will sing your praises in blogs and forums, similar to the weekly contributor awards. Once “on our radar” and making your mark, you will probably be interviewed for your greatness, and maybe eventually even invited into other inner TechNet/MSDN circles!

Winning this award in your favorite technology will help us learn the active members in each community. 

Feel free to ask any questions below.

More about TechNet Guru Awards.

You Share We Care!

TechNet Wiki Addict Chen V and ...


Thanks,


Ed Price, Azure Development Customer Program Manager (Blog,Small Basic, Wiki Ninjas, Wiki)

Answer an interesting question? Create a wiki article about it!

PowersShell system.data.SQLClient.SQLAdapter not honoring ApplicationIntent=ReadONly

$
0
0

I have a simple power Shell Script that I am using to test ApplicationIntent=Readonly Routing 

$Query="Select @@Servername"

$con="Server=AGListnerName;database=DBName; User ID=Username;Password=Password;ApplicationIntent=ReadOnly"

$da=New-Object System.Data.SQLClient.SqlAdapter($query,$con)

$dt=New-Object System.Data.DataTable

$da.fill($dt) | out-null

$dt | Format-Table -Autosize

When ever I execute it..it is just going to Primary Database.

Always On related Configuration is perfect as other .net applications and Management studio properly honors the ApplicationIntent.

However only from power shell it is not honoring. Why?

I am using PowerShell within a Server with Windows Version 2012 R2.


Thanks and Regards, Ibrahim Mehdi. MCSE-DataPlatform

Script changes config on many servers. Needs Successful/Failed output per server.

$
0
0

We are going to change IP address for Preferred DNS server on many machines. We have a script that works. It uses a list of servers in a text file and executes accordingly.

But we need an output that tells us which servers it did in fact change the config for (success), and which servers it did not change config for (failed). The more I think about it the more complicated it seems. Is there a way to achieve this?

Viewing all 21975 articles
Browse latest View live


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